1import{b as ct,u as dt,e as pe,r as x,j as e}from"./query-vendor-Dp9tfhuh.js";import{x as Se,s as z,B as S,b as Me,h as Te,c as X,z as Ct,X as ut,m as Ge,D as be,p as Ne,q as Ce,r as _e,o as _t,E as St,f as Mt,L as Ae,v as Xe,t as kt}from"./index-CgOeqv80.js";import{u as Et}from"./useInvestmentProperties-eR6DIttF.js";import{u as At}from"./index-Cc2m4mVS.js";import{B as ue}from"./badge-CarGzGVG.js";import{S as ht}from"./skeleton-U7PtyM3w.js";import{M as ke}from"./map-pin-B63H-upO.js";import{C as mt}from"./chevron-down-Bm2Y15mk.js";import{H as Fe}from"./house-5R4LHGOP.js";import{S as Pt}from"./square-pen-Bg7uj701.js";import{T as Qe}from"./trash-2-DAqLpVlV.js";import{S as Lt,T as It,F as Tt}from"./tree-pine-CouWAS-6.js";import{B as Ft}from"./building-DasY5zOg.js";import{u as Dt,G as Ot,C as ze,M as Rt,I as zt}from"./esm-BHLdRt99.js";import{j as et}from"./chart-vendor-BoynbIzZ.js";import{G as Bt,a as $t,b as Ut}from"./googleMaps-CnGBkgZD.js";import{S as Zt}from"./slider-BJvr272o.js";import{C as qt}from"./circle-pSWMGBM_.js";import{c as Gt}from"./mapMarkerStyles-BrAskDV3.js";import{E as Ht}from"./external-link-BIGsQXrz.js";import{P as pt}from"./pencil-d1bR18nI.js";import{I as W}from"./input-go5takyh.js";import{S as ge,a as xe,b as fe,c as je,d as E}from"./select-Bqpq_Ta3.js";import{u as Kt}from"./useIsRTL-D_a81cVb.js";import{S as gt}from"./search-Dx_o7OfG.js";import{u as Vt}from"./index.esm-CkJzGlqP.js";import{t as Wt,o as Qt,b as Yt,s as re,l as Jt,c as Be,e as $e}from"./types-szjy-y-j.js";import{F as Xt,a as B,b as $,c as U,d as Z,e as q}from"./form-B4EnfxjI.js";import{T as De}from"./textarea-BSB7eVDL.js";import{S as xt}from"./scroll-area-DpCy8yLM.js";import{C as es}from"./checkbox-BP3bjh8J.js";import{P as ft}from"./progress-DZ0cqMKx.js";import{L as ts}from"./layers-D0VRol72.js";import{D as jt}from"./download-B3iahoQg.js";import{D as ss,a as rs,b as ns,c as Pe}from"./dropdown-menu-BeZf8kFV.js";import{A as as,a as is,b as os,c as ls,d as cs,e as ds,f as us,g as hs}from"./alert-dialog-BvM39fc1.js";import{P as He}from"./plus-CYnN_kFu.js";import{E as ms,u as ps}from"./use-mobile-CojsY12Z.js";import{S as vt}from"./share-2-sKHj2vjO.js";import{C as gs}from"./circle-check-CLkepror.js";import{C as xs}from"./circle-x-CMEjdGNX.js";import{T as fs,a as js,b as tt}from"./tabs-CaoVN6UB.js";import{S as vs,a as ws,b as ys}from"./sheet-bqYui_d3.js";import{a as bs}from"./react-vendor-DfslLuwi.js";import{A as Ns}from"./arrow-left-BmX2tYO6.js";import{L as st}from"./list-BJoWfKXY.js";import{M as Cs}from"./map-C8rxfYCS.js";import"./ui-vendor-DW4RoVmg.js";import"./index-BdQq_4o_.js";import"./check-v4vwqlB-.js";import"./chevron-up-DVBQQKr7.js";import"./chevron-right-BdUdHP_I.js";const wt=()=>{const{toast:a}=Se(),t=ct(),{data:s,isLoading:r}=dt({queryKey:["map-portfolios"],queryFn:async()=>{const{data:{user:d}}=await z.auth.getUser();if(!d)throw new Error("Not authenticated");const u=localStorage.getItem("currentOrganizationId");if(!u)throw new Error("No organization selected");const{data:h,error:g}=await z.from("map_portfolios").select(` 2 *, 3 properties:map_portfolio_properties(count) 4 `).eq("organization_id",u).order("created_at",{ascending:!1});if(g)throw g;return(h||[]).map(m=>{var y,v;return{...m,property_count:((v=(y=m.properties)==null?void 0:y[0])==null?void 0:v.count)||0}})}}),l=pe({mutationFn:async d=>{const{data:{user:u}}=await z.auth.getUser();if(!u)throw new Error("Not authenticated");const h=localStorage.getItem("currentOrganizationId");if(!h)throw new Error("No organization selected");const{data:g,error:m}=await z.from("map_portfolios").insert([{...d,user_id:u.id,organization_id:h}]).select().single();if(m)throw m;return g},onSuccess:()=>{t.invalidateQueries({queryKey:["map-portfolios"]}),a({title:"Mapfolio created",description:"Your new Mapfolio has been created successfully."})},onError:d=>{a({title:"Error creating Mapfolio",description:d.message,variant:"destructive"})}}),i=pe({mutationFn:async({id:d,...u})=>{const{data:h,error:g}=await z.from("map_portfolios").update(u).eq("id",d).select().single();if(g)throw g;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["map-portfolios"]}),a({title:"Mapfolio updated",description:"Your Mapfolio has been updated successfully."})},onError:d=>{a({title:"Error updating Mapfolio",description:d.message,variant:"destructive"})}}),c=pe({mutationFn:async d=>{const{error:u}=await z.from("map_portfolios").delete().eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["map-portfolios"]}),a({title:"Mapfolio deleted",description:"Your Mapfolio has been deleted successfully."})},onError:d=>{a({title:"Error deleting Mapfolio",description:d.message,variant:"destructive"})}}),o=pe({mutationFn:async({id:d,isPublished:u})=>{const{data:h,error:g}=await z.from("map_portfolios").update({is_published:u}).eq("id",d).select().single();if(g)throw g;return h},onSuccess:d=>{t.invalidateQueries({queryKey:["map-portfolios"]}),a({title:d.is_published?"Mapfolio published":"Mapfolio unpublished",description:d.is_published?`Your Mapfolio is now live at /mapfolio/${d.public_token}`:"Your Mapfolio is now private."})},onError:d=>{a({title:"Error updating publish status",description:d.message,variant:"destructive"})}}),n=pe({mutationFn:async({portfolioId:d,propertyId:u})=>{var v;const{data:h}=await z.from("map_portfolio_properties").select("display_order").eq("portfolio_id",d).order("display_order",{ascending:!1}).limit(1),g=((v=h==null?void 0:h[0])==null?void 0:v.display_order)+1||0,{data:m,error:y}=await z.from("map_portfolio_properties").insert([{portfolio_id:d,investment_property_id:u,display_order:g}]).select().single();if(y)throw y;return m},onSuccess:()=>{t.invalidateQueries({queryKey:["map-portfolios"]}),t.invalidateQueries({queryKey:["map-portfolio-properties"]}),a({title:"Property added",description:"Property has been added to the Mapfolio."})},onError:d=>{a({title:"Error adding property",description:d.message,variant:"destructive"})}}),p=pe({mutationFn:async({portfolioId:d,propertyId:u})=>{const{error:h}=await z.from("map_portfolio_properties").delete().eq("portfolio_id",d).eq("investment_property_id",u);if(h)throw h},onSuccess:()=>{t.invalidateQueries({queryKey:["map-portfolios"]}),t.invalidateQueries({queryKey:["map-portfolio-properties"]}),a({title:"Property removed",description:"Property has been removed from the Mapfolio."})},onError:d=>{a({title:"Error removing property",description:d.message,variant:"destructive"})}});return{portfolios:s||[],isLoading:r,createPortfolio:l,updatePortfolio:i,deletePortfolio:c,publishPortfolio:o,addPropertyToPortfolio:n,removePropertyFromPortfolio:p}},_s=a=>dt({queryKey:["map-portfolio-properties",a],enabled:!!a,queryFn:async()=>
4{if(!a)return null;const{data:t,error:s}=await z.from("map_portfolios").select("*").eq("id",a).single();if(s)throw s;const{data:r,error:l}=await z.from("map_portfolio_properties").select(` 5 *, 6 investment_property:investment_properties(*) 7 `).eq("portfolio_id",a).order("display_order",{ascending:!0});if(l)throw l;return{...t,properties:r||[]}}});function Ss(){const{toast:a}=Se(),[t,s]=x.useState({total:0,processed:0,success:0,failed:0,isRunning:!1}),r=x.useCallback(async c=>{var d;const{data:o}=await z.auth.getSession();if(!((d=o==null?void 0:o.session)==null?void 0:d.access_token))throw new Error("Not authenticated");const p=await z.functions.invoke("geocode-batch",{body:{properties:c}});if(p.error)throw new Error(p.error.message||"Geocoding failed");return p.data},[]),l=x.useCallback(async()=>{s({total:0,processed:0,success:0,failed:0,isRunning:!0});try{const{data:c,error:o}=await z.from("investment_properties").select("id, address").or("latitude.is.null,longitude.is.null").not("address","is",null).not("address","eq","");if(o)throw o;if(!c||c.length===0){a({title:"All properties geocoded",description:"No properties with missing coordinates found."}),s(y=>({...y,isRunning:!1}));return}s(y=>({...y,total:c.length}));let n=0,p=0,d=[...c],u=0;const h=3,g=10,m=3e3;for(;d.length>0;){const y=d.slice(0,g);try{const v=await r(y);if(n+=v.success,p+=v.failed,u=0,s(f=>({...f,processed:f.processed+v.processed,success:n,failed:p})),d=d.slice(g),d.length>0){const f=m+(d.length>100?2e3:0);await new Promise(_=>setTimeout(_,f))}}catch(v){if(console.error("Batch error:",v),u++,u>=h){a({title:"Geocoding paused",description:"Too many consecutive errors. Please try again later.",variant:"destructive"});break}const f=Math.pow(2,u)*2e3;console.log(`Waiting ${f}ms before retry...`),await new Promise(_=>setTimeout(_,f));continue}}a({title:"Geocoding complete",description:`Successfully geocoded ${n} properties${p>0?`. ${p} could not be located.`:"!"}`})}catch(c){console.error("Geocoding error:",c),a({title:"Geocoding failed",description:c.message,variant:"destructive"})}finally{s(c=>({...c,isRunning:!1}))}},[r,a]),i=x.useCallback(async(c,o)=>{try{return(await r([{id:c,address:o}])).results[0]}catch(n){return console.error("Single geocode error:",n),null}},[r]);return{progress:t,geocodeBatch:r,geocodePropertiesWithMissingCoords:l,geocodeSingleProperty:i}}const Ms={owned:"bg-emerald-500/20 text-emerald-700 dark:text-emerald-400",scouting:"bg-blue-500/20 text-blue-700 dark:text-blue-400",potential:"bg-amber-500/20 text-amber-700 dark:text-amber-400",watching:"bg-slate-500/20 text-slate-700 dark:text-slate-400"},ks={Apartment:e.jsx(Ft,{className:"w-4 h-4"}),House:e.jsx(Fe,{className:"w-4 h-4"}),Land:e.jsx(It,{className:"w-4 h-4"}),Commercial:e.jsx(Lt,{className:"w-4 h-4"})},Es=100;function As({properties:a,selectedPropertyId:t,onPropertyClick:s,onEditProperty:r,onDeleteProperty:l,isLoading:i,totalCount:c,hasMore:o=!1,onLoadMore:n,isLoadingMore:p=!1}){const d=x.useRef(null),[u,h]=x.useState(null),g=x.useMemo(()=>t?a.findIndex(y=>y.id===t):-1,[a,t]),m=At({count:a.length+(o?1:0),getScrollElement:()=>d.current,estimateSize:()=>Es,overscan:5});return x.useEffect(()=>{g>=0&&m.scrollToIndex(g,{align:"center",behavior:"smooth"})},[g,m]),i?e.jsx("div",{className:"p-4 space-y-3",children:[1,2,3,4,5].map(y=>e.jsx(ht,{className:"h-24 w-full"},y))}):a.length===0?e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:[e.jsx(ke,{className:"w-12 h-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No properties yet"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Add your first investment property to get started tracking your portfolio."})]}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsx("div",{className:"px-3 py-2 border-b bg-muted/30 flex items-center justify-between",children:e.jsx("span",{className:"text-sm font-medium",children:c!==void 0?e.jsxs(e.Fragment,{children:["Showing ",a.length," of ",c]}):e.jsxs(e.Fragment,{children:[a.length," properties"]})})}),e.jsx("div",{ref:d,className:"flex-1 overflow-auto",children:e.jsx("div",{style:{height:`${m.getTotalSize()}px`,width:"100%",position:"relative"},children:m.getVirtualItems().map(y=>{if(y.index===a.length)return e.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:`${y.size}px`,transform:`translateY(${y.start}px)`},className:"p-3",children:e.jsx(S,{variant:"outline",onClick:n,disabled:p,className:"w-full",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Me,{className:"w-4 h-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{className:"w-4 h-4 mr-2"}),"Load More"]})})},"load-more");const f=a[y.index];if(!f)return null;const _=t===f.id,P=u===f.id;return e.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:`${y.size}px`,transform:`translateY(${y.start}px)`},className:"p-1.5",children:e.jsx(Te,{className:X("h-full p-3 cursor-pointer transition-all hover:shadow-md",_&&"ring-2 ring-primary"),onClick:()=>s(f.id),onMouseEnter:()=>h(f.id),onMouseLeave:()=>h(null),children:e.jsxs("div",{className:"flex gap-3 h-full",children:[e.jsx("div",{className:"w-16 h-16 rounded-md bg-muted shrink-0 overflow-hidden",children:f.image_url?e.jsx("img",{src:f.image_url,alt:f.title,className:"w-full h-full object-cover",loading:"lazy"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:ks[f.property_type||"House"]||e.jsx(Fe,{className:"w-6 h-6 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h4",{className:"font-medium text-sm truncate",children:f.title}),e.jsxs("div",{className:X("flex gap-1 transition-opacity",P||_?"opacity-100":"opacity-0"),children:[e.jsx(S,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:F=>{F.stopPropagation(),r(f)},children:e.jsx(Pt,{className:"w-3 h-3"})}),e.jsx(S,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:F=>{F.stopPropagation(),l(f.id)},children:e.jsx(Qe,{className:"w-3 h-3"})})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:f.address}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[f.category&&e.jsx(ue,{variant:"secondary",className:X("text-xs",Ms[f.category]),children:f.category}),f.estimated_value&&e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["$",f.estimated_value.toLocaleStr
7ing()]})]})]})]})})},f.id)})})})]})}const rt=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Ue=1,we=8;class Ye{static from(t){if(!(t instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[s,r]=new Uint8Array(t,0,2);if(s!==219)throw new Error("Data does not appear to be in a KDBush format.");const l=r>>4;if(l!==Ue)throw new Error(`Got v${l} data when expected v${Ue}.`);const i=rt[r&15];if(!i)throw new Error("Unrecognized array type.");const[c]=new Uint16Array(t,2,1),[o]=new Uint32Array(t,4,1);return new Ye(o,c,i,t)}constructor(t,s=64,r=Float64Array,l){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+s,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=rt.indexOf(this.ArrayType),c=t*2*this.ArrayType.BYTES_PER_ELEMENT,o=t*this.IndexArrayType.BYTES_PER_ELEMENT,n=(8-o%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);l&&l instanceof ArrayBuffer?(this.data=l,this.ids=new this.IndexArrayType(this.data,we,t),this.coords=new this.ArrayType(this.data,we+o+n,t*2),this._pos=t*2,this._finished=!0):(this.data=new ArrayBuffer(we+c+o+n),this.ids=new this.IndexArrayType(this.data,we,t),this.coords=new this.ArrayType(this.data,we+o+n,t*2),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,(Ue<<4)+i]),new Uint16Array(this.data,2,1)[0]=s,new Uint32Array(this.data,4,1)[0]=t)}add(t,s){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=s,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return Ke(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(t,s,r,l){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:c,nodeSize:o}=this,n=[0,i.length-1,0],p=[];for(;n.length;){const d=n.pop()||0,u=n.pop()||0,h=n.pop()||0;if(u-h<=o){for(let v=h;v<=u;v++){const f=c[2*v],_=c[2*v+1];f>=t&&f<=r&&_>=s&&_<=l&&p.push(i[v])}continue}const g=h+u>>1,m=c[2*g],y=c[2*g+1];m>=t&&m<=r&&y>=s&&y<=l&&p.push(i[g]),(d===0?t<=m:s<=y)&&(n.push(h),n.push(g-1),n.push(1-d)),(d===0?r>=m:l>=y)&&(n.push(g+1),n.push(u),n.push(1-d))}return p}within(t,s,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:l,coords:i,nodeSize:c}=this,o=[0,l.length-1,0],n=[],p=r*r;for(;o.length;){const d=o.pop()||0,u=o.pop()||0,h=o.pop()||0;if(u-h<=c){for(let v=h;v<=u;v++)nt(i[2*v],i[2*v+1],t,s)<=p&&n.push(l[v]);continue}const g=h+u>>1,m=i[2*g],y=i[2*g+1];nt(m,y,t,s)<=p&&n.push(l[g]),(d===0?t-r<=m:s-r<=y)&&(o.push(h),o.push(g-1),o.push(1-d)),(d===0?t+r>=m:s+r>=y)&&(o.push(g+1),o.push(u),o.push(1-d))}return n}}function Ke(a,t,s,r,l,i){if(l-r<=s)return;const c=r+l>>1;yt(a,t,c,r,l,i),Ke(a,t,s,r,c-1,1-i),Ke(a,t,s,c+1,l,1-i)}function yt(a,t,s,r,l,i){for(;l>r;){if(l-r>600){const p=l-r+1,d=s-r+1,u=Math.log(p),h=.5*Math.exp(2*u/3),g=.5*Math.sqrt(u*h*(p-h)/p)*(d-p/2<0?-1:1),m=Math.max(r,Math.floor(s-d*h/p+g)),y=Math.min(l,Math.floor(s+(p-d)*h/p+g));yt(a,t,s,m,y,i)}const c=t[2*s+i];let o=r,n=l;for(ye(a,t,r,s),t[2*l+i]>c&&ye(a,t,r,l);o<n;){for(ye(a,t,o,n),o++,n--;t[2*o+i]<c;)o++;for(;t[2*n+i]>c;)n--}t[2*r+i]===c?ye(a,t,r,n):(n++,ye(a,t,n,l)),n<=s&&(r=n+1),s<=n&&(l=n-1)}}function ye(a,t,s,r){Ze(a,s,r),Ze(t,2*s,2*r),Ze(t,2*s+1,2*r+1)}function Ze(a,t,s){const r=a[t];a[t]=a[s],a[s]=r}function nt(a,t,s,r){const l=a-s,i=t-r;return l*l+i*i}const Ps={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:a=>a},at=Math.fround||(a=>t=>(a[0]=+t,a[0]))(new Float32Array(1)),ce=2,ie=3,qe=4,ae=5,bt=6;class Ls{constructor(t){this.options=Object.assign(Object.create(Ps),t),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(t){const{log:s,minZoom:r,maxZoom:l}=this.options;s&&console.time("total time");const i=`prepare ${t.length} points`;s&&console.time(i),this.points=t;const c=[];for(let n=0;n<t.length;n++){const p=t[n];if(!p.geometry)continue;const[d,u]=p.geometry.coordinates,h=at(Le(d)),g=at(Ie(u));c.push(h,g,1/0,n,-1,1),this.options.reduce&&c.push(0)}let o=this.trees[l+1]=this._createTree(c);s&&console.timeEnd(i);for(let n=l;n>=r;n--){const p=+Date.now();o=this.trees[n]=this._createTree(this._cluster(o,n)),s&&console.log("z%d: %d clusters in %dms",n,o.numItems,+Date.now()-p)}return s&&console.timeEnd("total time"),this}getClusters(t,s){let r=((t[0]+180)%360+360)%360-180;const l=Math.max(-90,Math.min(90,t[1]));let i=t[2]===180?180:((t[2]+180)%360+360)%360-180;const c=Math.max(-90,Math.min(90,t[3]));if(t[2]-t[0]>=360)r=-180,i=180;else if(r>i){const u=this.getClusters([r,l,180,c],s),h=this.getClusters([-180,l,i,c],s);return u.concat(h)}const o=this.trees[this._limitZoom(s)],n=o.range(Le(r),Ie(c),Le(i),Ie(l)),p=o.data,d=[];for(const u of n){const h=this.stride*u;d.push(p[h+ae]>1?it(p,h,this.clusterProps):this.points[p[h+ie]])}return d}getChildren(t){const s=this._getOriginId(t),r=this._getOriginZoom(t),l="No cluster with the specified id.",i=this.trees[r];if(!i)throw new Error(l);const c=i.data;if(s*this.stride>=c.length)throw new Error(l);const o=this.options.radius/(this.options.extent*Math.pow(2,r-1)),n=c[s*this.stride],p=c[s*this.stride+1],d=i.within(n,p,o),u=[];for(const h of d){const g=h*this.stride;c[g+qe]===t&&u.push(c[g+ae]>1?it(c,g,this.clusterProps):this.points[c[g+ie]])}if(u.length===0)throw new Error(l);return u}getLeaves(t,s,r){s=s||10,r=r||0;const l=[];return this._appendLeaves(l,t,s,r,0),l}getTile(t,s,r){const l=this.trees[this._limitZoom(t)],i=Math.pow(2,t),{extent:c,radius:o}=this.options,n=o/c,p=(r-n)/i,d=(r+1+n)/i,u={features:[]};return this._addTileFeatures(l.range((s-n)/i,p,(s+1+n)/i,d),l.data,s,r,i,u),s===0&&this._addTileFeatures(l.range(1-n/i,p,1,d),l.data,i,r,i,u),s===i-1&&this._addTileFeatures(l.range(0,p,n/i,d),l.data,-1,r,i,u),u.features.length?u:null}getClusterExpansionZoom(t){let s=this._getOriginZoom(t)-1;for(;s<=this.options.maxZoom;){const r=this.getChildren(t);if(s++,r.length!==1)break;t=r[0].properties.cluster_id}return s}_appendLeaves(t,s,r,l,i){const c=this.getChildren(s);for(const o of c){const n=o.properties;if(n&&n.cluster?i+n.point_count<=l?i+=n.point_count:i=this._appendLeaves(t,n.cluster_id,r,l,i):i<l?i++:t.push(o),t.length===r)break}return i}_createTree(t){const s=new Ye(t.length/this.stride|0,this.options.nodeSize,Float32Array);for(let r=0;r<t.length;r+=this.stride)s.add(t[r],t[r+1]);return s.finish(),s.data=t,s}_addTileFeatures(t,s,r,l,i,c){for(const o of t){const n=o*this.stride,p=s[n+ae]>1;let d,u,h;if(p)d=Nt(s,n,this.clusterProps),u=s[n],h=s[n+1];else{const y=this.points[s[n+ie]];d=y.properties;const[v,f]=y.geometry.coordinates;u=Le(v),h=Ie(f)}const g={type:1,geometry:[[Math.round(this.options.extent*(u*i-r)),Math.round(this.options.extent*(h*i-l))]],tags:d};let m;p||this.options.generateId?m=s[n+ie]:m=this.points[s[n+ie]].id,m!==void 0&&(g.id=m),c.features.push(g)}}_limitZoom(t){return Math.max(this.options.minZoom,Math.min(Math.floor(+t),this.options.maxZoom+1))}_cluster(t,s){const{radius:r,extent:l,reduce:i,minPoints:c}=this.options,o=r/(l*Math.pow(2,s)),n=t.data,p=[],d=this.stride;for(let u=0;u<n.length;u+=d){if(n[u+ce]<=s)continue;n[u+ce]=s;const h=n[u],g=n[u+1],m=t.within(n[u],n[u+1],o),y=n[u+ae];let v=y;for(const f of m){const _=f*d;n[_+ce]>s&&(v+=n[_+ae])}if(v>y&&v>=c){let f=h*y,_=g*y,P,F=-1;const O=((u/d|0)<<5)+(s+1)+this.points.length;for(const Y of m){const j=Y*d;if(n[j+ce]<=s)continue;n[j+ce]=s;const L=n[j+ae];f+=n[j]*L,_+=n[j+1]*L,n[j+qe]=O,i&&(P||(P=this._map(n,u,!0),F=this.clusterProps.length,this.clusterProps.push(P)),i(P,this._map(n,j)))}n[u+qe]=O,p.push(f/v,_/v,1/0,O,-1,v),i&&p.push(F)}else{for(let f=0;f<d;f++)p.push(n[u+f]);if(v>1)for(const f of m){const _=f*d;if(!(n[_+ce]<=s)){n[_+ce]=s;for(let P=0;P<d;P++)p.push(n[_+P])}}}}return p}_getOriginId(t){return t-this.points.length>>5}_getOriginZoom(t){return(t-this.points.length)%32}_map(t,s,r){if(t[s+ae]>1){const c=this.clusterProps[t[s+bt]];return r?Object.assign({},c):c}const l=this.points[t[s+ie]].properties,i=this.options.map(l);return r&&i===l?Object.assign({},i):i}}function it(a,t,s){return{type:"Feature",id:a[t+ie],properties:Nt(a,t,s),geometry:{type:"Point",coordinates:[Is(a[t]),Ts(a[t+1])]}}}function Nt(a,t,s){const r=a[t+ae],l=r>=1e4?`${Math.round(r/1e3)}k`:r>=1e3?`${Math.round(r/100)/10}k`:r,i=a[t+bt],c=i===-1?{}:Object.assign({},s[i]);return Object.assign(c,{cluster:!0,cluster_id:a[t+ie],point_count:r,point_count_abbreviated:l})}function Le(a){return a/360+.5}function Ie(a){const t=Math.sin(a*Math.PI/180),s=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return s<0?0:s>1?1:s}function Is(a){return(a-.5)*360}function Ts(a){const t=(180-a*360)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function Fs(a,t){var s={};for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&t.indexOf(r)<0&&(s[r]=a[r]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function")for(var l=0,r=Object.getOwnPropertySymbols(a);l<r.length;l++)t.indexOf(r[l])<0&&Object.prototype.propertyIsEnumerable.call(a,r[l])&&(s[r[l]]=a[r[l]]);return s}class Q{static isAdvancedMarkerAvailable(t){return google.maps.marker&&t.getMapCapabilities().isAdvancedMarkersAvailable===!0}static isAdvancedMarker(t){return google.maps.marker&&t instanceof google.maps.marker.AdvancedMarkerElement}static setMap(t,s){this.isAdvancedMarker(t)?t.map=s:t.setMap(s)}static getPosition(t){if(this.isAdvancedMarker(t)){if(t.position){if(t.position instanceof google.maps.LatLng)return t.position;if(Number.isFinite(t.position.lat)&&Number.isFinite(t.position.lng))return new google.maps.LatLng(t.position.lat,t.position.lng)}return new google.maps.LatLng(null)}return t.getPosition()}static getVisible(t){return this.isAdvancedMarker(t)?!0:t.getVisible()}}class Ve{constructor({markers:t,position:s}){this.markers=[],t&&(this.markers=t),s&&(s instanceof google.maps.LatLng?this._position=s:this._position=new google.maps.LatLng(s))}get bounds(){if(this.markers.length===0&&!this._position)return;const t=new google.maps.LatLngBounds(this._position,this._position);for(const s of this.markers)t.extend(Q.getPosition(s));return t}get position(){return this._position||this.bounds.getCenter()}get count(){return this.markers.filter(t=>Q.getVisible(t)).length}push(t){this.markers.push(t)}delete(){this.marker&&(Q.setMap(this.marker,null),this.marker=void 0),this.markers.length=0}}function We(a,t="assertion failed"){if(a==null)throw Error(t)}class Ds{constructor({maxZoom:t=16}){this.maxZoom=t}noop({markers:t}){return Os(t)}}const Os=a=>a.map(s=>new Ve({position:Q.getPosition(s),markers:[s]}));class Rs extends Ds{constructor(t){var{maxZoom:s,radius:r=60}=t,l=Fs(t,["maxZoom","radius"]);super({maxZoom:s}
7),this.markers=[],this.clusters=[],this.state={zoom:-1},this.superCluster=new Ls(Object.assign({maxZoom:this.maxZoom,radius:r},l))}calculate(t){let s=!1,r=t.map.getZoom();We(r),r=Math.round(r);const l={zoom:r};if(!et(t.markers,this.markers)){s=!0,this.markers=[...t.markers];const i=this.markers.map(c=>{const o=Q.getPosition(c);return{type:"Feature",geometry:{type:"Point",coordinates:[o.lng(),o.lat()]},properties:{marker:c}}});this.superCluster.load(i)}return s||(this.state.zoom<=this.maxZoom||l.zoom<=this.maxZoom)&&(s=!et(this.state,l)),this.state=l,t.markers.length===0?(this.clusters=[],{clusters:this.clusters,changed:s}):(s&&(this.clusters=this.cluster(t)),{clusters:this.clusters,changed:s})}cluster({map:t}){const s=t.getZoom();return We(s),this.superCluster.getClusters([-180,-90,180,90],Math.round(s)).map(r=>this.transformCluster(r))}transformCluster({geometry:{coordinates:[t,s]},properties:r}){if(r.cluster)return new Ve({markers:this.superCluster.getLeaves(r.cluster_id,1/0).map(i=>i.properties.marker),position:{lat:s,lng:t}});const l=r.marker;return new Ve({markers:[l],position:Q.getPosition(l)})}}class zs{constructor(t,s){this.markers={sum:t.length};const r=s.map(i=>i.count),l=r.reduce((i,c)=>i+c,0);this.clusters={count:s.length,markers:{mean:l/s.length,sum:l,min:Math.min(...r),max:Math.max(...r)}}}}class Bs{render({count:t,position:s},r,l){const c=`<svg fill="${t>Math.max(10,r.clusters.markers.mean)?"#ff0000":"#0000ff"}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 240" width="50" height="50"> 8<circle cx="120" cy="120" opacity=".6" r="70" /> 9<circle cx="120" cy="120" opacity=".3" r="90" /> 10<circle cx="120" cy="120" opacity=".2" r="110" /> 11<text x="50%" y="50%" style="fill:#fff" text-anchor="middle" font-size="50" dominant-baseline="middle" font-family="roboto,arial,sans-serif">${t}</text> 12</svg>`,o=`Cluster of ${t} markers`,n=Number(google.maps.Marker.MAX_ZINDEX)+t;if(Q.isAdvancedMarkerAvailable(l)){const u=new DOMParser().parseFromString(c,"image/svg+xml").documentElement;u.setAttribute("transform","translate(0 25)");const h={map:l,position:s,zIndex:n,title:o,content:u};return new google.maps.marker.AdvancedMarkerElement(h)}const p={position:s,zIndex:n,title:o,icon:{url:`data:image/svg+xml;base64,${btoa(c)}`,anchor:new google.maps.Point(25,25)}};return new google.maps.Marker(p)}}function $s(a,t){for(let s in t.prototype)a.prototype[s]=t.prototype[s]}class Je{constructor(){$s(Je,google.maps.OverlayView)}}var de;(function(a){a.CLUSTERING_BEGIN="clusteringbegin",a.CLUSTERING_END="clusteringend",a.CLUSTER_CLICK="click",a.GMP_CLICK="gmp-click"})(de||(de={}));const Us=(a,t,s)=>{t.bounds&&s.fitBounds(t.bounds)};class Zs extends Je{constructor({map:t,markers:s=[],algorithmOptions:r={},algorithm:l=new Rs(r),renderer:i=new Bs,onClusterClick:c=Us}){super(),this.map=null,this.idleListener=null,this.markers=[...s],this.clusters=[],this.algorithm=l,this.renderer=i,this.onClusterClick=c,t&&this.setMap(t)}addMarker(t,s){this.markers.includes(t)||(this.markers.push(t),s||this.render())}addMarkers(t,s){t.forEach(r=>{this.addMarker(r,!0)}),s||this.render()}removeMarker(t,s){const r=this.markers.indexOf(t);return r===-1?!1:(Q.setMap(t,null),this.markers.splice(r,1),s||this.render(),!0)}removeMarkers(t,s){let r=!1;return t.forEach(l=>{r=this.removeMarker(l,!0)||r}),r&&!s&&this.render(),r}clearMarkers(t){this.markers.length=0,t||this.render()}render(){const t=this.getMap();if(t instanceof google.maps.Map&&t.getProjection()){google.maps.event.trigger(this,de.CLUSTERING_BEGIN,this);const{clusters:s,changed:r}=this.algorithm.calculate({markers:this.markers,map:t,mapCanvasProjection:this.getProjection()});if(r||r==null){const l=new Set;for(const c of s)c.markers.length==1&&l.add(c.markers[0]);const i=[];for(const c of this.clusters)c.marker!=null&&(c.markers.length==1?l.has(c.marker)||Q.setMap(c.marker,null):i.push(c.marker));this.clusters=s,this.renderClusters(),requestAnimationFrame(()=>i.forEach(c=>Q.setMap(c,null)))}google.maps.event.trigger(this,de.CLUSTERING_END,this)}}onAdd(){const t=this.getMap();We(t),this.idleListener=t.addListener("idle",this.render.bind(this)),this.render()}onRemove(){this.idleListener&&google.maps.event.removeListener(this.idleListener),this.reset()}
12reset(){this.markers.forEach(t=>Q.setMap(t,null)),this.clusters.forEach(t=>t.delete()),this.clusters=[]}renderClusters(){const t=new zs(this.markers,this.clusters),s=this.getMap();this.clusters.forEach(r=>{if(r.markers.length===1)r.marker=r.markers[0];else if(r.marker=this.renderer.render(r,t,s),r.markers.forEach(l=>Q.setMap(l,null)),this.onClusterClick){const l=Q.isAdvancedMarker(r.marker)?de.GMP_CLICK:de.CLUSTER_CLICK;r.marker.addListener(l,i=>{google.maps.event.trigger(this,de.CLUSTER_CLICK,r),this.onClusterClick(i,r,s)})}Q.setMap(r.marker,s)})}}const qs=[{label:"Watching",color:"#3B82F6"},{label:"Scouting",color:"#F59E0B"},{label:"Potential",color:"#8B5CF6"},{label:"Owned",color:"#22C55E"}];function Gs({className:a}){return e.jsxs("div",{className:X("absolute bottom-4 left-4 bg-card/90 backdrop-blur-sm rounded-lg border shadow-lg p-3 z-10",a),children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Categories"}),e.jsx("div",{className:"space-y-1.5",children:qs.map(t=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:t.color}}),e.jsx("span",{children:t.label})]},t.label))})]})}function Hs({activeMode:a,onModeChange:t,radiusKm:s,onRadiusChange:r,onClearDrawings:l,propertiesInRadius:i}){return e.jsxs("div",{className:"absolute top-4 left-4 z-10 flex flex-col gap-2",children:[e.jsxs("div",{className:"bg-card border rounded-lg shadow-lg p-2 flex flex-col gap-1",children:[e.jsxs(S,{size:"sm",variant:a==="radius-search"?"default":"ghost",onClick:()=>t(a==="radius-search"?"none":"radius-search"),className:"justify-start gap-2",children:[e.jsx(Ct,{className:"h-4 w-4"}),"Radius Search"]}),e.jsxs(S,{size:"sm",variant:a==="circle"?"default":"ghost",onClick:()=>t(a==="circle"?"none":"circle"),className:"justify-start gap-2",children:[e.jsx(qt,{className:"h-4 w-4"}),"Draw Area"]}),e.jsxs(S,{size:"sm",variant:"ghost",onClick:l,className:"justify-start gap-2 text-destructive hover:text-destructive",children:[e.jsx(ut,{className:"h-4 w-4"}),"Clear All"]})]}),a==="radius-search"&&e.jsxs("div",{className:"bg-card border rounded-lg shadow-lg p-3 w-48",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-2",children:["Click on map to search. Radius: ",s,"km"]}),e.jsx(Zt,{value:[s],onValueChange:c=>r(c[0]),min:1,max:50,step:1,className:"mb-2"}),i!==void 0&&e.jsxs("p",{className:"text-sm font-medium text-primary",children:[i," properties found"]})]}),a==="circle"&&e.jsx("div",{className:"bg-card border rounded-lg shadow-lg p-3 w-48",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click and drag on map to draw a circle area of interest"})})]})}function Ks(a,t,s,r){const i=(s-a)*Math.PI/180,c=(r-t)*Math.PI/180,o=Math.sin(i/2)*Math.sin(i/2)+Math.cos(a*Math.PI/180)*Math.cos(s*Math.PI/180)*Math.sin(c/2)*Math.sin(c/2);return 6371*(2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o)))}function Vs(a){const[t,s]=x.useState([]),[r,l]=x.useState(null),[i,c]=x.useState(5),o=x.useCallback(h=>{const g={...h,id:crypto.randomUUID()};s(m=>[...m,g])},[]),n=x.useCallback(()=>{s([]),l(null)},[]),p=x.useCallback(h=>{l({center:h,radiusKm:i})},[i]),d=x.useCallback(h=>{c(h),l(g=>g?{...g,radiusKm:h}:null)},[]),u=r?a.filter(h=>!h.latitude||!h.longitude?!1:Ks(r.center.lat,r.center.lng,h.latitude,h.longitude)<=r.radiusKm):[];return{drawnShapes:t,addShape:o,clearShapes:n,radiusSearch:r,setRadiusSearchCenter:p,radiusKm:i,updateRadiusKm:d,propertiesInRadius:u}}const Ws={width:"100%",height:"100%"},Qs={lat:40.7128,lng:-74.006},ot=a=>{switch(a){case"watching":return"#3B82F6";case"scouting":return"#F59E0B";case"potential":return"#8B5CF6";case"owned":return"#22C55E";default:return"#6B7280"}};function Ys({properties:a,selectedPropertyId:t,onPropertyClick:s,onEditProperty:r,onDeleteProperty:l}){const{isLoaded:i,loadError:c}=Dt({id:Bt,googleMapsApiKey:$t,libraries:Ut}),[o,n]=x.useState(null),[p,d]=x.useState("none"),u=x.useRef([]),h=x.useRef(null),{drawnShapes:g,addShape:m,clearShapes:y,radiusSearch:v,setRadiusSearchCenter:f,radiusKm:_,updateRadiusKm:P,propertiesInRadius:F}=Vs(a),[O,Y]=x.useState(!1),[j,L]=x.useState(null),[G,H]=x.useState(0),R=x.useMemo(()=>{const b=a.filter(T=>T.latitude&&T.longitude);if(b.length===0)return Qs;const D=b.reduce((T,te)=>T+(te.latitude||0),0)/b.length,M=b.reduce((T,te)=>T+(te.longitude||0),0)/b.length;return{lat:D,lng:M}},[a]),C=x.useMemo(()=>a.find(b=>b.id===t),[a,t]);x.useEffect(()=>{o&&(C!=null&&C.latitude)&&(C!=null&&C.longitude)&&(o.panTo({lat:C.latitude,lng:C.longitude}),o.setZoom(15))},[o,C]),x.useEffect(()=>{if(!o||!i)return;u.current.forEach(M=>M.setMap(null)),u.current=[],h.current&&h.current.clearMarkers();const D=a.filter(M=>M.latitude&&M.longitude).map(M=>{const T=M.id===t,te=M.pin_color||ot(M.category),se=new google.maps.Marker({position:{lat:M.latitude,lng:M.longitude},icon:{path:google.maps.SymbolPath.CIRCLE,fillColor:te,fillOpacity:1,strokeColor:"#ffffff",strokeWeight:T?3:2,scale:T?14:10}});return se.addListener("click",()=>s(M.id)),se});
12return u.current=D,h.current=new Zs({map:o,markers:D,renderer:{render:({count:M,position:T})=>new google.maps.Marker({position:T,icon:{path:google.maps.SymbolPath.CIRCLE,fillColor:"#6366F1",fillOpacity:.9,strokeColor:"#ffffff",strokeWeight:3,scale:Math.min(20+Math.log2(M)*4,40)},label:{text:String(M),color:"white",fontWeight:"bold",fontSize:"12px"},zIndex:Number(google.maps.Marker.MAX_ZINDEX)+M})}}),()=>{u.current.forEach(M=>M.setMap(null)),h.current&&h.current.clearMarkers()}},[o,a,t,i,s]);const K=x.useCallback(b=>{if(!b.latLng)return;const D={lat:b.latLng.lat(),lng:b.latLng.lng()};p==="radius-search"?f(D):p==="circle"&&(Y(!0),L(D),H(0))},[p,f]),he=x.useCallback(b=>{if(!O||!j||!b.latLng)return;const D={lat:b.latLng.lat(),lng:b.latLng.lng()},M=google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(j.lat,j.lng),new google.maps.LatLng(D.lat,D.lng));H(M)},[O,j]),oe=x.useCallback(()=>{O&&j&&G>100&&m({type:"circle",center:j,radius:G}),Y(!1),L(null),H(0)},[O,j,G,m]);return c?e.jsx("div",{className:"h-full flex items-center justify-center text-destructive",children:"Error loading maps"}):i?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx(Hs,{activeMode:p,onModeChange:d,radiusKm:_,onRadiusChange:P,onClearDrawings:y,propertiesInRadius:v?F.length:void 0}),e.jsxs(Ot,{mapContainerStyle:Ws,center:R,zoom:12,onLoad:b=>n(b),onClick:K,onMouseMove:he,onMouseUp:oe,options:{streetViewControl:!0,mapTypeControl:!0,fullscreenControl:!0,zoomControl:!0,draggableCursor:p!=="none"?"crosshair":void 0},children:[g.map(b=>e.jsx(ze,{center:b.center,radius:b.radius,options:{fillColor:"#8B5CF6",fillOpacity:.2,strokeColor:"#8B5CF6",strokeWeight:2}},b.id)),O&&j&&e.jsx(ze,{center:j,radius:G,options:{fillColor:"#8B5CF6",fillOpacity:.15,strokeColor:"#8B5CF6",strokeWeight:2,strokeOpacity:.8}}),v&&e.jsx(ze,{center:v.center,radius:v.radiusKm*1e3,options:{fillColor:"#3B82F6",fillOpacity:.15,strokeColor:"#3B82F6",strokeWeight:2}}),a.filter(b=>b.latitude&&b.longitude).map(b=>{const D=b.id===t,M=b.pin_color||ot(b.category);return e.jsx(Rt,{position:{lat:b.latitude,lng:b.longitude},icon:Gt(M,D?28:20)},`ring-${b.id}`)}),C&&C.latitude&&C.longitude&&e.jsx(zt,{position:{lat:C.latitude,lng:C.longitude},onCloseClick:()=>s(t||""),children:e.jsx(Te,{className:"border-0 shadow-none max-w-xs",children:e.jsxs(Ge,{className:"p-3",children:[C.image_url&&e.jsx("img",{src:C.image_url,alt:C.title,className:"w-full h-32 object-cover rounded-md mb-3"}),e.jsx("h3",{className:"font-semibold text-base mb-1",children:C.title}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1 mb-2",children:[e.jsx(ke,{className:"w-3 h-3"}),C.address]}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground mb-3 line-clamp-2",children:C.description}),e.jsxs("div",{className:"flex gap-2",children:[C.listing_url&&e.jsx(S,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:C.listing_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ht,{className:"w-3 h-3 mr-1"}),"View"]}
12)}),r&&e.jsxs(S,{size:"sm",variant:"outline",onClick:()=>r(C),children:[e.jsx(pt,{className:"w-3 h-3 mr-1"}),"Edit"]}),l&&e.jsx(S,{size:"sm",variant:"destructive",onClick:()=>l(C.id),children:e.jsx(Qe,{className:"w-3 h-3"})})]})]})})})]}),e.jsx(Gs,{})]}):e.jsx("div",{className:"h-full flex items-center justify-center",children:"Loading maps..."})}function Js({categoryFilter:a,setCategoryFilter:t,typeFilter:s,setTypeFilter:r,searchQuery:l,setSearchQuery:i,propertyCount:c,missingCoordsCount:o=0,onFixMissingCoords:n,isGeocoding:p=!1}){const d=Kt();return e.jsxs("div",{className:X("border-b bg-card/50 px-4 py-2 flex flex-wrap items-center gap-3 shrink-0",d&&"flex-row-reverse"),children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-sm",children:[e.jsx(gt,{className:X("absolute top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground",d?"right-3":"left-3")}),e.jsx(W,{placeholder:"Search properties...",value:l,onChange:u=>i(u.target.value),className:X("h-9",d?"pr-9":"pl-9"),dir:"auto"})]}),e.jsxs(ge,{value:a,onValueChange:u=>t(u),children:[e.jsx(xe,{className:"w-[140px] h-9",children:e.jsx(fe,{placeholder:"Category"})}),e.jsxs(je,{children:[e.jsx(E,{value:"all",children:"All Categories"}),e.jsx(E,{value:"owned",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-500"}),"Owned"]})}),e.jsx(E,{value:"scouting",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-500"}),"Scouting"]})}),e.jsx(E,{value:"potential",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"Potential"]})}),e.jsx(E,{value:"watching",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-slate-500"}),"Watching"]})})]})]}),e.jsxs(ge,{value:s,onValueChange:r,children:[e.jsx(xe,{className:"w-[140px] h-9",children:e.jsx(fe,{placeholder:"Type"})}),e.jsxs(je,{children:[e.jsx(E,{value:"all",children:"All Types"}),e.jsx(E,{value:"Apartment",children:"Apartment"}),e.jsx(E,{value:"House",children:"House"}),e.jsx(E,{value:"Land",children:"Land"}),e.jsx(E,{value:"Commercial",children:"Commercial"})]})]}),o>0&&n&&e.jsxs(S,{variant:"outline",size:"sm",onClick:n,disabled:p,className:"text-amber-600 border-amber-300 hover:bg-amber-50 gap-1",children:[p?e.jsx(Me,{className:"w-4 h-4 animate-spin"}):e.jsx(ke,{className:"w-4 h-4"}),"Fix ",o," missing"]}),e.jsxs("span",{className:X("text-sm text-muted-foreground",d?"mr-auto":"ml-auto"),children:[c," ",c===1?"property":"properties"]})]})}const Xs=Qt({title:re().min(1,"Title is required"),address:re().min(1,"Address is required"),category:$e(["owned","scouting","potential","watching"]).nullable(),property_type:$e(["Apartment","House","Land","Commercial"]).nullable(),status:$e(["For Sale","For Rent","Sold","Rented","Planning"]).nullable(),estimated_value:Be.number().nullable(),latitude:Be.number().nullable(),longitude:Be.number().nullable(),listing_url:re().nullable(),image_url:re().nullable(),description:re().nullable(),notes:re().nullable(),contact_name:re().nullable(),contact_phone:re().nullable(),contact_email:re().email().nullable().or(Jt("")),is_public:Yt()});function er({open:a,onOpenChange:t,property:s,onSave:r,isLoading:l}){const i=Vt({resolver:Wt(Xs),defaultValues:{title:"",address:"",category:null,property_type:null,status:null,estimated_value:null,latitude:null,longitude:null,listing_url:null,image_url:null,description:null,notes:null,contact_name:null,contact_phone:null,contact_email:null,is_public:!1}});x.useEffect(()=>{s?i.reset({title:s.title,address:s.address,category:s.category||null,property_type:s.property_type||null,status:s.status||null,estimated_value:s.estimated_value||null,latitude:s.latitude||null,longitude:s.longitude||null,listing_url:s.listing_url||null,image_url:s.image_url||null,description:s.description||null,notes:s.notes||null,contact_name:s.contact_name||null,contact_phone:s.contact_phone||null,contact_email:s.contact_email||null,is_public:s.is_public}
12):i.reset({title:"",address:"",category:"scouting",property_type:null,status:null,estimated_value:null,latitude:null,longitude:null,listing_url:null,image_url:null,description:null,notes:null,contact_name:null,contact_phone:null,contact_email:null,is_public:!1})},[s,i]);const c=async o=>{await r({...o,contact_email:o.contact_email||null})};return e.jsx(be,{open:a,onOpenChange:t,children:e.jsxs(Ne,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Ce,{children:e.jsx(_e,{children:s?"Edit Property":"Add New Property"})}),e.jsx(Xt,{...i,children:e.jsxs("form",{onSubmit:i.handleSubmit(c),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(B,{control:i.control,name:"title",render:({field:o})=>e.jsxs($,{className:"col-span-full",children:[e.jsx(U,{children:"Title *"}),e.jsx(Z,{children:e.jsx(W,{placeholder:"Property name",...o})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"address",render:({field:o})=>e.jsxs($,{className:"col-span-full",children:[e.jsx(U,{children:"Address *"}),e.jsx(Z,{children:e.jsx(W,{placeholder:"Full address",...o})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"category",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Category"}),e.jsxs(ge,{value:o.value||"",onValueChange:n=>o.onChange(n||null),children:[e.jsx(Z,{children:e.jsx(xe,{children:e.jsx(fe,{placeholder:"Select category"})})}),e.jsxs(je,{children:[e.jsx(E,{value:"owned",children:"Owned"}),e.jsx(E,{value:"scouting",children:"Scouting"}),e.jsx(E,{value:"potential",children:"Potential"}),e.jsx(E,{value:"watching",children:"Watching"})]})]}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"property_type",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Property Type"}),e.jsxs(ge,{value:o.value||"",onValueChange:n=>o.onChange(n||null),children:[e.jsx(Z,{children:e.jsx(xe,{children:e.jsx(fe,{placeholder:"Select type"})})}),e.jsxs(je,{children:[e.jsx(E,{value:"Apartment",children:"Apartment"}),e.jsx(E,{value:"House",children:"House"}),e.jsx(E,{value:"Land",children:"Land"}),e.jsx(E,{value:"Commercial",children:"Commercial"})]})]}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"status",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Status"}),e.jsxs(ge,{value:o.value||"",onValueChange:n=>o.onChange(n||null),children:[e.jsx(Z,{children:e.jsx(xe,{children:e.jsx(fe,{placeholder:"Select status"})})}),e.jsxs(je,{children:[e.jsx(E,{value:"For Sale",children:"For Sale"}),e.jsx(E,{value:"For Rent",children:"For Rent"}),e.jsx(E,{value:"Sold",children:"Sold"}),e.jsx(E,{value:"Rented",children:"Rented"}),e.jsx(E,{value:"Planning",children:"Planning"})]})]}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"estimated_value",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Estimated Value ($)"}),e.jsx(Z,{children:e.jsx(W,{type:"number",placeholder:"0",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value?Number(n.target.value):null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"latitude",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Latitude"}),e.jsx(Z,{children:e.jsx(W,{type:"number",step:"any",placeholder:"14.5995",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value?Number(n.target.value):null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"longitude",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Longitude"}),e.jsx(Z,{children:e.jsx(W,{type:"number",step:"any",placeholder:"120.9842",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value?Number(n.target.value):null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"image_url",render:({field:o})=>e.jsxs($,{className:"col-span-full",children:[e.jsx(U,{children:"Image URL"}),e.jsx(Z,{children:e.jsx(W,{placeholder:"https://...",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value||null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"listing_url",render:({field:o})=>e.jsxs($,{className:"col-span-full",children:[e.jsx(U,{children:"Listing URL"}),e.jsx(Z,{children:e.jsx(W,{placeholder:"https://...",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value||null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"description",render:({field:o})=>e.jsxs($,{className:"col-span-full",children:[e.jsx(U,{children:"Description"}),e.jsx(Z,{children:e.jsx(De,{placeholder:"Property description...",rows:3,...o,value:o.value??"",onChange:n=>o.onChange(n.target.value||null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"notes",render:({field:o})=>e.jsxs($,{className:"col-span-full",children:[e.jsx(U,{children:"Private Notes"}),e.jsx(Z,{children:e.jsx(De,{placeholder:"Your private notes...",rows:2,...o,value:o.value??"",onChange:n=>o.onChange(n.target.value||null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"contact_name",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Contact Name"}),e.jsx(Z,{children:e.jsx(W,{placeholder:"Agent/Owner name",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value||null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"contact_phone",render:({field:o})=>e.jsxs($,{children:[e.jsx(U,{children:"Contact Phone"}),e.jsx(Z,{children:e.jsx(W,{placeholder:"+1234567890",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value||null)})}),e.jsx(q,{})]})}),e.jsx(B,{control:i.control,name:"contact_email",render:({field:o})=>e.jsxs($,{className:"col-span-full",children:[e.jsx(U,{children:"Contact Email"}),e.jsx(Z,{children:e.jsx(W,{type:"email",placeholder:"[email protected]",...o,value:o.value??"",onChange:n=>o.onChange(n.target.value||null)})}),e.jsx(q,{})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(S,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(S,{type:"submit",disabled:l,children:[l&&e.jsx(Me,{className:"w-4 h-4 mr-2 animate-spin"}),s?"Update Property":"Add Property"]})]})]})})]})})}const tr=50;function sr({open:a,onOpenChange:t,onImport:s,isImporting:r,existingLinkedIds:l,selectedPortfolioId:i,selectedPortfolioName:c}){const{toast:o}
12=Se(),[n,p]=x.useState(""),[d,u]=x.useState(""),[h,g]=x.useState(new Set),[m,y]=x.useState("scouting"),[v,f]=x.useState(0),[_,P]=x.useState(0),[F,O]=x.useState(0),[Y,j]=x.useState(null),[L,G]=x.useState(!1),H=x.useRef(!1),[R,C]=x.useState([]),[K,he]=x.useState(null),[oe,b]=x.useState(!1),[D,M]=x.useState(!1),[T,te]=x.useState([]),se=x.useRef(0);x.useEffect(()=>{const w=setTimeout(()=>{u(n)},300);return()=>clearTimeout(w)},[n]);const ne=x.useCallback(async(w=1,I=!1)=>{w===1?b(!0):M(!0);try{const k=localStorage.getItem("currentOrganizationId"),{data:J,error:A}=await z.functions.invoke("jha-properties-paginated",{body:{page:w,pageSize:tr,search:d,portfolioId:i,organizationId:k}});if(A)throw A;J.success&&(C(I?V=>[...V,...J.data]:J.data),he(J.pagination),te(J.alreadyImportedIds||[]))}catch(k){console.error("Error fetching JHA properties:",k),o({title:"Error loading properties",description:"Could not load JHA properties. Please try again.",variant:"destructive"})}finally{b(!1),M(!1)}},[d,i,o]);x.useEffect(()=>{a&&(C([]),he(null),g(new Set),G(!1),H.current=!1,ne(1))},[a,ne]),x.useEffect(()=>{a&&d!==void 0&&ne(1)},[d,a,ne]);const Oe=()=>{K&&K.hasMore&&ne(K.page+1,!0)},me=w=>T.includes(w),ve=w=>l.includes(w),le=x.useMemo(()=>i?R.filter(w=>!me(w.id)).length:R.filter(w=>!ve(w.id)).length,[R,i,T,l]),Re=w=>{g(I=>{const k=new Set(I);return k.has(w)?k.delete(w):k.add(w),k})},Ee=async()=>{f(0),P(0),G(!1),H.current=!1,se.current=Date.now();const w=R.filter(I=>h.has(I.id));O(w.length),await s(w,m,I=>{if(H.current)return;f(I);const k=Math.round(I/100*w.length);if(P(k),k>0){const A=(Date.now()-se.current)/k,V=(w.length-k)*A;V>6e4?j(`~${Math.ceil(V/6e4)} min remaining`):V>1e3?j(`~${Math.ceil(V/1e3)} sec remaining`):j("Almost done...")}}),g(new Set),f(0),j(null),t(!1)},N=async()=>{f(0),P(0),G(!1),H.current=!1,se.current=Date.now();const w=i?R.filter(I=>!me(I.id)):R.filter(I=>!ve(I.id));w.length!==0&&(O(w.length),await s(w,m,I=>{if(H.current)return;f(I);const k=Math.round(I/100*w.length);if(P(k),k>0){const A=(Date.now()-se.current)/k,V=(w.length-k)*A;V>6e4?j(`~${Math.ceil(V/6e4)} min remaining`):V>1e3?j(`~${Math.ceil(V/1e3)} sec remaining`):j("Almost done...")}}),g(new Set),f(0),j(null),t(!1))},ee=()=>{H.current=!0,G(!0),o({title:"Import cancelled",description:`Imported ${_} of ${F} properties.`})};return e.jsx(be,{open:a,onOpenChange:t,children:e.jsxs(Ne,{className:"max-w-2xl max-h-[80vh] flex flex-col",children:[e.jsx(Ce,{children:e.jsxs(_e,{className:"flex items-center gap-2",children:["Import from JHA Data",c&&e.jsxs(ue,{variant:"outline",className:"font-normal",children:["to ",c]})]})}),e.jsxs("div",{className:"flex gap-3 items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(W,{placeholder:"Search properties...",value:n,onChange:w=>p(w.target.value),className:"pl-9",disabled:r})]}),e.jsxs(ge,{value:m,onValueChange:w=>y(w),children:[e.jsx(xe,{className:"w-36",children:e.jsx(fe,{placeholder:"Category"})}),e.jsxs(je,{children:[e.jsx(E,{value:"scouting",children:"Scouting"}),e.jsx(E,{value:"watching",children:"Watching"}),e.jsx(E,{value:"potential",children:"Potential"}),e.jsx(E,{value:"owned",children:"Owned"})]})]})]}),r&&e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Importing ",_," of ",F," properties"]}),Y&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Y})]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:ee,disabled:L,children:[e.jsx(ut,{className:"w-4 h-4 mr-1"}),"Cancel"]})]}),e.jsx(ft,{value:v,className:"h-2"})]}),K&&!r&&e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground px-1",children:[e.jsxs("span",{children:["Showing ",R.length," of ",K.total," properties"]}),le>0&&e.jsxs("span",{className:"text-primary font-medium",children:[le," available to import"]})]}),e.jsx(xt,{className:"flex-1 -mx-6 px-6",children:oe?e.jsx("div",{className:"space-y-3",children:[1,2,3,4,5].map(w=>e.jsx(ht,{className:"h-20 w-full"},w))}):R.length===0?e.jsxs("div",{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Fe,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No JHA properties found"}),d&&e.jsx("p",{className:"text-sm mt-1",children:"Try a different search term"})]}):e.jsxs("div",{className:"space-y-2",children:[R.map(w=>{const I=i&&me(w.id),k=ve(w.id),J=I||k&&!i,A=h.has(w.id);return e.jsxs("div",{className:`flex gap-3 p-3 rounded-lg border transition-colors ${J?"bg-muted/50 opacity-60":A?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(es,{checked:A,disabled:J||r,onCheckedChange:()=>Re(w.id)}),e.jsx("div",{className:"w-16 h-16 rounded-md bg-muted shrink-0 overflow-hidden",children:w.representative_image_url?e.jsx("img",{src:w.representative_image_url,alt:w.title||"Property",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fe,{className:"w-6 h-6 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h4",{className:"font-medium text-sm truncate",children:w.title||"Untitled Property"}),I&&e.jsxs(ue,{variant:"secondary",className:"text-xs shrink-0 bg-amber-100 text-amber-700",children:[e.jsx(_t,{className:"w-3 h-3 mr-1"}),"In portfolio"]}),k&&!i&&e.jsx(ue,{variant:"secondary",className:"text-xs shrink-0",children:"Already imported"}),k&&i&&!I&&e.jsx(ue,{variant:"outline",className:"text-xs shrink-0",children:"In other portfolio"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1 mt-0.5",children:[e.jsx(ke,{className:"w-3 h-3 shrink-0"}),w.address||"No address"]}),e.jsxs("div",{className:"flex gap-3 mt-1 text-xs text-muted-foreground",children:[w.price&&e.jsxs("span",{className:"font-medium",children:["$",w.price.toLocaleStr
12ing()]}),w.bedrooms&&e.jsxs("span",{children:[w.bedrooms," beds"]}),w.bathrooms&&e.jsxs("span",{children:[w.bathrooms," baths"]})]})]})]},w.id)}),(K==null?void 0:K.hasMore)&&e.jsx("div",{className:"pt-4 pb-2 flex justify-center",children:e.jsx(S,{variant:"outline",onClick:Oe,disabled:D||r,className:"w-full max-w-xs",children:D?e.jsxs(e.Fragment,{children:[e.jsx(Me,{className:"w-4 h-4 mr-2 animate-spin"}),"Loading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{className:"w-4 h-4 mr-2"}),"Load More (",K.total-R.length," remaining)"]})})})]})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[h.size," selected"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(S,{variant:"outline",onClick:()=>t(!1),disabled:r,children:"Cancel"}),le>0&&e.jsxs(S,{variant:"outline",onClick:N,disabled:r||oe,children:[e.jsx(ts,{className:"w-4 h-4 mr-2"}),"Import All (",le,")"]}),e.jsxs(S,{onClick:Ee,disabled:h.size===0||r,children:[e.jsx(jt,{className:"w-4 h-4 mr-2"}),r?"Importing...":`Import ${h.size>0?`(${h.size})`:""}`]})]})]})]})})}function lt({selectedPortfolio:a,onSelectPortfolio:t,className:s}){const{portfolios:r,isLoading:l,createPortfolio:i,updatePortfolio:c,deletePortfolio:o,publishPortfolio:n}=wt(),{toast:p}=Se(),[d,u]=x.useState(!1),[h,g]=x.useState(null),[m,y]=x.useState(null),[v,f]=x.useState({title:"",description:""}),_=()=>{v.title.trim()&&i.mutate({title:v.title,description:v.description||null,listing_type:"mixed",theme_color:"#3b82f6"},{onSuccess:()=>{u(!1),f({title:"",description:""})}})},P=()=>{!h||!v.title.trim()||c.mutate({id:h.id,title:v.title,description:v.description||null},{onSuccess:()=>{g(null),f({title:"",description:""})}})},F=()=>{m&&o.mutate(m.id,{onSuccess:()=>{(a==null?void 0:a.id)===m.id&&t(null),y(null)}})},O=j=>{const L=`${window.location.origin}/mapfolio/${j.public_token}`;navigator.clipboard.writeText(L),p({title:"Link copied to clipboard"})},Y=j=>{n.mutate({id:j.id,isPublished:!j.is_published})};return e.jsxs("div",{className:X("flex flex-col h-full bg-background border-r",s),children:[e.jsxs("div",{className:"p-3 border-b",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"font-semibold text-sm",children:"Portfolios"}),e.jsx(S,{size:"sm",variant:"ghost",onClick:()=>{f({title:"",description:""}),u(!0)},children:e.jsx(He,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.length," portfolio",r.length!==1?"s":""]})]}),e.jsx(xt,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1",children:[e.jsx(Te,{className:X("cursor-pointer transition-all hover:bg-accent/50",!a&&"ring-2 ring-primary bg-accent"),onClick:()=>t(null),children:e.jsx(Ge,{className:"p-2.5",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:"All Properties"})]})})}),l?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Loading..."}):r.length===0?e.jsxs("div",{className:"p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No portfolios yet"}),e.jsxs(S,{size:"sm",variant:"outline",onClick:()=>{f({title:"",description:""}),u(!0)},children:[e.jsx(He,{className:"h-3 w-3 mr-1"}),"Create"]})]}):r.map(j=>e.jsx(Te,{className:X("cursor-pointer transition-all hover:bg-accent/50",(a==null?void 0:a.id)===j.id&&"ring-2 ring-primary bg-accent"),onClick:()=>t(j),children:e.jsx(Ge,{className:"p-2.5",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:j.title}),j.is_published?e.jsx(ue,{variant:"default",className:"text-[10px] px-1 py-0 h-4",children:"Live"}):e.jsx(ue,{variant:"secondary",className:"text-[10px] px-1 py-0 h-4",children:"Draft"})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[j.property_count||0," properties ⢠",j.view_count," views"]})]}),e.jsxs(ss,{children:[e.jsx(rs,{asChild:!0,onClick:L=>L.stopPropagation(),children:e.jsx(S,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(ms,{className:"h-3.5 w-3.5"})})}),e.jsxs(ns,{align:"end",children:[e.jsxs(Pe,{onClick:L=>
12{L.stopPropagation(),f({title:j.title,description:j.description||""}),g(j)},children:[e.jsx(pt,{className:"h-3.5 w-3.5 mr-2"}),"Edit"]}),e.jsx(Pe,{onClick:L=>{L.stopPropagation(),Y(j)},children:j.is_published?e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"h-3.5 w-3.5 mr-2"}),"Unpublish"]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"h-3.5 w-3.5 mr-2"}),"Publish"]})}),j.is_published&&e.jsxs(Pe,{onClick:L=>{L.stopPropagation(),O(j)},children:[e.jsx(vt,{className:"h-3.5 w-3.5 mr-2"}),"Share Link"]}),e.jsxs(Pe,{className:"text-destructive",onClick:L=>{L.stopPropagation(),y(j)},children:[e.jsx(Qe,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})})},j.id))]})}),e.jsx(be,{open:d,onOpenChange:u,children:e.jsxs(Ne,{children:[e.jsx(Ce,{children:e.jsx(_e,{children:"Create Portfolio"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Ae,{htmlFor:"title",children:"Title"}),e.jsx(W,{id:"title",value:v.title,onChange:j=>f({...v,title:j.target.value}),placeholder:"My Investment Portfolio"})]}),e.jsxs("div",{children:[e.jsx(Ae,{htmlFor:"description",children:"Description (optional)"}),e.jsx(De,{id:"description",value:v.description,onChange:j=>f({...v,description:j.target.value}),placeholder:"A collection of investment properties...",rows:3})]})]}),e.jsxs(Xe,{children:[e.jsx(S,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(S,{onClick:_,disabled:i.isPending,children:"Create"})]})]})}),e.jsx(be,{open:!!h,onOpenChange:j=>!j&&g(null),children:e.jsxs(Ne,{children:[e.jsx(Ce,{children:e.jsx(_e,{children:"Edit Portfolio"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(Ae,{htmlFor:"edit-title",children:"Title"}),e.jsx(W,{id:"edit-title",value:v.title,onChange:j=>f({...v,title:j.target.value})})]}),e.jsxs("div",{children:[e.jsx(Ae,{htmlFor:"edit-description",children:"Description"}),e.jsx(De,{id:"edit-description",value:v.description,onChange:j=>f({...v,description:j.target.value}),rows:3})]})]}),e.jsxs(Xe,{children:[e.jsx(S,{variant:"outline",onClick:()=>g(null),children:"Cancel"}),e.jsx(S,{onClick:P,disabled:c.isPending,children:"Save"})]})]})}),e.jsx(as,{open:!!m,onOpenChange:j=>!j&&y(null),children:e.jsxs(is,{children:[e.jsxs(os,{children:[e.jsx(ls,{children:"Delete Portfolio?"}),e.jsxs(cs,{children:['This will permanently delete "',m==null?void 0:m.title,'" and remove all property assignments.']})]}),e.jsxs(ds,{children:[e.jsx(us,{children:"Cancel"}),e.jsx(hs,{onClick:F,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function rr({open:a,progress:t}){const s=t.total>0?Math.round(t.processed/t.total*100):0;return e.jsx(be,{open:a,children:e.jsxs(Ne,{className:"sm:max-w-md",onPointerDownOutside:r=>r.preventDefault(),children:[e.jsxs(Ce,{children:[e.jsxs(_e,{className:"flex items-center gap-2",children:[e.jsx(ke,{className:"w-5 h-5 text-primary"}),"Geocoding Addresses"]}),e.jsx(kt,{children:"Converting property addresses to map coordinates using Google Maps API."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:t.isRunning?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Me,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):"Complete"}),e.jsxs("span",{className:"font-medium",children:[t.processed," / ",t.total]})]}),e.jsx(ft,{value:s,className:"h-2"}),e.jsxs("div",{className:"flex justify-center gap-6 pt-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(gs,{className:"w-4 h-4 text-emerald-500"}),e.jsx("span",{className:"text-muted-foreground",children:"Success:"}),e.jsx("span",{className:"font-medium",children:t.success})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(xs,{className:"w-4 h-4 text-red-500"}),e.jsx("span",{className:"text-muted-foreground",children:"Failed:"}),e.jsx("span",{className:"font-medium",children:t.failed})]})]}),!t.isRunning&&t.processed>0&&e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"You can close this dialog. Refresh the map to see updated pins."})]})]})})}const sn=()=>{var Ee;const a=bs(),{toast:t}=Se(),s=ps(),r=ct(),{properties:l,isLoading:i,createProperty:c,updateProperty:o,deleteProperty:n}
12=Et(),{addPropertyToPortfolio:p}=wt(),{progress:d,geocodePropertiesWithMissingCoords:u}=Ss(),[h,g]=x.useState(null),[m,y]=x.useState(null),[v,f]=x.useState("all"),[_,P]=x.useState("all"),[F,O]=x.useState(""),[Y,j]=x.useState("map"),[L,G]=x.useState(!1),[H,R]=x.useState(null),[C,K]=x.useState(!1),[he,oe]=x.useState(!1),{data:b}=_s((m==null?void 0:m.id)||null),D=new Set(((Ee=b==null?void 0:b.properties)==null?void 0:Ee.map(N=>N.investment_property_id))||[]),M=l.filter(N=>N.jha_property_id).map(N=>N.jha_property_id),T=l.filter(N=>{if(m&&!D.has(N.id)||v!=="all"&&N.category!==v||_!=="all"&&N.property_type!==_)return!1;if(F){const ee=F.toLowerCase();return N.title.toLowerCase().includes(ee)||N.address.toLowerCase().includes(ee)}return!0}),te=x.useMemo(()=>l.filter(N=>!N.latitude||!N.longitude).length,[l]),se=async()=>{await u(),r.invalidateQueries({queryKey:["investment-properties"]})},ne=x.useCallback(N=>{g(ee=>ee===N?null:N)},[]),Oe=()=>{R(null),G(!0)},me=N=>{R(N),G(!0)},ve=async N=>{if(H)await o.mutateAsync({id:H.id,...N});else{const ee=await c.mutateAsync(N);m&&ee&&await p.mutateAsync({portfolioId:m.id,propertyId:ee.id})}G(!1),R(null)},le=async N=>{await n.mutateAsync(N),h===N&&g(null)},Re=()=>{if(!m)return;const N=`${window.location.origin}/mapfolio/${m.public_token}`;navigator.clipboard.writeText(N),t({title:"Link copied to clipboard"})};return e.jsxs("div",{className:"h-screen flex flex-col bg-background",children:[e.jsxs("header",{className:"border-b bg-card px-4 py-3 flex items-center gap-3 shrink-0",children:[e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>a("/property-view"),children:e.jsx(Ns,{className:"w-5 h-5"})}),s&&e.jsxs(vs,{children:[e.jsx(ws,{asChild:!0,children:e.jsxs(S,{variant:"outline",size:"sm",className:"shrink-0",children:[e.jsx(st,{className:"h-4 w-4 mr-1"}),(m==null?void 0:m.title)||"All"]})}),e.jsx(ys,{side:"left",className:"p-0 w-72",children:e.jsx(lt,{selectedPortfolio:m,onSelectPortfolio:y,className:"h-full"})})]}),e.jsx("h1",{className:X("font-semibold flex-1 truncate",s?"text-base":"text-xl"),children:(m==null?void 0:m.title)||"Investment Tracker"}),s&&e.jsx(fs,{value:Y,onValueChange:N=>j(N),children:e.jsxs(js,{className:"h-9",children:[e.jsx(tt,{value:"list",className:"px-3",children:e.jsx(st,{className:"w-4 h-4"})}),e.jsx(tt,{value:"map",className:"px-3",children:e.jsx(Cs,{className:"w-4 h-4"})})]})}),(m==null?void 0:m.is_published)&&e.jsxs(S,{variant:"outline",size:"sm",onClick:Re,children:[e.jsx(vt,{className:"w-4 h-4"}),!s&&e.jsx("span",{className:"ml-1",children:"Share"})]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>K(!0),children:[e.jsx(jt,{className:"w-4 h-4"}),!s&&e.jsx("span",{className:"ml-1",children:"Import"})]}),e.jsxs(S,{size:"sm",onClick:Oe,children:[e.jsx(He,{className:"w-4 h-4"}),!s&&e.jsx("span",{className:"ml-1",children:"Add"})]})]}),e.jsx(Js,{categoryFilter:v,setCategoryFilter:f,typeFilter:_,setTypeFilter:P,searchQuery:F,setSearchQuery:O,propertyCount:T.length,missingCoordsCount:te,onFixMissingCoords:se,isGeocoding:d.isRunning}),e.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[!s&&e.jsx(lt,{selectedPortfolio:m,onSelectPortfolio:y,className:"w-56 shrink-0"}),e.jsx("div",{className:`w-full md:w-72 lg:w-80 border-r bg-card overflow-hidden flex flex-col ${Y==="map"?"hidden md:flex":"flex"}`,children:e.jsx(As,{properties:T,selectedPropertyId:h,onPropertyClick:ne,onEditProperty:me,onDeleteProperty:le,isLoading:i})}),e.jsx("div",{className:`flex-1 ${Y==="list"?"hidden md:block":"block"}`,children:e.jsx(Ys,{properties:T,selectedPropertyId:h,onPropertyClick:ne,onEditProperty:me,onDeleteProperty:le})})]}),e.jsx(er,{open:L,onOpenChange:G,property:H,onSave:ve,isLoading:c.isPending||o.isPending}),e.jsx(sr,{open:C,onOpenChange:K,selectedPortfolioId:m==null?void 0:m.id,selectedPortfolioName:m==null?void 0:m.title,existingLinkedIds:M,isImporting:he,onImport:async(N,ee,w)=>{oe(!0);try{for(let k=0;k<N.length;k+=10){const J=N.slice(k,k+10);await Promise.all(J.map(async A=>{const V=await c.mutateAsync({title:A.title||"Untitled Property",address:A.address||"",latitude:A.lat,longitude:A.lng,estimated_value:A.price,image_url:A.representative_image_url,listing_url:A.source_url,description:A.description,property_type:A.property_type,contact_name:A.agent_name,contact_phone:A.agent_phone,jha_property_id:A.id,category:ee,is_public:!1});m&&V&&await p.mutateAsync({portfolioId:m.id,propertyId:V.id})})),w==null||w((k+J.length)/N.length*100)}}finally{oe(!1)}}}),e.jsx(rr,{open:d.isRunning||d.processed>0&&d.processed===d.total,progress:d})]})};export{sn 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.