PageSourceSearch

https://jhasolutions.com/assets/GPSTracker-C5ePMjKc.js

js jhasolutions.com collected 2026-09-24 14:46:49 UTC 70,855 bytes, 13 lines download raw bytes

1import{b as We,u as Ue,e as pe,r as v,j as e}from"./query-vendor-Dp9tfhuh.js";import{aV as st,W as at,K as ve,aW as rt,D as it}from"./DashboardLayout-v_SFEx5M.js";import{F as nt}from"./FeatureGate-Dy39LW4d.js";import{B as P}from"./badge-CarGzGVG.js";import{x as Le,s as R,d as lt,h as F,i as O,k as $,m as E,B as D,l as ct,D as ot,p as dt,q as mt,r as ut,t as ht,L as W,S as ce,v as xt,w as Ee,y as pt,T as Ne,b as He,j as Ae,c as te,e as gt}from"./index-CgOeqv80.js";import{I as ie}from"./input-go5takyh.js";import{P as ft}from"./progress-DZ0cqMKx.js";import{S as X}from"./scroll-area-DpCy8yLM.js";import{S as ke,a as Se,b as Ce,c as Me,d as ye}from"./select-Bqpq_Ta3.js";import{T as jt,a as vt,b as we,c as le,d as Nt,e as se}from"./table-DCRDDm_8.js";import{T as yt,a as _t,b as Y,c as Z}from"./tabs-CaoVN6UB.js";import{P as wt}from"./PageHeader-DAD15sYQ.js";import{u as bt}from"./useBookings-BvtzXjMP.js";import{u as kt}from"./useListings-DS81Fvfl.js";import{u as St}from"./useMaintenanceRequests-DqDKMQug.js";import{u as Ct}from"./useOrganization-msM7McOc.js";import{u as Mt}from"./useOrganizationMembers-CpXyVLgI.js";import{u as Tt}from"./useProperties-EVF9Wa0N.js";import{u as It,i as Rt}from"./usePropertyTasks-Ci4e2Ecd.js";import{t as Dt,c as Lt,l as At,n as Ft}from"./en-US-5rFTtd83.js";import{a as Et,e as Ot}from"./formatDistanceToNow-DExfhm_y.js";import{i as Oe,a as Te}from"./isBefore-CgCj7brn.js";import{s as $e,f as z,d as $t}from"./format-Ch7dQtBq.js";import{i as K}from"./isSameDay-DKb4pGQS.js";import{p as H}from"./parseISO-k3Q1d3Py.js";import{o as Pt,u as Gt,a as zt,L as qt,S as Bt,T as Wt}from"./TrackingSettings-DdDtpO2e.js";import{R as oe}from"./route-Df-61sSI.js";import{C as Fe}from"./clock-BmPJ466V.js";import{N as ne}from"./navigation-mR6QetLo.js";import{A as Ut}from"./activity-CfnIewRD.js";import{G as Ht,W as Jt,H as Pe}from"./wifi-off-BfVaxzCl.js";import{Z as Kt}from"./zap-BKGpOGd1.js";import{u as Je,G as Ke,P as Qt,M as Ie,I as Vt,C as Yt,a as Zt}from"./esm-BHLdRt99.js";import{G as Qe,a as Ve,b as Ye}from"./googleMaps-CnGBkgZD.js";import{s as Xt}from"./startOfMonth-CR-gPZr_.js";import{C as es}from"./car-D3b4R55M.js";import{D as ts}from"./download-B3iahoQg.js";import{T as ss}from"./textarea-BSB7eVDL.js";import{M as ee}from"./map-pin-B63H-upO.js";import{C as as}from"./circle-pSWMGBM_.js";import{U as Re}from"./users-9XO_ctWv.js";import{P as rs}from"./plus-CYnN_kFu.js";import{C as Ge}from"./calendar-days-Cbs598pa.js";import{C as _e}from"./clipboard-list-FvLR_NG8.js";import{P as De}from"./play-CVPqrcf1.js";import{S as is}from"./square-MsVDU0g-.js";import{C as ns}from"./circle-check-CLkepror.js";import{R as ls}from"./refresh-ccw-BR8hKK-Q.js";import{W as cs}from"./wrench-CDdvezGQ.js";import{i as os}from"./isToday-C3mvRkZe.js";import"./ui-vendor-DW4RoVmg.js";import"./react-vendor-DfslLuwi.js";import"./use-mobile-CojsY12Z.js";import"./separator-DP1KYTpB.js";import"./sheet-bqYui_d3.js";import"./skeleton-U7PtyM3w.js";import"./tooltip-CSLOX5Ak.js";import"./Logo-Dty4QCqO.js";import"./building-2-BMIYvzwG.js";import"./message-square-B81woyC-.js";import"./file-text-CuOiBfSM.js";import"./credit-card-B-2xvAjl.js";import"./panel-top-BGv8mfXo.js";import"./mail-CObWevXE.js";import"./log-out-SS0g6Uak.js";import"./bell-D0vTOuek.js";import"./check-check-2zE5w8gN.js";import"./LanguageSwitcher-DHMsopEY.js";import"./dropdown-menu-BeZf8kFV.js";import"./chevron-right-BdUdHP_I.js";import"./check-v4vwqlB-.js";import"./languages-DOZFgZ9Q.js";import"./message-circle-BYe5rrWz.js";import"./arrow-down-CIVFAk8G.js";import"./arrow-left-BmX2tYO6.js";import"./arrow-right-left-DF8EQ874.js";import"./arrow-right-ksEPM703.js";import"./banknote-CdW1Jv9F.js";import"./bed-B88pYHvh.js";import"./list-ordered-hB6RbGtG.js";import"./book-open-check-DYZCLGLv.js";import"./book-open-D0Y1dKqG.js";import"./brain-BohJitgU.js";import"./building-DasY5zOg.js";import"./calculator-ByooPTmb.js";import"./calendar-D4RFJDPY.js";import"./landmark-BwZdzl4J.js";import"./chart-no-axes-column-increasing-C6Bh1bTG.js";import"./chart-pie-7jztI-xg.js";import"./chevron-down-Bm2Y15mk.js";import"./chevron-left-DCDYd6CA.js";import"./chevron-up-DVBQQKr7.js";import"./circle-check-big-CQmmVCDK.js";import"./message-square-text-W-2xUYbe.js";import"./circle-help-Cpt-rFJF.js";import"./circle-x-CMEjdGNX.js";import"./clipboard-check-Cvc1fMv5.js";import"./clipboard-viWVwQwk.js";import"./copy-BEDU18te.js";import"./database-kv95WpLa.js";import"./dollar-sign-D0iC4HrG.js";import"./zoom-out-zrJfLdu9.js";import"./external-link-BIGsQXrz.js";import"./twitter-BaxQU1X8.js";import"./file-chart-column-increasing-DEN9Rsed.js";import"./file-check-cM7E4NaC.js";import"./file-spreadsheet-ZK-q7Zgc.js";import"./filter-Bs-PYMIY.js";import"./folder-open-DFmVGiUq.js";import"./tree-pine-CouWAS-6.js";import"./globe-C_UDh3Yp.js";import"./video-DaS8rS9K.js";import"./hammer-691LkvTd.js";import"./heart-Dv9Odr8c.js";import"./hotel-C1w3GOsr.js";import"./house-5R4LHGOP.js";import"./image-plus-xT5L-tET.js";import"./image-CayqqQKD.js";import"./infinity-wq20aEtI.js";import"./key-round-Dh3U7Shh.js";import"./pen-tool-_n2hBO7N.js";import"./keyboard-CSqz3mRU.js";import"./layers-D0VRol72.js";import"./lightbulb-DlRuWc33.js";import"./list-checks-coQAK2sr.js";import"./list-BJoWfKXY.js";import"./lock-B0M9hAnN.js";import"./map-pinned-B-fJbXg-.js";import"./map-C8rxfYCS.js";import"./maximize-2-CZGGiq67.js";import"./maximize-DHDDLx00.js";import"./menu-DuKtMQlr.js";import"./minus-04ztrfH_.js";import"./mouse-pointer-click-Bc_ivnf4.js";import"./mouse-CUCnDlYq.js";import"./pause-DWfQPC5O.js";import"./pencil-d1bR18nI.js";import"./ruler-BoWqmUga.js";import"./phone-I9m-09C5.js";import"./printer-DjW2gpx9.js";
1import"./rocket-DxjHbFsp.js";import"./rotate-ccw-CE2HFYnH.js";import"./rotate-cw-n6J_8Piu.js";import"./save-DF6x0jpO.js";import"./scale-CZXGlUhc.js";import"./search-Dx_o7OfG.js";import"./send-Blf9Z7mq.js";import"./share-2-sKHj2vjO.js";import"./square-plus-Dp1sCmj5.js";import"./skip-forward-eFm9X_4U.js";import"./smartphone-CBjqwShe.js";import"./square-check-big-DF0dFzei.js";import"./square-pen-Bg7uj701.js";import"./star-DlIZz9Im.js";import"./trash-2-DAqLpVlV.js";import"./trending-down-COltpy2W.js";import"./trending-up-CRE5UWZg.js";import"./upload-55xlfOPi.js";import"./user-check-XkucE5f8.js";import"./user-DV5oCLCs.js";import"./volume-2-DTT7l7C1.js";import"./volume-x-BBMkTIRp.js";import"./wallet-_cnDvlQk.js";import"./workflow-Bfwpj-zP.js";import"./useIsRTL-D_a81cVb.js";import"./UpgradePrompt-BocCWdcP.js";import"./usePaddle-CWtEfRja.js";import"./paddleJs-D6vCOr2I.js";import"./chart-vendor-BoynbIzZ.js";import"./index-BdQq_4o_.js";import"./addDays-DdzlNAKv.js";import"./_commonjs-dynamic-modules-TDtrdbi3.js";function Ze(t,s){const n=+Dt(t);return Lt(t,n+s)}function ae(t,s){return Ze(t,s*At)}function ze(t,s){return Ze(t,s*Ft)}function ds(t){const{organizationId:s,assignedTo:n}=t,{toast:m}=Le(),l=We(),{data:x,isLoading:a,error:f}=Ue({queryKey:["route-assignments",s,n],queryFn:async()=>{if(!s)return[];let y=R.from("route_assignments").select("*").eq("organization_id",s).order("priority",{ascending:!1}).order("scheduled_date",{ascending:!0});n&&(y=y.eq("assigned_to",n));const{data:c,error:h}=await y;if(h)throw h;return c||[]},enabled:!!s}),N=async y=>{const{data:c,error:h}=await R.from("route_waypoints").select("*").eq("route_id",y).order("sequence_order",{ascending:!0});if(h)throw h;return c||[]},d=pe({mutationFn:async y=>{const{data:{user:c}}=await R.auth.getUser();if(!c)throw new Error("Not authenticated");const{waypoints:h,...C}=y,{data:T,error:L}=await R.from("route_assignments").insert({...C,organization_id:s,assigned_by:c.id}).select().single();if(L)throw L;if(h&&h.length>0){const r=h.map((o,M)=>({...o,route_id:T.id,sequence_order:o.sequence_order??M})),{error:_}=await R.from("route_waypoints").insert(r);if(_)throw _}return T},onSuccess:()=>{l.invalidateQueries({queryKey:["route-assignments"]}),m({title:"Route created",description:"Route assignment has been created successfully."})},onError:y=>{m({title:"Error creating route",description:y.message,variant:"destructive"})}}),p=pe({mutationFn:async({routeId:y,status:c})=>{const h={status:c};c==="in_progress"?h.started_at=new Date().toISOString():c==="completed"&&(h.completed_at=new Date().toISOString());const{data:C,error:T}=await R.from("route_assignments").update(h).eq("id",y).select().single();if(T)throw T;return C},onSuccess:()=>{l.invalidateQueries({queryKey:["route-assignments"]}),m({title:"Route updated"})},onError:y=>{m({title:"Error updating route",description:y.message,variant:"destructive"})}}),b=pe({mutationFn:async({waypointId:y,status:c})=>{const h={status:c};(c==="arrived"||c==="completed")&&(h.actual_arrival=new Date().toISOString());const{data:C,error:T}=await R.from("route_waypoints").update(h).eq("id",y).select().single();if(T)throw T;return C},onSuccess:()=>{l.invalidateQueries({queryKey:["route-waypoints"]}),m({title:"Waypoint updated"})},onError:y=>{m({title:"Error updating waypoint",description:y.message,variant:"destructive"})}}),i=pe({mutationFn:async y=>{const{error:c}=await R.from("route_assignments").update({status:"cancelled"}).eq("id",y);if(c)throw c},onSuccess:()=>{l.invalidateQueries({queryKey:["route-assignments"]}),m({title:"Route cancelled"})},onError:y=>{m({title:"Error cancelling route",description:y.message,variant:"destructive"})}});return{routes:x||[],isLoading:a,error:f,fetchWaypoints:N,createRoute:d,updateRouteStatus:p,updateWaypointStatus:b,deleteRoute:i}}const de={urgent:0,high:1,medium:2,low:3},ms={pending:"pending",in_progress:"in_progress",completed:"completed",cancelled:"cancelled"},us={cleaning:"cleaning",inspection:"inspection",maintenance:"maintenance",renovation:"maintenance"},hs={low:"low",medium:"medium",high:"high",urgent:"urgent"};function xs(t){if(!t)return null;if(t instanceof Date)return t;const s=H(t);return Number.isNaN(s.getTime())?null:s}function re(t,s,n=0){const m=typeof t=="string"?H(t):new Date(t);return m.setHours(s,n,0,0),m}function ge(t){return t?t.formatted_address||[t.address,t.city,t.state,t.zip_code].filter(
1Boolean).join(", "):null}function fe(t){if(t.status==="completed"||t.status==="cancelled")return"on_track";const s=new Date,n=t.latestFinishAt||t.dueAt,m=(n.getTime()-s.getTime())/(1e3*60*60);return Te(n,s)?"overdue":t.priority==="urgent"||m<=4?"at_risk":m<=24?"due_soon":"on_track"}function Xe(t,s){if(t.lat==null||t.lng==null||s.lat==null||s.lng==null)return 0;const n=6371,m=(s.lat-t.lat)*Math.PI/180,l=(s.lng-t.lng)*Math.PI/180,x=t.lat*Math.PI/180,a=s.lat*Math.PI/180,f=Math.sin(m/2)*Math.sin(m/2)+Math.cos(x)*Math.cos(a)*Math.sin(l/2)*Math.sin(l/2);return n*2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f))}function ps(t){const s=t.filter(l=>l.hasLocation&&l.status!=="completed"&&l.status!=="cancelled").sort((l,x)=>{const a=de[l.priority]-de[x.priority];return a!==0?a:l.dueAt.getTime()-x.dueAt.getTime()});if(s.length<=2)return s;const n=[],m=[...s];for(n.push(m.shift());m.length>0;){const l=n[n.length-1];let x=0,a=Number.POSITIVE_INFINITY;m.forEach((f,N)=>{const d=Xe(l,f),p=Math.max(0,$t(f.dueAt,l.dueAt))*8,b=de[f.priority]*4,i=d+p+b;i<a&&(a=i,x=N)}),n.push(m.splice(x,1)[0])}return n}function gs(t,s){const n=ps(t),m=n.reduce((d,p,b)=>b===0?d:d+Xe(n[b-1],p),0),l=Math.round(m/45*60),x=n.reduce((d,p)=>d+p.estimatedDurationMinutes,0),a=n.filter(d=>d.priority==="urgent").length,f=t.filter(d=>!d.hasLocation).length,N=Math.max(1,Math.round(100-f*12-a*4-Math.max(0,l-180)/4));return{date:s,jobs:n,totalStops:n.length,estimatedDriveMinutes:l,estimatedWorkMinutes:x,estimatedTotalMinutes:l+x,estimatedDistanceKm:Math.round(m*10)/10,urgentCount:a,missingLocationCount:f,routeScore:N}}function fs(t){return Ue({queryKey:["field-route-waypoints",t],queryFn:async()=>{if(!t)return[];const{data:s,error:n}=await R.from("route_waypoints").select("*").eq("route_id",t).order("sequence_order",{ascending:!0});if(n)throw n;return s||[]},enabled:!!t})}function js(t=new Date){const{user:s}=lt(),{toast:n}=Le(),m=We(),{organization:l}=Ct(),x=Mt(),{properties:a,isLoading:f}=Tt(),{listings:N,isLoading:d}=kt(),{bookings:p,isLoading:b}=bt(),{tasks:i,isLoading:y,startTask:c,completeTask:h}=It(),{requests:C,isLoading:T,updateRequest:L}=St(),r=ds({organizationId:(l==null?void 0:l.id)||null}),_=v.useMemo(()=>new Map(a.map(k=>[k.id,k])),[a]),o=v.useMemo(()=>new Map(N.map(k=>[k.id,k])),[N]),M=v.useMemo(()=>{var B;const k=x.data||[];return!s||k.some(g=>g.member_id===s.id)?k:[{id:s.id,member_id:s.id,full_name:((B=s.user_metadata)==null?void 0:B.full_name)||s.email||"Current user",email:s.email||"",role:"field_agent",is_active:!0,joined_at:new Date().toISOString()},...k]},[x.data,s]),I=v.useMemo(()=>{const k=new Date,q=ae(Et(t),24*14),B=[];return p.forEach(g=>{if(g.status==="cancelled")return;const j=o.get(g.listing_id),w=j?_.get(j.property_id):void 0,S=re(g.check_out,11),J=re(g.check_in,15);if(Oe(S,$e(k))&&Te(S,q)){const U=p.some(xe=>xe.id===g.id||xe.status==="cancelled"||xe.listing_id!==g.listing_id?!1:K(H(xe.check_in),H(g.check_out))),A=U||K(S,k)?"urgent":"high",V=U?re(g.check_out,14):ae(S,6),he={id:`booking-cleaning-${g.id}`,source:"booking",sourceId:g.id,type:"cleaning",status:g.status==="completed"?"completed":"pending",priority:A,title:`${(w==null?void 0:w.name)||(j==null?void 0:j.title)||"Property"} turnover cleaning`,description:g.notes,propertyId:(j==null?void 0:j.property_id)||null,propertyName:(w==null?void 0:w.name)||(j==null?void 0:j.title)||"Unlinked booking",address:ge(w),lat:(w==null?void 0:w.latitude)??null,lng:(w==null?void 0:w.longitude)??null,dueAt:S,earliestStartAt:S,latestFinishAt:V,estimatedDurationMinutes:U?120:90,relatedBooking:g,hasLocation:!!(w!=null&&w.latitude)&&!!(w!=null&&w.longitude)};B.push({...he,risk:fe(he)})}
1if(Oe(J,$e(k))&&Te(J,q)){const U=re(g.check_in,13),A=K(U,k)?"high":"medium",V={id:`booking-inspection-${g.id}`,source:"booking",sourceId:g.id,type:"inspection",status:g.status==="completed"?"completed":"pending",priority:A,title:`${(w==null?void 0:w.name)||(j==null?void 0:j.title)||"Property"} pre-arrival inspection`,description:`Guest: ${g.guest_name}`,propertyId:(j==null?void 0:j.property_id)||null,propertyName:(w==null?void 0:w.name)||(j==null?void 0:j.title)||"Unlinked booking",address:ge(w),lat:(w==null?void 0:w.latitude)??null,lng:(w==null?void 0:w.longitude)??null,dueAt:U,earliestStartAt:re(g.check_in,9),latestFinishAt:J,estimatedDurationMinutes:30,relatedBooking:g,hasLocation:!!(w!=null&&w.latitude)&&!!(w!=null&&w.longitude)};B.push({...V,risk:fe(V)})}}),i.forEach(g=>{if(g.status==="cancelled")return;const j=_.get(g.property_id),w=xs(g.due_date)||ae(new Date,8),S={id:`task-${g.id}`,source:"task",sourceId:g.id,type:us[g.task_type]||"general",status:ms[g.status],priority:hs[g.priority],title:g.title,description:g.description,propertyId:g.property_id,propertyName:(j==null?void 0:j.name)||"Unlinked property",address:ge(j),lat:g.latitude??(j==null?void 0:j.latitude)??null,lng:g.longitude??(j==null?void 0:j.longitude)??null,dueAt:w,earliestStartAt:null,latestFinishAt:w,estimatedDurationMinutes:g.estimated_duration_minutes||60,assignedTo:g.assigned_to,relatedTask:g,hasLocation:!!(g.latitude??(j==null?void 0:j.latitude))&&!!(g.longitude??(j==null?void 0:j.longitude))};B.push({...S,risk:fe(S)})}),C.forEach(g=>{if(["completed","cancelled","closed"].includes(g.status))return;const j=_.get(g.property_id),w=(g.priority||"medium").toLowerCase(),S=["low","medium","high","urgent"].includes(w)?w:"medium",J=g.priority==="urgent"?ae(new Date,4):ae(new Date(g.created_at),48),U={id:`maintenance-${g.id}`,source:"maintenance",sourceId:g.id,type:"maintenance",status:g.status==="in_progress"?"in_progress":"pending",priority:S,title:g.title||`Maintenance: ${g.category||"request"}`,description:g.description,propertyId:g.property_id,propertyName:(j==null?void 0:j.name)||"Unlinked property",address:ge(j),lat:(j==null?void 0:j.latitude)??null,lng:(j==null?void 0:j.longitude)??null,dueAt:J,earliestStartAt:null,latestFinishAt:J,estimatedDurationMinutes:75,assignedTo:g.assigned_to,relatedMaintenance:g,hasLocation:!!(j!=null&&j.latitude)&&!!(j!=null&&j.longitude)};B.push({...U,risk:fe(U)})}),B.sort((g,j)=>{const w=+(g.status==="completed")-+(j.status==="completed");if(w!==0)return w;const S=de[g.priority]-de[j.priority];return S!==0?S:g.dueAt.getTime()-j.dueAt.getTime()})},[p,o,_,C,t,i]),G=v.useMemo(()=>I.filter(k=>K(k.dueAt,t)),[I,t]),ue=v.useMemo(()=>gs(G,t),[G,t]),u=v.useMemo(()=>{const k=new Date,q=ae(k,24),B=I.filter(S=>K(S.dueAt,k)&&S.status!=="completed").length,g=I.filter(S=>K(S.dueAt,q)&&S.status!=="completed").length,j=r.routes.filter(S=>S.status==="in_progress").length,w=r.routes.filter(S=>S.status==="pending").length;return{dueToday:B,dueTomorrow:g,activeJobs:I.filter(S=>S.status==="pending"||S.status==="in_progress").length,completedToday:I.filter(S=>S.status==="completed"&&K(S.dueAt,k)).length,atRisk:I.filter(S=>S.risk==="at_risk"||S.risk==="overdue").length,missingLocations:I.filter(S=>!S.hasLocation).length,routeReady:I.filter(S=>S.hasLocation&&S.status!=="completed"&&S.status!=="cancelled").length,activeRoutes:j,pendingRoutes:w}},[I,r.routes]),Q=async(k,q,B)=>{if(!(l!=null&&l.id)||!(s!=null&&s.id))return n({title:"Route not created",description:"Organization or user context is missing.",variant:"destructive"}),null;if(k.jobs.length===0)return n({title:"No route-ready jobs",description:"Add property coordinates before creating this route.",variant:"destructive"}),null;const g=q||s.id,j=z(k.date,"MMM d"),w=B||`JHA Field Route - ${j}`;let S=re(k.date,9);const J=k.jobs.map((A,V)=>{S=V===0?S:ze(S,Math.max(5,Math.round(k.estimatedDriveMinutes/Math.max(1,k.jobs.length))));const he={property_id:A.propertyId,sequence_order:V+1,lat:A.lat,lng:A.lng,name:A.propertyName,address:A.address,status:"pending",estimated_arrival:S.toISOString(),actual_arrival:null,duration_minutes:A.estimatedDurationMinutes,notes:`${A.type.toUpperCase()}: ${A.title}
2Source: ${A.source}:${A.sourceId}`};return S=ze(S,A.estimatedDurationMinutes),he}),U=await r.createRoute.mutateAsync({organization_id:l.id,assigned_to:g,assigned_by:s.id,name:w,description:`${k.totalStops} stops | ${k.estimatedDistanceKm} km | ${k.estimatedTotalMinutes} min`,status:"pending",priority:k.urgentCount>0?10:5,scheduled_date:z(k.date,"yyyy-MM-dd"),estimated_duration_minutes:k.estimatedTotalMinutes,actual_duration_minutes:null,started_at:null,completed_at:null,total_distance_km:k.estimatedDistanceKm,notes:JSON.stringify({generatedBy:"field_ops_smart_dispatch",score:k.routeScore,jobIds:k.jobs.map(A=>A.id)}
2),waypoints:J});return m.invalidateQueries({queryKey:["route-assignments"]}),m.invalidateQueries({queryKey:["field-route-waypoints"]}),U},tt=async(k,q)=>{if(k.source==="task"&&k.relatedTask){q==="in_progress"?await c.mutateAsync(k.relatedTask.id):q==="completed"&&await h.mutateAsync({id:k.relatedTask.id});return}if(k.source==="maintenance"&&k.relatedMaintenance){await L.mutateAsync({id:k.relatedMaintenance.id,status:q==="completed"?"completed":q,completed_at:q==="completed"?new Date().toISOString():k.relatedMaintenance.completed_at});return}n({title:"Virtual booking job",description:"Booking-generated jobs are completed through the related task or route stop for now."})};return{organization:l,teamMembers:M,jobs:I,jobsForSelectedDate:G,metrics:u,smartRoutePlan:ue,routes:r.routes,isLoading:f||d||b||y||T||r.isLoading||x.isLoading,createRouteFromPlan:Q,updateJobStatus:tt,updateRouteStatus:r.updateRouteStatus,updateWaypointStatus:r.updateWaypointStatus,deleteRoute:r.deleteRoute}}const vs=({stats:t})=>{const s=l=>{const x=Math.floor(l/3600),a=Math.floor(l%3600/60),f=l%60;return x>0?`${x}:${a.toString().padStart(2,"0")}:${f.toString().padStart(2,"0")}`:`${a}:${f.toString().padStart(2,"0")}`},n=l=>l<1?`${Math.round(l*1e3)} m`:`${l.toFixed(2)} km`,m=l=>l===null?"-- km/h":`${l.toFixed(1)} km/h`;return e.jsxs(F,{children:[e.jsx(O,{className:"pb-2",children:e.jsx($,{className:"text-base sm:text-lg",children:"Active Session"})}),e.jsx(E,{className:"space-y-3",children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 sm:gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx(oe,{className:"h-4 w-4 sm:h-5 sm:w-5 text-primary shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] sm:text-xs text-muted-foreground",children:"Distance"}),e.jsx("div",{className:"text-base sm:text-lg font-semibold truncate",children:n(t.totalDistance)})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx(Fe,{className:"h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] sm:text-xs text-muted-foreground",children:"Duration"}),e.jsx("div",{className:"text-base sm:text-lg font-semibold truncate",children:s(t.totalDuration)})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx(ne,{className:"h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] sm:text-xs text-muted-foreground",children:"Points"}),e.jsx("div",{className:"text-base sm:text-lg font-semibold",children:t.pointsCount})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx(Ut,{className:"h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] sm:text-xs text-muted-foreground",children:"Speed"}),e.jsx("div",{className:"text-base sm:text-lg font-semibold truncate",children:m(t.currentSpeed)})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx(Ht,{className:"h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] sm:text-xs text-muted-foreground",children:"Avg"}),e.jsx("div",{className:"text-base sm:text-lg font-semibold truncate",children:m(t.averageSpeed)})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[e.jsx(Kt,{className:"h-4 w-4 sm:h-5 sm:w-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[10px] sm:text-xs text-muted-foreground",children:"Max"}),e.jsx("div",{className:"text-base sm:text-lg font-semibold truncate",children:m(t.maxSpeed)})]})]})]})})]})},Ns={width:"100%",height:"100%"},ys={lat:25.7617,lng:-80.1918},_s={urgent:"#DC2626",high:"#F97316",medium:"#2563EB",low:"#64748B"};function ws(t){t.lat==null||t.lng==null||window.open(`https://www.google.com/maps/dir/?api=1&destination=${t.lat},${t.lng}`,"_blank")}function bs({jobs:t,routePlan:s,height:n="560px"}){const[m,l]=v.useState(null),{isLoaded:x,loadError:a}=Je({id:Qe,googleMapsApiKey:Ve,libraries:Ye}),f=v.useMemo(()=>t.filter(b=>b.lat!=null&&b.lng!=null),[t]),N=f.find(b=>b.id===m)||null,d=v.useMemo(()=>{const b=(s==null?void 0:s.jobs.filter(y=>y.lat!=null&&y.lng!=null))||[],i=b.length>0?b:f;return i.length===0?ys:{lat:i.reduce((y,c)=>y+(c.lat||0),0)/i.length,lng:i.reduce((y,c)=>y+(c.lng||0),0)/i.length}},[s==null?void 0:s.jobs,f]),p=v.useMemo(()=>((s==null?void 0:s.jobs)||[]).filter(b=>b.lat!=null&&b.lng!=null).map(b=>({lat:b.lat,lng:b.lng})),[s==null?void 0:s.jobs]);return a?e.jsx("div",{className:"flex items-center justify-center rounded-lg border bg-muted/40 p-6 text-center",style:{height:n},children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Map could not load"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Check the Google Maps API key and domain restrictions."})]})}):x?e.jsx("div",{className:"overflow-hidden rounded-lg border bg-background",style:{height:n},children:e.jsxs(Ke,{mapContainerStyle:Ns,center:d,zoom:f.length>1?11:13,options:{streetViewControl:!1,mapTypeControl:!1,fullscreenControl:!0,clickableIcons:!1,styles:[{featureType:"poi",elementType:"labels",stylers:[{visibility:"off"}]}]},children:[p.length>1&&e.jsx(Qt,{path:p,options:{strokeColor:"#111827",strokeOpacity:.78,strokeWeight:4}}),f.map(b=>{const i=(s==null?void 0:s.jobs.findIndex(y=>y.id===b.id))??-1;return e.jsx(Ie,{position:{lat:b.lat,lng:b.lng},label:i>=0?{text:String(i+1),color:"#FFFFFF",fontWeight:"700"}:void 0,icon:{path:google.maps.SymbolPath.CIRCLE,fillColor:_s[b.priority],fillOpacity:1,strokeColor:"#FFFFFF",strokeWeight:2,scale:i>=0?13:10},title:b.title,onClick:()=>l(b.id)},b.id)}),N&&N.lat!=null&&N.lng!=null&&e.jsx(Vt,{position:{lat:N.lat,lng:N.lng},onCloseClick:()=>l(null),children:e.jsxs("div",{className:"min-w-56 max-w-72 space-y-2 p-1",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:N.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:N.propertyName})]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsx(P,{variant:"secondary",className:"capitalize",children:N.type}),e.jsx(P,{variant:N.priority==="urgent"?"destructive":"outline",className:"capitalize",children:N.priority})]}),N.address&&e.jsx("div",{className:"text-xs text-muted-foreground",children:N.address}),e.jsxs(D,{size:"sm",className:"h-8 w-full",onClick:()=>ws(N),children:[e.jsx(ne,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"ml-2",children:"Navigate"})]})]})})]})}):e.jsx("div",{className:"flex items-center justify-center rounded-lg border bg-muted/40",style:{height:n},children:e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading map..."})})}const ks=({sessions:t,month:s=new Date})=>{const n=Xt(s),m=Ot(s),l=t.filter(N=>{const d=new Date(N.started_at);return d>=n&&d<=m}),x=l.reduce((N,d)=>N+(d.total_distance_km||0),0),a=l.reduce((N,d)=>N+(d.duration_minutes||0),0),f=()=>{const N=["Date","Session","Distance (km)","Duration (min)","Notes"],d=l.map(c=>{var h,C;return[z(new Date(c.started_at),"yyyy-MM-dd"),c.title,((h=c.total_distance_km)==null?void 0:h.toFixed(2))||"0.00",((C=c.duration_minutes)==null?void 0:C.toString())||"0",c.notes||""]});d.push(["","TOTAL",x.toFixed(2),a.toString(),""]);const p=[N.join(","),...d.map(c=>c.map(h=>`"${h}"`).join(","))].join(`
3`),b=new Blob([p],{type:"text/csv"}),i=URL.createObjectURL(b),y=document.createElement("a");y.href=i,y.download=`mileage-report-${z(s,"yyyy-MM")}.csv`,y.click(),URL.revokeObjectURL(i)};return e.jsxs(F,{children:[e.jsx(O,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs($,{className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-5 w-5"}),"Mileage Report"]}),e.jsx(ct,{children:z(s,"MMMM yyyy")})]}),e.jsxs(D,{onClick:f,size:"sm",variant:"outline",children:[e.jsx(ts,{className:"h-4 w-4 mr-2"}),"Export"]})]})}),e.jsxs(E,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Distance"}),e.jsxs("p",{className:"text-2xl font-bold",children:[x.toFixed(2)," km"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Sessions"}),e.jsx("p",{className:"text-2xl font-bold",children:l.length})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Time"}),e.jsxs("p",{className:"text-2xl font-bold",children:[Math.floor(a/60),"h ",a%60,"m"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Avg Distance/Session"}),e.jsxs("p",{className:"text-2xl font-bold",children:[l.length>0?(x/l.length).toFixed(1):"0.0"," ","km"]})]})]}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("h4",{className:"text-sm font-semibold mb-2",children:"Recent Sessions"}),e.jsx("div",{className:"space-y-2",children:l.slice(0,5).map(N=>{var d;return e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:N.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:z(new Date(N.started_at),"MMM d, yyyy")})]}),e.jsxs("p",{className:"font-semibold",children:[(d=N.total_distance_km)==null?void 0:d.toFixed(1)," km"]})]},N.id)})})]})]})]})},Ss={width:"100%",height:"100%"},Cs={lat:41.3275,lng:19.8187},Ms=({teamMembers:t,geofences:s=[],currentPosition:n,center:m,zoom:l=14,onMapClick:x,showGeofences:a=!0})=>{const{isLoaded:f,loadError:N}
3=Je({id:Qe,googleMapsApiKey:Ve,libraries:Ye}),d=v.useMemo(()=>m||n||(t.length>0?{lat:t[0].lat,lng:t[0].lng}:Cs),[m,n,t]);return N?e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-muted p-4 text-center",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:"Map could not load"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Check the Google Maps API key and allowed domains."})]})}):f?e.jsxs(Ke,{mapContainerStyle:Ss,center:d,zoom:l,onClick:p=>{x&&p.latLng&&x(p.latLng.lat(),p.latLng.lng())},options:{streetViewControl:!1,mapTypeControl:!0,fullscreenControl:!1,styles:[{featureType:"poi",elementType:"labels",stylers:[{visibility:"off"}]}]},children:[n&&e.jsx(Ie,{position:n,icon:{path:google.maps.SymbolPath.CIRCLE,scale:12,fillColor:"#22C55E",fillOpacity:1,strokeColor:"#FFFFFF",strokeWeight:3},title:"You",zIndex:100}),t.map(p=>e.jsx(Ie,{position:{lat:p.lat,lng:p.lng},icon:{path:p.heading!==null?google.maps.SymbolPath.FORWARD_CLOSED_ARROW:google.maps.SymbolPath.CIRCLE,scale:p.heading!==null?6:10,fillColor:p.color,fillOpacity:p.isOnline?1:.5,strokeColor:"#FFFFFF",strokeWeight:2,rotation:p.heading||0},title:`${p.name}${p.speed?` - ${Math.round(p.speed*3.6)} km/h`:""}`,zIndex:50},p.id)),a&&s.map(p=>p.fence_type==="circle"&&p.center_lat&&p.center_lng&&p.radius_meters?e.jsx(Yt,{center:{lat:p.center_lat,lng:p.center_lng},radius:p.radius_meters,options:{fillColor:p.color,fillOpacity:.2,strokeColor:p.color,strokeOpacity:.8,strokeWeight:2}},p.id):p.fence_type==="polygon"&&p.polygon_coords&&p.polygon_coords.length>=3?e.jsx(Zt,{paths:p.polygon_coords,options:{fillColor:p.color,fillOpacity:.2,strokeColor:p.color,strokeOpacity:.8,strokeWeight:2}},p.id):null)]}):e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-muted",children:e.jsx("div",{className:"text-muted-foreground",children:"Loading map..."})})},Ts=[{value:"#3B82F6",label:"Blue"},{value:"#22C55E",label:"Green"},{value:"#EF4444",label:"Red"},{value:"#F97316",label:"Orange"},{value:"#8B5CF6",label:"Purple"},{value:"#EC4899",label:"Pink"}],Is=({open:t,onOpenChange:s,onSubmit:n,initialPosition:m})=>{const[l,x]=v.useState(!1),[a,f]=v.useState({name:"",description:"",fence_type:"circle",center_lat:(m==null?void 0:m.lat)||0,center_lng:(m==null?void 0:m.lng)||0,radius_meters:100,color:"#3B82F6",trigger_on_enter:!0,trigger_on_exit:!0,trigger_on_dwell:!1,dwell_time_seconds:300}),N=async d=>{d.preventDefault(),x(!0);try{await n(a),s(!1),f({name:"",description:"",fence_type:"circle",center_lat:0,center_lng:0,radius_meters:100,color:"#3B82F6",trigger_on_enter:!0,trigger_on_exit:!0,trigger_on_dwell:!1,dwell_time_seconds:300})}finally{x(!1)}};return e.jsx(ot,{open:t,onOpenChange:s,children:e.jsxs(dt,{className:"sm:max-w-[500px]",children:[e.jsxs(mt,{children:[e.jsxs(ut,{className:"flex items-center gap-2",children:[e.jsx(ee,{className:"h-5 w-5"}),"Create Geofence"]}),e.jsx(ht,{children:"Define an area to receive alerts when team members enter or exit."})]}),e.jsxs("form",{onSubmit:N,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{htmlFor:"name",children:"Name"}),e.jsx(ie,{id:"name",value:a.name,onChange:d=>f({...a,name:d.target.value}),placeholder:"e.g., Downtown Office Area",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ss,{id:"description",value:a.description,onChange:d=>f({...a,description:d.target.value}),placeholder:"Additional notes about this geofence",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{children:"Type"}),e.jsxs(ke,{value:a.fence_type,onValueChange:d=>f({...a,fence_type:d}),children:[e.jsx(Se,{children:e.jsx(Ce,{})}),e.jsxs(Me,{children:[e.jsx(ye,{value:"circle",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(as,{className:"h-4 w-4"}),"Circle"]})}),e.jsx(ye,{value:"polygon",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(st,{className:"h-4 w-4"}),"Polygon"]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{children:"Color"}),e.jsxs(ke,{value:a.color,onValueChange:d=>f({...a,color:d}),children:[e.jsx(Se,{children:e.jsx(Ce,{})}),e.jsx(Me,{children:Ts.map(d=>e.jsx(ye,{value:d.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 roun
3ded-full",style:{backgroundColor:d.value}}),d.label]})},d.value))})]})]})]}),a.fence_type==="circle"&&e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{htmlFor:"lat",children:"Latitude"}),e.jsx(ie,{id:"lat",type:"number",step:"any",value:a.center_lat,onChange:d=>f({...a,center_lat:parseFloat(d.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{htmlFor:"lng",children:"Longitude"}),e.jsx(ie,{id:"lng",type:"number",step:"any",value:a.center_lng,onChange:d=>f({...a,center_lng:parseFloat(d.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(W,{htmlFor:"radius",children:"Radius (m)"}),e.jsx(ie,{id:"radius",type:"number",min:"10",max:"10000",value:a.radius_meters,onChange:d=>f({...a,radius_meters:parseInt(d.target.value)||100}),required:!0})]})]}),e.jsxs("div",{className:"space-y-3 border rounded-lg p-4",children:[e.jsx(W,{className:"text-sm font-medium",children:"Triggers"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(W,{htmlFor:"trigger_enter",className:"text-sm font-normal",children:"Alert on enter"}),e.jsx(ce,{id:"trigger_enter",checked:a.trigger_on_enter,onCheckedChange:d=>f({...a,trigger_on_enter:d})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(W,{htmlFor:"trigger_exit",className:"text-sm font-normal",children:"Alert on exit"}),e.jsx(ce,{id:"trigger_exit",checked:a.trigger_on_exit,onCheckedChange:d=>f({...a,trigger_on_exit:d})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(W,{htmlFor:"trigger_dwell",className:"text-sm font-normal",children:"Alert on dwell"}),e.jsx(ce,{id:"trigger_dwell",checked:a.trigger_on_dwell,onCheckedChange:d=>f({...a,trigger_on_dwell:d})})]}),a.trigger_on_dwell&&e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(W,{htmlFor:"dwell_time",children:"Dwell time (seconds)"}),e.jsx(ie,{id:"dwell_time",type:"number",min:"60",max:"3600",value:a.dwell_time_seconds,onChange:d=>f({...a,dwell_time_seconds:parseInt(d.target.value)||300})})]})]}),e.jsxs(xt,{children:[e.jsx(D,{type:"button",variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(D,{type:"submit",disabled:l||!a.name,children:l?"Creating...":"Create Geofence"})]})]})]})})},Rs=(t={})=>{const{updateInterval:s=3e3,highAccuracy:n=!0,enableHeartbeat:m=!0,organizationId:l=null,sessionId:x=null}=t,[a,f]=v.useState(null),[N,d]=v.useState(!1),[p,b]=v.useState(null),[i,y]=v.useState(navigator.onLine),c=v.useRef(null),h=v.useRef(null),C=v.useRef(null),T=v.useRef(null);v.useEffect(()=>{const o=()=>y(!0),M=()=>y(!1);return window.addEventListener("online",o),window.addEventListener("offline",M),()=>{window.removeEventListener("online",o),window.removeEventListener("offline",M)}},[]);const L=v.useCallback(async o=>{if(!i){await Pt.savePoint({session_id:x||"",user_id:"",lat:o.lat,lng:o.lng,accuracy:o.accuracy,speed:o.speed,timestamp:o.timestamp.toISOString(),synced:!1});return}try{const{data:{user:M}}=await R.auth.getUser();if(!M)return;const I={user_id:M.id,organization_id:l,session_id:x,lat:o.lat,lng:o.lng,accuracy:o.accuracy,speed:o.speed,heading:o.heading,altitude:o.altitude,is_online:!0,last_heartbeat:new Date().toISOString(),updated_at:new Date().toISOString()};if(T.current)await R.from("live_locations").update(I).eq("id",T.current);else{const{data:G}=await R.from("live_locations").insert({...I,created_at:new Date().toISOString()}).select("id").single();G&&(T.current=G.id)}}catch(M){console.error("Failed to update live location:",M)}},[i,l,x]),r=v.useCallback(()=>{if(c.current===null){if(!navigator.geolocation){b("Geolocation is not supported by this browser");return}d(!0),b(null),c.current=navigator.geolocation.watchPosition(o=>{const M={lat:o.coords.latitude,lng:o.coords.longitude,accuracy:o.coords.accuracy,speed:o.coords.speed,heading:o.coords.heading,altitude:o.coords.altitude,timestamp:new Date(o.timestamp)};f(M);const I=new Date;(!h.current||I.getTime()-h.current.getTime()>=s)&&(h.current=I,L(M))},o=>{const M=o.code===o.PERMISSION_DENIED?"Location permission denied. Please enable location access.":o.code===o.POSITION_UNAVAILABLE?"Location information unavailable.":o.code===o.TIMEOUT?"Location request timed out.":o.message;b(M),d(!1),c.current!==null&&(navigator.geolocation.clearWatch(c.current),c.current=null),C.current&&(clearInterval(C.current),C.current=null),console.error("Geolocation error:",o)},{enableHighAccuracy:n,maximumAge:1e3,timeout:1e4}),m&&(C.current=setInterval(async()=>{T.current&&i&&await R.from("live_locations").update({last_heartbeat:new Date().toISOString(),is_online:!0}).eq("id",T.current)},1e4))}},[n,s,m,L,i]),_=v.useCallback(async()=>{c.current!==null&&(navigator.geolocation.clearWatch(c.current),c.current=null),C.current&&(clearInterval(C.current),C.current=null),T.current&&i&&await R.from("live_locations").update({is_online:!1}).eq("id",T.current),d(!1),T.current=null},[i]);return v.useEffect(()=>()=>{c.current!==null&&navigator.geolocation.clearWatch(c.current),C.current&&clearInterval(C.current)},[]),{position:a,isTracking:N,error:p,isOnline:i,startTracking:r,stopTracking:_}},qe=["#EF4444","#F97316","#EAB308","#22C55E","#06B6D4","#3B82F6","#8B5CF6","#EC4899"],Ds=t=>{const{organizationId:s,enabled:n=!0,staleThresholdMs:m=3e4}=t,[l,x]=v.useState([]),[a,f]=v.useState(!0),N=v.useRef(null),d=v.useRef(new Map),p=v.useCallback(i=>{if(d.current.has(i))return d.current.get(i);const y=d.current.size%qe.length,c=qe[y];return d.current.set(i,c),c},[]),b=v.useCallback(async()=>
3{if(!s){x([]),f(!1);return}try{const{data:{user:i}}=await R.auth.getUser();if(!i)return;const y=new Date(Date.now()-m).toISOString(),{data:c,error:h}=await R.from("live_locations").select(`
4          id,
5          user_id,
6          lat,
7          lng,
8          accuracy,
9          speed,
10          heading,
11          is_online,
12          last_heartbeat
13        `).eq("organization_id",s).eq("is_online",!0).gte("last_heartbeat",y).neq("user_id",i.id);if(h)throw h;const C=(c==null?void 0:c.map(_=>_.user_id))||[],{data:T}=await R.from("profiles").select("id, full_name").in("id",C),L=new Map((T==null?void 0:T.map(_=>[_.id,_.full_name]))||[]),r=(c==null?void 0:c.map(_=>({id:_.id,userId:_.user_id,name:L.get(_.user_id)||"Team Member",lat:_.lat,lng:_.lng,accuracy:_.accuracy,speed:_.speed,heading:_.heading,isOnline:_.is_online,lastHeartbeat:new Date(_.last_heartbeat),color:p(_.user_id)})))||[];x(r)}catch(i){console.error("Error fetching team locations:",i)}finally{f(!1)}},[s,m,p]);return v.useEffect(()=>{if(!(!n||!s))return b(),N.current=R.channel(`team-locations-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"live_locations",filter:`organization_id=eq.${s}`},async i=>{const{data:{user:y}}=await R.auth.getUser();if(!y)return;if(i.eventType==="DELETE"){x(r=>r.filter(_=>_.id!==i.old.id));return}const c=i.new;if(c.user_id===y.id)return;const h=new Date(c.last_heartbeat).getTime();if(Date.now()-h>m)return;let C="Team Member";const{data:T}=await R.from("profiles").select("full_name").eq("id",c.user_id).single();T&&(C=T.full_name||C);const L={id:c.id,userId:c.user_id,name:C,lat:c.lat,lng:c.lng,accuracy:c.accuracy,speed:c.speed,heading:c.heading,isOnline:c.is_online,lastHeartbeat:new Date(c.last_heartbeat),color:p(c.user_id)};x(r=>r.find(o=>o.id===c.id)?r.map(o=>o.id===c.id?L:o):[...r,L])}).subscribe(),()=>{N.current&&(N.current.unsubscribe(),N.current=null)}},[n,s,b,m,p]),v.useEffect(()=>{if(!n)return;const i=setInterval(()=>{const y=Date.now();x(c=>c.filter(h=>y-h.lastHeartbeat.getTime()<m))},1e4);return()=>clearInterval(i)},[n,m]),{teamMembers:l,isLoading:a,refreshTeam:b}},Ls=(t,s,n,m)=>{const x=(n-t)*Math.PI/180,a=(m-s)*Math.PI/180,f=Math.sin(x/2)*Math.sin(x/2)+Math.cos(t*Math.PI/180)*Math.cos(n*Math.PI/180)*Math.sin(a/2)*Math.sin(a/2);return 6371e3*(2*Math.atan2(Math.sqrt(f),Math.sqrt(1-f)))},As=(t,s)=>{let n=!1;const m=t.lng,l=t.lat;for(let x=0,a=s.length-1;x<s.length;a=x++){const f=s[x].lng,N=s[x].lat,d=s[a].lng,p=s[a].lat;N>l!=p>l&&m<(d-f)*(l-N)/(p-N)+f&&(n=!n)}return n},Fs=(t,s={})=>{const{organizationId:n=null,enabled:m=!0,checkInterval:l=5e3}=s,{toast:x}=Le(),[a,f]=v.useState([]),[N,d]=v.useState([]),[p,b]=v.useState(!0),i=v.useRef(new Map),y=v.useRef(null),c=v.useCallback(async()=>{if(!n){f([]),b(!1);return}try{const{data:r,error:_}=await R.from("geofences").select("*").eq("organization_id",n).eq("is_active",!0);if(_)throw _;const o=(r||[]).map(M=>({...M,fence_type:M.fence_type,polygon_coords:M.polygon_coords,auto_actions:M.auto_actions}));f(o)}catch(r){console.error("Error fetching geofences:",r)}finally{b(!1)}},[n]);v.useEffect(()=>{c()},[c]);const h=v.useCallback((r,_)=>r.fence_type==="circle"?!r.center_lat||!r.center_lng||!r.radius_meters?!1:Ls(_.lat,_.lng,r.center_lat,r.center_lng)<=r.radius_meters:r.fence_type==="polygon"?!r.polygon_coords||r.polygon_coords.length<3?!1:As(_,r.polygon_coords):!1,[]),C=v.useCallback(async(r,_,o)=>{try{const{data:{user:M}}=await R.auth.getUser();if(!M)return;await R.from("geofence_events").insert({geofence_id:r,user_id:M.id,event_type:_,lat:o.lat,lng:o.lng,triggered_at:new Date().toISOString()})}catch(M){console.error("Error logging geofence event:",M)}},[]);v.useEffect(()=>{if(!m||!t||a.length===0)return;const r=new Date;if(y.current&&r.getTime()-y.current.getTime()<l)return;y.current=r;const _=[];for(const o of a){const M=h(o,t),I=i.current.get(o.id);if(M){if(_.push(o.id),!I||!I.isInside)o.trigger_on_enter&&(x({title:`Entered: ${o.name}`,description:o.description||"You entered a geofenced area"}),C(o.id,"enter",t)),i.current.set(o.id,{geofenceId:o.id,isInside:!0,enteredAt:r,dwellTriggered:!1});else if(o.trigger_on_dwell&&I.enteredAt&&!I.dwellTriggered){const G=r.getTime()-I.enteredAt.getTime();G>=o.dwell_time_seconds*1e3&&(x({title:`Dwell: ${o.name}`,description:`You've been in this area for ${Math.round(G/6e4)} minutes`}),C(o.id,"dwell",t),i.current.set(o.id,{...I,dwellTriggered:!0}))}}else I!=null&&I.isInside&&(o.trigger_on_exit&&(x({title:`Exited: ${o.name}`,description:o.description||"You left a geofenced area"}),C(o.id,"exit",t)),i.current.delete(o.id))}d(_)},[t,a,m,l,h,C,x]);const T=v.useCallback(async r=>{try{const{data:{user:_}}
13=await R.auth.getUser();if(!_)throw new Error("Not authenticated");const{data:o,error:M}=await R.from("geofences").insert({name:r.name||"",description:r.description,fence_type:r.fence_type||"circle",center_lat:r.center_lat,center_lng:r.center_lng,radius_meters:r.radius_meters,polygon_coords:r.polygon_coords,color:r.color||"#3B82F6",trigger_on_enter:r.trigger_on_enter??!0,trigger_on_exit:r.trigger_on_exit??!0,trigger_on_dwell:r.trigger_on_dwell??!1,dwell_time_seconds:r.dwell_time_seconds||300,linked_property_ids:r.linked_property_ids||[],organization_id:n,created_by:_.id}).select().single();if(M)throw M;const I={...o,fence_type:o.fence_type,polygon_coords:o.polygon_coords,auto_actions:o.auto_actions};return f(G=>[...G,I]),x({title:"Geofence created",description:`${o.name} has been created`}),I}catch(_){throw x({title:"Error creating geofence",description:_.message,variant:"destructive"}),_}},[n,x]),L=v.useCallback(async r=>{try{const{error:_}=await R.from("geofences").update({is_active:!1}).eq("id",r);if(_)throw _;f(o=>o.filter(M=>M.id!==r)),i.current.delete(r),x({title:"Geofence deleted"})}catch(_){x({title:"Error deleting geofence",description:_.message,variant:"destructive"})}},[x]);return{geofences:a,activeGeofences:N,isLoading:p,createGeofence:T,deleteGeofence:L,refreshGeofences:c}},Es=({organizationId:t,sessionId:s})=>{const[n,m]=v.useState(!1),[l,x]=v.useState(null),{position:a,isTracking:f,isOnline:N,error:d,startTracking:p,stopTracking:b}=Rs({organizationId:t,sessionId:s,updateInterval:3e3}),{teamMembers:i,isLoading:y}=Ds({organizationId:t,enabled:f}),{geofences:c,activeGeofences:h,createGeofence:C}=Fs(a?{lat:a.lat,lng:a.lng}:null,{organizationId:t}),T=(r,_)=>{x({lat:r,lng:_}),m(!0)},L=async r=>{await C(r)};return e.jsxs("div",{className:"flex flex-col h-full gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Team Tracking"}),e.jsx(P,{variant:N?"default":"secondary",className:"ml-2",children:N?e.jsxs(e.Fragment,{children:[e.jsx(at,{className:"h-3 w-3 mr-1"})," Online"]}):e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-3 w-3 mr-1"})," Offline"]})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(D,{variant:"outline",size:"sm",onClick:()=>m(!0),children:[e.jsx(rs,{className:"h-4 w-4 mr-1"}),"Geofence"]}),f?e.jsxs(D,{variant:"destructive",size:"sm",onClick:b,children:[e.jsx(ve,{className:"h-4 w-4 mr-1"}),"Stop Sharing"]}):e.jsxs(D,{size:"sm",onClick:p,children:[e.jsx(ne,{className:"h-4 w-4 mr-1"}),"Share Location"]})]})]}),d&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:d}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4 flex-1 min-h-0",children:[e.jsx("div",{className:"lg:col-span-3 rounded-lg overflow-hidden border bg-card min-h-[400px]",children:e.jsx(Ms,{teamMembers:i.map(r=>({id:r.id,userId:r.userId,name:r.name,lat:r.lat,lng:r.lng,speed:r.speed,heading:r.heading,isOnline:r.isOnline,color:r.color})),geofences:c,currentPosition:a?{lat:a.lat,lng:a.lng}:null,onMapClick:T,showGeofences:!0})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(F,{children:[e.jsx(O,{className:"py-3",children:e.jsxs($,{className:"text-sm flex items-center gap-2",children:[e.jsx(Re,{className:"h-4 w-4"}),"Team (",i.length,")"]})}),e.jsx(E,{className:"py-0 pb-3",children:e.jsx(X,{className:"h-[200px]",children:y?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading..."}):i.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No team members online"}):e.jsx("div",{className:"space-y-2",children:i.map(r=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted/50",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:r.color}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:r.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r.speed?`${Math.round(r.
13speed*3.6)} km/h`:"Stationary"})]}),e.jsx(P,{variant:r.isOnline?"default":"secondary",className:"text-xs",children:r.isOnline?"Live":"Away"})]},r.id))})})})]}),e.jsxs(F,{children:[e.jsx(O,{className:"py-3",children:e.jsxs($,{className:"text-sm flex items-center gap-2",children:[e.jsx(ee,{className:"h-4 w-4"}),"Geofences (",c.length,")"]})}),e.jsx(E,{className:"py-0 pb-3",children:e.jsx(X,{className:"h-[150px]",children:c.length===0?e.jsx("div",{className:"text-sm text-muted-foreground",children:"No geofences created"}):e.jsx("div",{className:"space-y-2",children:c.map(r=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted/50",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:r.color}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:r.name}),e.jsxs("div",{className:"text-xs text-muted-foreground capitalize",children:[r.fence_type,r.radius_meters&&` • ${r.radius_meters}m`]})]}),h.includes(r.id)&&e.jsx(P,{variant:"default",className:"text-xs",children:"Inside"})]},r.id))})})})]}),a&&e.jsxs(F,{children:[e.jsx(O,{className:"py-3",children:e.jsxs($,{className:"text-sm flex items-center gap-2",children:[e.jsx(ne,{className:"h-4 w-4"}),"Your Position"]})}),e.jsx(E,{className:"py-0 pb-3",children:e.jsxs("div",{className:"text-xs space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Lat: ",a.lat.toFixed(6)]}),e.jsxs("div",{children:["Lng: ",a.lng.toFixed(6)]}),a.accuracy&&e.jsxs("div",{children:["Accuracy: ±",Math.round(a.accuracy),"m"]}),a.speed&&e.jsxs("div",{children:["Speed: ",Math.round(a.speed*3.6)," km/h"]})]})})]})]})]}),e.jsx(Is,{open:n,onOpenChange:m,onSubmit:L,initialPosition:l})]})};function me(t){const s=Math.floor(t/60),n=t%60;return s===0?`${n}m`:n===0?`${s}h`:`${s}h ${n}m`}function Os(t){return os(t)?`Today, ${z(t,"h:mm a")}`:Rt(t)?`Tomorrow, ${z(t,"h:mm a")}`:z(t,"MMM d, h:mm a")}function $s(t){return z(t,"yyyy-MM-dd")}function Ps(t){switch(t){case"cleaning":return Ae;case"inspection":return gt;case"maintenance":return cs;case"turnover":return ls;default:return _e}}function et(t){switch(t){case"urgent":return"bg-destructive text-destructive-foreground border-destructive";case"high":return"bg-orange-500/10 text-orange-700 border-orange-500/30";case"medium":return"bg-blue-500/10 text-blue-700 border-blue-500/30";default:return"bg-slate-500/10 text-slate-700 border-slate-500/30"}}function Gs(t){switch(t){case"overdue":return"bg-destructive text-destructive-foreground";case"at_risk":return"bg-orange-500 text-white";case"due_soon":return"bg-yellow-500/15 text-yellow-700 border-yellow-500/30";default:return""}}function zs(t){t.lat==null||t.lng==null||window.open(`https://www.google.com/maps/dir/?api=1&destination=${t.lat},${t.lng}`,"_blank")}const qs=[{label:"Checkout cleaning",enabled:!0,detail:"Create cleaning stops from confirmed check-outs"},{label:"Pre-arrival inspection",enabled:!0,detail:"Create readiness checks before check-ins"},{label:"Urgent maintenance",enabled:!0,detail:"Escalate high-priority maintenance into routes"},{label:"Same-day turnover priority",enabled:!0,detail:"Prioritize properties with same-day check-in"}];function je({label:t,value:s,detail:n,icon:m,tone:l="default"}){return e.jsx(F,{className:te(l==="danger"&&"border-destructive/40",l==="warning"&&"border-orange-500/40"),children:e.jsx(E,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:t}),e.jsx("p",{className:"mt-1 text-2xl font-semibold tracking-tight",children:s}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:n})]}),e.jsx("div",{className:te("rounded-md border p-2",l==="danger"&&"border-destructive/30 bg-destructive/10 text-destructive",l==="warning"&&"border-orange-500/30 bg-
13orange-500/10 text-orange-700",l==="success"&&"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:e.jsx(m,{className:"h-4 w-4"})})]})})})}function be({job:t,compact:s,onStatusChange:n}){const m=Ps(t.type);return e.jsx("div",{className:te("rounded-lg border bg-background p-3",t.risk==="overdue"&&"border-destructive/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-md border bg-muted/40 p-2",children:e.jsx(m,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate font-medium",children:t.title}),e.jsx(P,{variant:"outline",className:te("capitalize",et(t.priority)),children:t.priority}),t.risk!=="on_track"&&e.jsx(P,{variant:"outline",className:te("capitalize",Gs(t.risk)),children:t.risk.replace("_"," ")})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ee,{className:"h-3 w-3"}),t.propertyName]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fe,{className:"h-3 w-3"}),Os(t.dueAt)]}),e.jsx("span",{className:"capitalize",children:t.type}),e.jsx("span",{children:me(t.estimatedDurationMinutes)})]}),!s&&t.description&&e.jsx("p",{className:"mt-2 line-clamp-2 text-sm text-muted-foreground",children:t.description}),!t.hasLocation&&e.jsxs("p",{className:"mt-2 flex items-center gap-1 text-xs text-destructive",children:[e.jsx(Ne,{className:"h-3 w-3"}),"Property needs latitude and longitude before it can be routed."]})]}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.hasLocation&&e.jsx(D,{size:"icon",variant:"outline",className:"h-9 w-9",onClick:()=>zs(t),children:e.jsx(ne,{className:"h-4 w-4"})}),n&&t.status==="pending"&&e.jsxs(D,{size:"sm",variant:"secondary",onClick:()=>n(t,"in_progress"),children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-1 hidden sm:inline",children:"Start"})]}),n&&t.status==="in_progress"&&e.jsxs(D,{size:"sm",onClick:()=>n(t,"completed"),children:[e.jsx(ns,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-1 hidden sm:inline",children:"Done"})]})]})]})})}function Be({plan:t,assignee:s,onAssigneeChange:n,members:m,onCreateRoute:l,isCreating:x}){return e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(oe,{className:"h-5 w-5"}),"Smart Route"]}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[t.totalStops," stops"]}),e.jsxs("span",{children:[t.estimatedDistanceKm," km"]}),e.jsx("span",{children:me(t.estimatedTotalMinutes)}),e.jsxs("span",{children:[t.urgentCount," urgent"]})]})]}),e.jsx("div",{className:"w-full sm:w-56",children:e.jsxs(ke,{value:s,onValueChange:n,children:[e.jsx(Se,{children:e.jsx(Ce,{placeholder:"Assign route"})}),e.jsx(Me,{children:m.map(a=>e.jsx(ye,{value:a.member_id,children:a.full_name||a.email||a.role},a.member_id))})]})})]})}),e.jsxs(E,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Route confidence"}),e.jsxs("span",{className:"font-medium",children:[t.routeScore,"%"]})]}),e.jsx(ft,{value:t.routeScore,className:"h-2"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-sm",children:[e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-muted-foreground",children:"Drive"}),e.jsx("p",{className:"font-semibold",children:me(t.estimatedDriveMinutes)})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-muted-foreground",children:"Work"}),e.jsx("p",{className:"font-semibold",children:me(t.estimatedWorkMinutes)})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-muted-foreground",children:"Missing GPS"}),e.jsx("p",{className:"font-semibold",children:t.missingLocationCount})]})]}),e.jsx(X,{className:"h-72 pr-2",children:e.jsxs("div",{className:"space-y-2",children:[t.jobs.map((a,f)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-md border bg-muted/20 p-3",children:[e.jsx(P,{variant:"secondary",className:"mt-0.5 h-6 w-6 justify-center rounded-full p-0",children:f+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:a.propertyName}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:a.title})]}),e.jsx(P,{variant:"outline",className:te("capitalize",et(a.priority)),children:a.priority})]},a.id)),t.jobs.length===0&&e.jsx("div",{className:"rounded-md border border-dashed p-8 text-center text-sm text-muted-foreground",children:"No route-ready jobs for this date."})]})}),e.jsxs(D,{className:"w-full",disabled:t.jobs.length===0||x,onClick:l,children:[x?e.jsx(He,{className:"h-4 w-4 animate-spin"}):e.jsx(Ae,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Create Smart Route"})]})]})]})}function Bs(){var M,I,G,ue;const[t,s]=v.useState(new Date),[n,m]=v.useState(),[l,x]=v.useState(null),[a,f]=v.useState(!1),[N,d]=v.useState(!0),[p,b]=v.useState(null),i=js(t),y=fs(l),c=Gt(),h=zt();v.useEffect(()=>{navigator.geolocation&&navigator.geolocation.getCurrentPosition(u=>{b({lat:u.coords.latitude,lng:u.coords.longitude})},()=>{},{enableHighAccuracy:!0,timeout:1e4,maximumAge:3e4})},[]);const C=v.useMemo(()=>i.routes.find(u=>u.id===l)||null,[i.routes,l]),T=v.useMemo(()=>h.liveTrackPoints.map(u=>({...u,note:null})),[h.liveTrackPoints]),L=h.currentPosition?{lat:h.currentPosition.lat,lng:h.currentPosition.lng}:p,r=v.useMemo(()=>i.routes.filter(u=>u.scheduled_date?K(H(u.scheduled_date),t):!0),[i.routes,t]),_=v.useMemo(()=>i.jobs.filter(u=>u.risk==="at_risk"||u.risk==="overdue").slice(0,6),[i.jobs]),o=async()=>{f(!0);try{const u=await i.createRouteFromPlan(i.smartRoutePlan,n);u!=null&&u.id&&x(u.id)}finally{f(!1)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(wt,{title:"Field Ops",subtitle:"Smart dispatch, routes, and live property-service tracking",icon:e.jsx(oe,{className:"h-5 w-5"}),actions:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ie,{type:"date",className:"h-9 w-40",value:$s(t),onChange:u=>s(H(u.target.value))}),e.jsxs(D,{variant:"outline",size:"sm",onClick:()=>window.location.href="/gps-tracker/fullscreen",children:[e.jsx(ve,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2 hidden sm:inline",children:"Live View"})]})]})}),i.isLoading?e.jsx("div",{className:"flex min-h-[420px] items-center justify-center",children:e.jsx(Ee,{})}):e.jsxs(yt,{defaultValue:"today",className:"space-y-6",children:[e.jsxs(_t,{className:"flex w-full flex-wrap justify-start gap-1 h-auto",children:[e.jsxs(Y,{value:"today",children:[e.jsx(Ge,{className:"h-4 w-4"}),"Today"]}),e.jsxs(Y,{value:"routes",children:[e.jsx(oe,{className:"h-4 w-4"}),"Routes"]}),e.jsxs(Y,{value:"map",children:[e.jsx(ee,{className:"h-4 w-4"}),"Map"]}),e.jsxs(Y,{value:"jobs",children:[e.jsx(_e,{className:"h-4 w-4"}),"Jobs"]}),e.jsxs(Y,{value:"staff",children:[e.jsx(Re,{className:"h-4 w-4"}),"Staff"]}),e.jsxs(Y,{value:"history",children:[e.jsx(Pe,{className:"h-4 w-4"}),"History"]}),e.jsxs(Y,{value:"settings",children:[e.jsx(pt,{className:"h-4 w-4"}),"Settings"]})]}),e.jsxs(Z,{value:"today",className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(je,{label:"Due today",value:i.metrics.dueToday,detail:`${i.metrics.dueTomorrow} due tomorrow`,icon:Ge}),e.jsx(je,{label:"At risk",value:i.metrics.atRisk,detail:"Late or urgent jobs",icon:Ne,tone
13:i.metrics.atRisk>0?"danger":"success"}),e.jsx(je,{label:"Route ready",value:i.metrics.routeReady,detail:`${i.metrics.missingLocations} missing GPS`,icon:ee,tone:i.metrics.missingLocations>0?"warning":"default"}),e.jsx(je,{label:"Active routes",value:i.metrics.activeRoutes,detail:`${i.metrics.pendingRoutes} waiting to start`,icon:ve})]}),e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[minmax(0,1fr)_420px]",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(_e,{className:"h-5 w-5"}),"Dispatch Queue"]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ce,{checked:N,onCheckedChange:d}),e.jsx("span",{className:"text-muted-foreground",children:"Auto-plan"})]})]})}),e.jsx(E,{children:e.jsx(X,{className:"h-[470px] pr-2",children:e.jsxs("div",{className:"space-y-3",children:[i.jobsForSelectedDate.map(u=>e.jsx(be,{job:u,onStatusChange:i.updateJobStatus},u.id)),i.jobsForSelectedDate.length===0&&e.jsxs("div",{className:"rounded-lg border border-dashed p-12 text-center text-sm text-muted-foreground",children:["No field jobs for ",z(t,"MMM d"),"."]})]})})})]}),e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Ne,{className:"h-5 w-5"}),"Risk Board"]})}),e.jsx(E,{children:e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[_.map(u=>e.jsx(be,{job:u,compact:!0,onStatusChange:i.updateJobStatus},u.id)),_.length===0&&e.jsx("div",{className:"rounded-lg border border-dashed p-8 text-sm text-muted-foreground",children:"No urgent route risks right now."})]})})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(Be,{plan:i.smartRoutePlan,assignee:n,onAssigneeChange:m,members:i.teamMembers,onCreateRoute:o,isCreating:a}),e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ee,{className:"h-5 w-5"}),"Live Location"]}),e.jsx(P,{variant:h.isTracking?"default":h.isPaused?"secondary":"outline",children:h.isTracking?"Tracking":h.isPaused?"Paused":"Idle"})]})}),e.jsxs(E,{className:"space-y-3",children:[e.jsx("div",{className:"h-[320px] overflow-hidden rounded-lg border bg-muted",children:e.jsx(qt,{currentPosition:L,points:T,isTracking:h.isTracking,heading:(M=h.currentPosition)==null?void 0:M.heading,accuracy:(I=h.currentPosition)==null?void 0:I.accuracy,showUserLocation:!!L})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsxs("p",{className:"font-medium text-foreground",children:[h.stats.totalDistance.toFixed(2)," km"]}),e.jsx("p",{children:"Distance"})]}),e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsx("p",{className:"font-medium text-foreground",children:T.length}),e.jsx("p",{children:"Points"})]}),e.jsxs("div",{className:"rounded-md border p-2",children:[e.jsx("p",{className:"font-medium text-foreground",children:(G=h.currentPosition)!=null&&G.accuracy?`${Math.round(h.currentPosition.accuracy)} m`:"--"}),e.jsx("p",{children:"Accuracy"})]})]})]})]}),e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ve,{className:"h-5 w-5"}),"Field Session"]})}),e.jsxs(E,{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsx(Bt,{status:h.syncStatus,pendingCount:h.pendingPoints,syncedCount:h.stats.pointsCount})}),h.error&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Ne,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("p",{children:h.error})]}),(h.isTracking||h.isPaused)&&e.jsx(vs,{stats:h.stats}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:h.trackingState==="idle"?e.jsxs(D,{className:"col-span-2",onClick:()=>h.startTracking("Field Ops Shift"),children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Start Shift"})]}):e.jsxs(e.Fragment,{children:[h.isTracking?e.jsxs(D,{variant:"outline",onClick:h.pauseTracking,children:[e.jsx(Fe,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Pause"})]}):e.jsxs(D,{onClick:h.resumeTracking,children:[e.jsx(De,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Resume"})]}),e.jsxs(D,{variant:"destructive",onClick:()=>h.stopTracking(),children:[e.jsx(is,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"End"})]})]})})]})]})]})]})]}),e.jsx(Z,{value:"routes",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[minmax(0,1fr)_420px]",children:[e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(oe,{className:"h-5 w-5"}),"Route Assignments"]}),e.jsxs(D,{onClick:o,disabled:i.smartRoutePlan.jobs.length===0||a,children:[a?e.jsx(He,{className:"h-4 w-4 animate-spin"}):e.jsx(Ae,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Create Route"})]})]})}),e.jsx(E,{children:e.jsx("div",{className:"overflow-hidden rounded-lg border",children:e.jsxs(jt,{children:[e.jsx(vt,{children:e.jsxs(we,{children:[e.jsx(le,{children:"Route"}),e.jsx(le,{children:"Status"}),e.jsx(le,{children:"Schedule"}),e.jsx(le,{children:"ETA"}),e.jsx(le,{className:"text-right",children:"Actions"})]})}),e.jsxs(Nt,{children:[r.map(u=>e.jsxs(we,{className:te("cursor-pointer",l===u.id&&"bg-muted/70"),onClick:()=>x(u.id),children:[e.jsxs(se,{children:[e.jsx("div",{className:"font-medium",children:u.name}),u.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:u.description})]}),e.jsx(se,{children:e.jsx(P,{variant:u.status==="completed"?"default":u.status==="in_progress"?"secondary":"outline",className:"capitalize",children:u.status.replace("_"," ")})}
13),e.jsx(se,{children:u.scheduled_date?z(H(u.scheduled_date),"MMM d"):"Unscheduled"}),e.jsx(se,{children:u.estimated_duration_minutes?me(u.estimated_duration_minutes):"--"}),e.jsx(se,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[u.status==="pending"&&e.jsx(D,{size:"sm",variant:"secondary",onClick:Q=>{Q.stopPropagation(),i.updateRouteStatus.mutate({routeId:u.id,status:"in_progress"})},children:"Start"}),u.status==="in_progress"&&e.jsx(D,{size:"sm",onClick:Q=>{Q.stopPropagation(),i.updateRouteStatus.mutate({routeId:u.id,status:"completed"})},children:"Complete"})]})})]},u.id)),r.length===0&&e.jsx(we,{children:e.jsx(se,{colSpan:5,className:"h-28 text-center text-muted-foreground",children:"No routes scheduled for this date."})})]})]})})})]}),e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(ee,{className:"h-5 w-5"}),"Route Stops"]})}),e.jsx(E,{children:C?y.isLoading?e.jsx("div",{className:"flex h-48 items-center justify-center",children:e.jsx(Ee,{})}):e.jsx(X,{className:"h-[520px] pr-2",children:e.jsxs("div",{className:"space-y-3",children:[(y.data||[]).map((u,Q)=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(P,{variant:"secondary",className:"h-6 w-6 justify-center rounded-full p-0",children:Q+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:u.name||u.address||"Stop"}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:u.address}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsx(P,{variant:"outline",className:"capitalize",children:u.status}),u.estimated_arrival&&e.jsx(P,{variant:"secondary",children:z(H(u.estimated_arrival),"h:mm a")})]})]})]}),e.jsxs("div",{className:"mt-3 grid grid-cols-3 gap-2",children:[e.jsx(D,{size:"sm",variant:"outline",onClick:()=>window.open(`https://www.google.com/maps/dir/?api=1&destination=${u.lat},${u.lng}`,"_blank"),children:e.jsx(ne,{className:"h-4 w-4"})}),e.jsx(D,{size:"sm",variant:"secondary",disabled:u.status!=="pending",onClick:()=>i.updateWaypointStatus.mutate({waypointId:u.id,status:"arrived"}),children:"Arrive"}),e.jsx(D,{size:"sm",disabled:u.status==="completed",onClick:()=>i.updateWaypointStatus.mutate({waypointId:u.id,status:"completed"}),children:"Done"})]})]},u.id)),(y.data||[]).length===0&&e.jsx("div",{className:"rounded-lg border border-dashed p-8 text-sm text-muted-foreground",children:"This route does not have stops yet."})]})}):e.jsx("div",{className:"rounded-lg border border-dashed p-8 text-sm text-muted-foreground",children:"Select a route to review stops."})})]})]})}),e.jsx(Z,{value:"map",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]",children:[e.jsx(bs,{jobs:i.jobsForSelectedDate,routePlan:i.smartRoutePlan,height:"680px"}),e.jsx(Be,{plan:i.smartRoutePlan,assignee:n,onAssigneeChange:m,members:i.teamMembers,onCreateRoute:o,isCreating:a})]})}),e.jsx(Z,{value:"jobs",className:"space-y-6",children:e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(_e,{className:"h-5 w-5"}),"Field Jobs"]})}),e.jsx(E,{children:e.jsx(X,{className:"h-[650px] pr-2",children:e.jsx("div",{className:"space-y-3",children:i.jobs.map(u=>e.jsx(be,{job:u,onStatusChange:i.updateJobStatus},u.id))})})})]})}),e.jsx(Z,{value:"staff",className:"space-y-6",children:e.jsx(Es,{organizationId:((ue=i.organization)==null?void 0:ue.id)||null})}),e.jsx(Z,{value:"history",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsx(ks,{sessions:c.sessions||[]}),e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Pe,{className:"h-5 w-5"}),"Recent Routes"]})}),e.jsx(E,{children:e.jsx(X,{className:"h-80 pr-2",children:e.jsx("div",{className:"space-y-3",children:i.routes.slice(0,12).map(u=>e.jsx("div",{className:"rounded-lg border p-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:u.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.scheduled_date?z(H(u.sc
13heduled_date),"MMM d, yyyy"):"Unscheduled"})]}),e.jsx(P,{variant:"outline",className:"capitalize",children:u.status.replace("_"," ")})]})},u.id))})})})]})]})}),e.jsx(Z,{value:"settings",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsx(Wt,{}),e.jsxs(F,{children:[e.jsx(O,{className:"pb-3",children:e.jsxs($,{className:"flex items-center gap-2 text-lg",children:[e.jsx(rt,{className:"h-5 w-5"}),"Automation Rules"]})}),e.jsx(E,{className:"space-y-4",children:qs.map(u=>e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:u.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.detail})]}),e.jsx(ce,{defaultChecked:u.enabled})]},u.label))})]})]})})]})]})}const en=()=>e.jsx(nt,{feature:"gps-tracker",showOverlay:!1,children:e.jsx(it,{children:e.jsx(Bs,{})})});export{en as default};

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