1import{i as Ft,c as t,r as i,j as f,T as q,B as G,l as gt,t as R,u as Ut,b as jt,q as qt,k as zt,d as ve,g as pe,F as Wt,S as $t,n as nt,P as qe,I as ze,h as it}from"./index-tAWMy1gn.js";import{d as We,L as Ht,A as Kt,D as Gt}from"./DatePicker-DtwaR3Z7.js";/* empty css */import{S as ht}from"./SidePanel-BoAD_fzh.js";import{F as Re,I as Te,S as De,T as M,a as Yt}from"./TextField-BylU5aXr.js";import{M as ie}from"./MenuItem-6X63peVZ.js";import{A as Zt,C as Xt,l as Jt}from"./googleMapsLoader-Bv6Oy1Uh.js";import{C as bt}from"./Chip-DR7AnK4m.js";import{G as h}from"./Grid-Cq5Nc5q_.js";import{E as Qt}from"./ExpandMore-BwAKSc_L.js";import{C as Vt}from"./Collapse-_8gmMfnV.js";import{F as er}from"./FormControlLabel-CabZ8Ilq.js";import{A as tr,E as rr}from"./Edit-DRsoB175.js";import{D as nr,a as ir}from"./Delete-H_1K-G2J.js";import{M as or}from"./Modal-CQkdqTe5.js";import{D as lr}from"./Dialog-DRPjSRZo.js";import{D as sr,a as ar}from"./DialogTitle-65ne_2WF.js";import{D as cr}from"./DialogContent-DbXXRCsh.js";import"./Stack-CoPCaYsK.js";import"./InputAdornment-CKm9Dh5a.js";import"./Button-CmO21ur9.js";import"./List-C4MvHZeR.js";import"./ListContext-B0_9D8qv.js";import"./ListItem-BHepOfPZ.js";import"./index-BwqtTtay.js";import"./listItemIconClasses-BOEH3G7l.js";import"./listItemTextClasses-BtNYjTAf.js";import"./dividerClasses-DubNWCLK.js";const ur=Ft(t("path",{d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}),"Close"),me=({type:o,value:u,onChange:g,label:s,required:ee=!1,disabled:E=!1,error:oe=!1,helperText:w="",parentValue:S=null,parentType:T=null,onLocationSelect:N=null,placeholder:c="",allowCustomEntry:Y=!0,disableFreeText:fe=!1,loadAllOptions:D=!1,apiEndpoint:L="/api/",popperZIndex:k="auto",parentIsManual:H=!1})=>{const[_,z]=i.useState([]),[Q,we]=i.useState([]),[K,Be]=i.useState(!1),[le,te]=i.useState(""),[he,Le]=i.useState(!1),[$e,Ce]=i.useState(!1),[se,ge]=i.useState(!1),re=i.useRef(null),Oe=i.useRef(!0),He=i.useRef(S),Me=i.useRef(null),Se=i.useRef(!1),Ke=i.useRef(u);i.useEffect(()=>{const l=setTimeout(()=>{Oe.current=!1},2e3);return()=>clearTimeout(l)},[]),i.useEffect(()=>{const l=u!==Ke.current;Ke.current=u,!Se.current&&l&&(u&&!$e?te(u):u||te(""))},[u,$e]);const V=i.useCallback(async(l="")=>{if(!K){if(Q.length>0){const a=l?Q.filter(m=>m.name.toLowerCase().includes(l.toLowerCase())):Q;z(a);return}Be(!0);try{if(o==="suburb"&&T==="city"&&H){z([]),Be(!1);return}let a="";const m=new URLSearchParams;switch(o){case"province":a=`${L}provinces/`;break;case"city":a=`${L}cities/`;break;case"suburb":a=`${L}suburbs/`;break;default:a=`${L}locations/search/`}l&&m.append("q",l),o==="city"&&S&&T==="province"?m.append("province_id",S):o==="suburb"&&S&&T==="city"&&m.append("city_id",S),m.toString()&&(a+=`?${m.toString()}`),o==="city"&&console.log("[City] Fetching from URL:",a,"parentValue:",S);const A=await fetch(a);if(!A.ok)throw new Error(`HTTP error! status: ${A.status}`);const X=await A.json();let ne=[];a.includes("locations/search/")?ne=X.results.filter(C=>C.type===o).map(C=>({id:C.id,name:C.name,display:C.display,...C})):ne=X.map(C=>({id:C.id,name:C.name,display:C.name,...C}));const Z=ne.reduce((C,I)=>(C.find(Ye=>Ye.id===I.id)||C.push(I),C),[]);o==="city"&&console.log("[City] Fetched options count:",Z.length),we(Z);const J=l?Z.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())):Z;o==="city"&&console.log("[City] Setting options (filtered):",J.length),z(J),ge(!0)}catch(a){console.error(`Error fetching ${o} options:`,a),z([]),ge(!0)}finally{Be(!1)}}},[o,T,S,L,Q.length,H]),ot=(l,a,m)=>{if(te(a),m==="input"&&(Se.current=!0,setTimeout(()=>{Se.current=!1},500),Le(!0)),m==="input"&&a!==u&&g(a),re.current&&clearTimeout(re.current),!fe&&a&&a.length>=1)if(re.current&&clearTimeout(re.current),Q.length>0){const A=Q.filter(X=>X.name.toLowerCase().includes(a.toLowerCase()));z(A)}else re.current=setTimeout(()=>{V(a)},300);else a||Q.length>0&&z(Q)},lt=(l,a)=>{Se.current=!1,a==null?(Ce(!1),g(""),te(""),N&&N(null)):a&&typeof a=="object"?a.isCustom?(Ce(!0),te(a.name),g(a.name),N&&N({name:a.name,type:o,isCustom:!0}
1)):(Ce(!1),te(a.name),g(a.name),N&&N(a)):typeof a=="string"&&(Ce(!0),te(a),g(a),N&&N({name:a,type:o,isCustom:!0}))},st=()=>{Le(!0),!se&&!K&&_.length===0&&V()},at=()=>{Le(!1)};i.useEffect(()=>{if(o==="city"&&T==="province"||o==="suburb"&&T==="city"){const l=He.current!==S;He.current=S,S?l&&(z([]),we([]),ge(!1),Oe.current?u||te(""):(te(""),g(""),N&&N(null)),Me.current=null,V(u||"")):!Oe.current&&l&&!u&&(z([]),ge(!1),te(""),g(""),N&&N(null))}},[S,o,T,u,g,N,V]),i.useEffect(()=>{D&&!se&&_.length===0&&!K&&V()},[D,se,_.length,K,V]),i.useEffect(()=>{!D&&he&&!se&&_.length===0&&!K&&(o==="province"||o==="city"||o==="suburb"&&T==="city"&&S)&&(o==="city"&&console.log("[City] Calling fetchOptions from useEffect",{isOpen:he,parentValue:S,hasFetched:se,optionsLength:_.length}),V())},[he,S,T,D,o,V,se,_.length,K]),i.useEffect(()=>{!D&&u&&!K&&S&&!_.some(a=>a.name===u)&&!se&&Me.current!==u&&o==="city"&&T==="province"&&(Me.current=u,V(u))},[u,S,_,o,T,K,D,se,V]),i.useEffect(()=>()=>{re.current&&clearTimeout(re.current)},[]);const n=Y&&le&&le.trim()!==""&&(he||le.length>0)&&!_.some(l=>l.name.toLowerCase()===le.toLowerCase())&&(!u||u.toLowerCase()!==le.toLowerCase()),U=!1,ae=u&&_.some(l=>l.name===u),ce=[..._,...!ae&&u&&!U?[{id:"temp-current-value",name:u,display:u,isTemporary:!0}]:[],...n?[{id:"custom",name:le,display:`Add "${le}" as custom entry`,isCustom:!0}]:[]];if(fe){const a=!u||_.some(m=>m.name===u)?_:[{id:"temp",name:u,display:u},..._];return f(Re,{fullWidth:!0,error:oe,disabled:E,required:ee,children:[t(Te,{id:`${o}-select-label`,children:s}),f(De,{labelId:`${o}-select-label`,id:`${o}-select`,value:u||"",onChange:m=>{const A=m.target.value;g(A);const X=_.find(ne=>ne.name===A);X&&N?N(X):!A&&N&&N(null)},onOpen:()=>{_.length===0&&!K&&V()},label:s,disabled:E,MenuProps:{PaperProps:{style:{maxHeight:300,zIndex:k==="auto"?void 0:k}},autoFocus:!0,variant:"menu",style:{zIndex:k==="auto"?1:`${k} !important`}},children:[K&&t(ie,{disabled:!0,children:t("em",{children:"Loading..."})}),a.map(m=>t(ie,{value:m.name,children:m.display||m.name},m.id))]}),w&&t(q,{variant:"caption",color:oe?"error":"text.secondary",sx:{mt:.5,ml:1.75},children:w})]})}let _e=c;_e||(_e=`Search for ${o}...`);const Ge=u?ce.find(l=>
1l.name===u):null;return t(Zt,{freeSolo:Y&&!fe,options:ce,value:Ge,inputValue:le,onInputChange:ot,onChange:lt,onOpen:st,onClose:at,open:he,loading:K,openOnFocus:!0,autoHighlight:!0,disabled:E||U,clearOnEscape:!1,clearOnBlur:!1,selectOnFocus:!1,handleHomeEndKeys:!1,blurOnSelect:!1,filterOptions:l=>l,disablePortal:!1,componentsProps:{popper:{placement:"bottom-start",modifiers:[{name:"flip",enabled:!0},{name:"preventOverflow",enabled:!0,options:{altAxis:!0,altBoundary:!0,tether:!0,rootBoundary:"viewport",padding:8}}],sx:{zIndex:k==="auto"?1300:k,"& .MuiPaper-root":{boxShadow:"0px 5px 15px rgba(0,0,0,0.2)",border:"1px solid #ccc"}}}},getOptionLabel:l=>typeof l=="string"?l:l.display||l.name||"",getOptionKey:l=>typeof l=="string"?l:l.id||l.name,isOptionEqualToValue:(l,a)=>!l||!a?!1:typeof l=="string"&&typeof a=="string"?l===a:typeof l=="object"&&typeof a=="object"?l.id&&a.id?l.id===a.id:l.name===a.name:!1,ListboxProps:{style:{maxHeight:"300px"}},renderInput:l=>{var a;return t(M,{...l,label:s,required:ee,error:oe,helperText:w,placeholder:_e,onKeyDown:m=>{var A;(m.metaKey||m.ctrlKey)&&m.key==="a"||m.metaKey||m.ctrlKey||(A=l.inputProps)!=null&&A.onKeyDown&&l.inputProps.onKeyDown(m)},InputProps:{...l.InputProps&&{autoComplete:l.InputProps.autoComplete,autoFocus:l.InputProps.autoFocus,className:l.InputProps.className,disabled:l.InputProps.disabled,id:l.InputProps.id,inputRef:l.InputProps.inputRef,name:l.InputProps.name,onBlur:l.InputProps.onBlur,onChange:l.InputProps.onChange,onFocus:l.InputProps.onFocus,placeholder:l.InputProps.placeholder,readOnly:l.InputProps.readOnly,required:l.InputProps.required,startAdornment:l.InputProps.startAdornment,tabIndex:l.InputProps.tabIndex,type:l.InputProps.type,value:l.InputProps.value},endAdornment:f(gt,{children:[K?"â³":null,(a=l.InputProps)==null?void 0:a.endAdornment]})}})},renderOption:(l,a)=>{const{key:m,...A}=l;return t(G,{component:"li",...A,children:f(G,{sx:{display:"flex",flexDirection:"column",width:"100%"},children:[t(q,{variant:"body1",children:a.display||a.name}),a.isCustom&&t(q,{variant:"caption",color:"text.secondary",children:"Custom entry"}),a.postal_code&&f(q,{variant:"caption",color:"text.secondary",children:["Postal Code: ",a.postal_code]})]})},m)},renderTags:(l,a)=>l.map((m,A)=>i.createElement(bt,{label:m.display||m.name,...a({index:A}),key:m.id}))})};me.propTypes={type:R.oneOf(["province","city","suburb"]).isRequired,value:R.string,onChange:R.func.isRequired,label:R.string.isRequired,required:R.bool,disabled:R.bool,error:R.bool,helperText:R.string,parentValue:R.oneOfType([R.string,R.number]),parentType:R.oneOf(["province","city"]),onLocationSelect:R.func,placeholder:R.string,allowCustomEntry:R.bool,disableFreeText:R.bool,loadAllOptions:R.bool,apiEndpoint:R.string,popperZIndex:R.oneOfType([R.number,R.string])};const dr=` 2 .pac-container { 3 z-index: 9999 !important; 4 border-radius: 12px !important; 5 box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important; 6 border: 1px solid #e5e7eb !important; 7 overflow: hidden !important; 8 background: white !important; 9 max-height: 280px !important; 10 overflow-y: auto !important; 11 margin-top: 6px !important; 12 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif !important; 13 backdrop-filter: blur(8px) !important; 14 -webkit-backdrop-filter: blur(8px) !important; 15 } 16 .pac-item { 17 border-top: none !important; 18 padding: 14px 18px !important; 19 cursor: pointer !important; 20 transition: all 0.2s ease !important; 21 font-size: 14px !important; 22 line-height: 1.5 !important; 23 border-bottom: 1px solid #f9fafb !important; 24 position: relative !important; 25 background-color: white !important; 26 color: #374151 !important; 27 } 28 .pac-item:hover { 29 background-color: #f8fafc !important; 30 transform: translateX(2px) !important; 31 } 32 .pac-item:first-child { 33 border-top: none !important; 34 border-top-left-radius: 12px !important; 35 border-top-right-radius: 12px !important; 36 } 37 .pac-item:last-child { 38 border-bottom: none !important; 39 border-bottom-left-radius: 12px !important; 40 border-bottom-right-radius: 12px !important; 41 } 42 .pac-item-selected, 43 .pac-item-selected:hover { 44 background-color: #f0f9ff !important; 45 border-left: 4px solid #3b82f6 !important; 46 transform: translateX(4px) !important; 47 color: #374151 !important; 48 } 49 .pac-matched { 50 font-weight: 600 !important; 51 color: #1d4ed8 !important; 52 } 53 .pac-icon { 54 margin-right: 14px !important; 55 width: 18px !important; 56 height: 18px !important; 57 opacity: 0.7 !important; 58 } 59 .pac-item-query { 60 font-size: 14px !important; 61 color: #374151 !important; 62 font-weight: 500 !important; 63 } 64 .pac-item-query .pac-matched { 65 font-weight: 700 !important; 66 color: #1d4ed8 !important; 67 } 68 69 /* Ensure all text in pac-item is visible */ 70 .pac-item span { 71 color: #374151 !important; 72 } 73 74 /* Completely disable browser autocomplete */ 75 input[name="street"] { 76 autocomplete: off !important; 77 -webkit-autocomplete: off !important; 78 -moz-autocomplete: off !important; 79 -ms-autocomplete: off !important; 80 -o-autocomplete: off !important; 81 } 82 83 /* Hide any browser autocomplete suggestions */ 84 input[name="street"]::-webkit-autofill, 85 input[name="street"]::-webkit-autofill:hover, 86 input[name="street"]::-webkit-autofill:focus, 87 input[name="street"]::-webkit-autofill:active { 88 -webkit-box-shadow: 0 0 0 30px white inset !important; 89 -webkit-text-fill-color: inherit !important; 90 } 91 92 /* Kill Chrome's autocomplete dropdown completely */ 93 input[name="street"]::-webkit-contacts-auto-fill-button { 94 visibility: hidden; 95 display: none !important; 96 pointer-events: none; 97 position: absolute; 98 right: 0; 99 } 100`;if(typeof document<"u"&&!document.getElementById("profile-google-places-styles")){const o=document.createElement("style");o.id="profile-google-places-styles",o.textContent=dr,document.head.appendChild(o)}const pr={center:{lat:-28.4793,lng:24.6727},zoom:19,disableDefaultUI:!1,zoomControl:!0,mapTypeControl:!0,mapTypeControlOptions:{style:2,position:1,mapTypeIds:["roadmap","satellite","hybrid","terrain"]},scaleControl:!0,streetViewControl:!1,rotateControl:!1,fullscreenControl:!0},mr=({address:o,onCoordsChange:u,initialCoords:g,onMapInit:s})=>{const ee=i.useRef(null),E=i.useRef(null),oe=i.useRef(null),w=i.useRef(null),S=i.useRef(null),T=i.useRef(!1),[N,c]=i.useState(null),[Y,fe]=i.useState(!1);return i.useEffect(()=>{if(!(!N||!oe.current||!E.current))try{oe.current.geocode({address:N},(D,L)=>{if(L==="OK"&&D[0]){const k=D[0].geometry.location;if(E.current.setCenter(k),E.current.setZoom(19),o.isUserChange){w.current?w.current.setPosition(k):(w.current=ne
100w window.google.maps.Marker({map:E.current,position:k,draggable:!0}),w.current.addListener("dragend",()=>{const _=w.current.getPosition(),z={lat:_.lat(),lng:_.lng()};S.current=z,u==null||u(z)}));const H={lat:k.lat(),lng:k.lng()};S.current=H,u==null||u(H)}}})}catch(D){console.warn("Geocoding failed:",D)}},[N]),i.useEffect(()=>{const D=async()=>{try{if(await Jt(),!ee.current)return;const L=new window.google.maps.Map(ee.current,pr);if(E.current=L,oe.current=new window.google.maps.Geocoder,s==null||s(E.current,oe.current),L.addListener("click",k=>{const H=k.latLng,_={lat:H.lat(),lng:H.lng()};w.current?w.current.setPosition(H):(w.current=new window.google.maps.Marker({map:E.current,position:H,draggable:!0}),w.current.addListener("dragend",()=>{const z=w.current.getPosition(),Q={lat:z.lat(),lng:z.lng()};S.current=Q,u==null||u(Q)})),S.current=_,u==null||u(_)}),T.current=!0,g!=null&&g.lat&&(g!=null&&g.lng)){const k=new window.google.maps.LatLng(g.lat,g.lng);L.setCenter(k),L.setZoom(19),w.current=new window.google.maps.Marker({map:E.current,position:k,draggable:!0}),w.current.addListener("dragend",()=>{const H=w.current.getPosition(),_={lat:H.lat(),lng:H.lng()};S.current=_,u==null||u(_)}),S.current=g}}catch(L){console.error("Failed to initialize Google Maps:",L),fe(!0)}};return E.current||D(),()=>{w.current&&w.current.setMap(null)}},[]),i.useEffect(()=>{if(!T.current||!(g!=null&&g.lat)||!(g!=null&&g.lng)||!E.current)return;const D=new window.google.maps.LatLng(g.lat,g.lng);E.current.setCenter(D),E.current.setZoom(19),o.isUserChange&&(w.current?w.current.setPosition(D):(w.current=new window.google.maps.Marker({map:E.current,position:D,draggable:!0}),w.current.addListener("dragend",()=>{const L=w.current.getPosition(),k={lat:L.lat(),lng:L.lng()};S.current=k,u==null||u(k)})),S.current=g,u==null||u(g))},[g,o.isUserChange]),i.useEffect(()=>{if(T.current&&!(!o.street||!o.city)&&o.isUserChange&&!(g!=null&&g.lat)){const D=`${o.street}, ${o.suburb||""}, ${o.city}, ${o.province||""}, ${o.postalCode||""}, ${o.country||"South Africa"}`.replace(/,,/g,",");c(D)}},[o,g]),Y?t("div",{style:{height:"100%",width:"100%",borderRadius:"4px",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f5f5f5",border:"1px solid #ddd"},children:t(q,{color:"text.secondary",children:"Map temporarily unavailable"})}):t("div",{ref:ee,style:{height:"100%",width:"100%",borderRadius:"4px"}})},fr=i.memo(({address:o,onCoordsChange:u,initialCoords:g,onMapInit:s})=>t(G,{sx:{height:{xs:"200px",sm:"225px",md:"250px"},width:"100%",position:"relative",minHeight:"175px",maxHeight:"250px",mb:2},children:t(mr,{address:o,onCoordsChange:u,initialCoords:g,onMapInit:(ee,E)=>s==null?void 0:s(ee,E)})})),Gr=()=>{i.useEffect(()=>{document.title="My Profile - Merrypak"},[]);const{t:o}=Ut(),u=jt(),{fetchBasketCount:g}=qt(),{profile:s,fetchProfile:ee}=zt(),[E,oe]=i.useState(null),[w,S]=i.useState(!1),[T,N]=i.useState(5),[c,Y]=i.useState({title:"",firstName:"",lastName:"",email:"",phone:"",companyName:"",vatNumber:"",companyRegNumber:"",contactNumber:"",businessType:"",position:"",department:"",paymentPerson:"",street:"",suburb:"",city:"",postalCode:"",country:"South Africa",birthDate:null,billingUnit:"",billingBuilding:"",billingAddress:"",billingCity:"",billingProvince:"",billingState:"",billingPostalCode:"",billingCountry:"South Africa",useBillingInCheckout:!1,subscribeToEmails:!0}),[fe,D]=i.useState(!1),[L,k]=i.useState(!1),[H,_]=i.useState(""),[z,Q]=i.useState(!1),[we,K]=i.useState([]),[Be,le]=i.useState(!1),[te,he]=i.useState(!1),[Le,$e]=i.useState(null),[Ce,se]=i.useState(!1),[ge,re]=i.useState(null),[Oe,He]=i.useState({name:"",street:"",suburb:"",city:"",postalCode:"",country:"South Africa"}),[Me,Se]=i.useState({}),[Ke,V]=i.useState({lat:-26.2041,lng:28.0473}),[ot,lt]=i.useState(!1),[st,at]=i.useState(null),[n,U]=i.useState(null),[ae,ce]=i.useState(null),[_e,Ge]=i.useState(19),[Ae,l]=i.useState(!1),[a,m]=i.useState({open:!1,message:"",severity:"success"}),[A,X]=i.useState(!1),[ne,Z]=i.useState({show:!1,message:"",severity:"error"}),[J,C]=i.useState({}),[I,Pe]=i.useState({}),[Ye,yt]=i.useState(typeof window<"u"?window.innerWidth:1920),[xt,ct]=i.useState(!1),[Ze,Xe]=i.useState(!1),[vt,Ne]=i.useState(!0),[Je,ut]=i.useState(null),[Qe,Ve]=i.useState(null),[hr,Fe]=i.useState(null),[et,Ue]=i.useState(null),[tt,Ie]=i.useState(null),[gr,be]=i.useState(null);i.useRef(null);const je=i.useRef(null),rt=i.useRef(null);i.useEffect(()=>{if(w&&T>0){const e=setTimeout(()=>{N(r=>r-1)},1e3);return()=>clearTimeout(e)}else w&&T===0&&window.location.reload()},[w,T]),i.useEffect(()=>{try{ee()}catch(e){console.error("Error fetching profile:",e)}},[]),i.useEffect(()=>{var e;(e=u.state)!=null&&e.successMessage&&(m({open:!0,message:u.state.successMessage,severity:"success"}),window.history.replaceState({},document.title))},[u]),i.useEffect(()=>{try{s&&(Y({title:s.title||"",firstName:s.first_name||"",lastName:s.last_name||"",email:s.email||"",phone:s.phone||"",companyName:s.company_name||"",vatNumber:s.tax_number||"",companyRegNumber:s.company_reg_number||"",contactNumber:s.contact_number||"",businessType:s.business_type||"",position:s.position||"",department:s.department||"",paymentPerson:s.payment_person||"",street:s.street||"",suburb:s.suburb||"",city:s.city||"",postalCode:s.postal_code||"",country:s.country||"South Africa",birthDate:s.birth_date?We(s.birth_date):null,billingUnit:s.billing_unit||"",billingBuilding:s.billing_building||"",billingAddress:s.billing_address||"",billingCity:s.billing_city||"",billingProvince:s.billing_province||"",billingState:s.billing_state||"",billingPostalCode:s.billing_postal_code||"",billingCountry:s.billing_country||"South Africa",useBillingInCheckout:s.use_billing_in_checkout||!1,subscribeToEmails:s.subscribe_to_emails!==void 0?s.subscribe_to_emails:!1}),s.company_name||s.tax_number||s.company_reg_number||s.business_type||s.position||s.department||s.payment_person?(Xe(!0),Ne(!0)):(Xe(!1),Ne(!0)))}catch(e){console.error("Error setting form data:",e)}},[s]),i.useEffect(()=>{s&&(s.company_name||s.tax_number||s.company_reg_number||s.business_type||s.position||s.department||s.payment_person||Ne(!0))},[s]),i.useEffect(()=>{(async()=>
100{if(s&&s.billing_province)try{const v=(await(await fetch(`/api/locations/search/?q=${encodeURIComponent(s.billing_province)}`)).json()).results.find(b=>b.type==="province"&&b.name.toLowerCase()===s.billing_province.toLowerCase());if(v&&(ut(v),s.billing_city)){const P=(await(await fetch(`/api/locations/search/?q=${encodeURIComponent(s.billing_city)}`)).json()).results.find(y=>y.type==="city"&&y.name.toLowerCase()===s.billing_city.toLowerCase()&&y.province_id===v.id);if(P&&(Ve(P),s.billing_state)){const F=(await(await fetch(`/api/locations/search/?q=${encodeURIComponent(s.billing_state)}`)).json()).results.find(B=>B.type==="suburb"&&B.name.toLowerCase()===s.billing_state.toLowerCase()&&B.city_id===P.id);F&&Fe(F)}}}catch(r){console.error("Error loading billing location data:",r)}})()},[s]);const ye=i.useCallback(async()=>{try{const e=await ve.get("/api/delivery-addresses/",{params:{format:"json"}});K(e.data||[])}catch(e){console.error("Error fetching delivery addresses:",e)}},[]);i.useEffect(()=>{ye()},[ye]),i.useEffect(()=>{let e;return a.open&&(e=setTimeout(()=>{m(r=>({...r,open:!1}))},4e3)),()=>{e&&clearTimeout(e)}},[a.open]),i.useEffect(()=>{if(!Ae||!n)return;(async()=>{if(n.coordinates){const r=n.coordinates.split(",").map(Number);r.length===2&&ce({lat:r[0],lng:r[1]})}})()},[Ae,n]),i.useEffect(()=>{(async()=>{if(n&&n.province)try{const v=(await(await fetch(`/api/locations/search/?q=${encodeURIComponent(n.province)}`)).json()).results.find(b=>b.type==="province"&&b.name.toLowerCase()===n.province.toLowerCase());if(v&&(Ue(v),n.city)){const P=(await(await fetch(`/api/locations/search/?q=${encodeURIComponent(n.city)}`)).json()).results.find(y=>y.type==="city"&&y.name.toLowerCase()===n.city.toLowerCase()&&y.province_id===v.id);if(P&&(Ie(P),n.suburb)){const F=(await(await fetch(`/api/locations/search/?q=${encodeURIComponent(n.suburb)}`)).json()).results.find(B=>B.type==="suburb"&&B.name.toLowerCase()===n.suburb.toLowerCase()&&B.city_id===P.id);F&&be(F)}}}catch(r){console.error("Error loading modal location data:",r)}})()},[n]),i.useEffect(()=>{const e=()=>yt(window.innerWidth);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),i.useEffect(()=>()=>{const e=document.querySelector('input[name="street"]');e&&e._autocompleteCleanup&&e._autocompleteCleanup()},[]);const wt=i.useCallback((e,r)=>{je.current=e,rt.current=r},[]),Ct=()=>{S(!0),N(5)};if(E)return w?t("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:f("div",{className:"bg-white rounded-lg p-8 max-w-md mx-4 text-center",children:[f("div",{className:"mb-4",children:[t("div",{className:"text-6xl mb-4",children:"â ï¸"}),t("h2",{className:"text-xl font-bold text-gray-800 mb-2",children:"Something went wrong"}),t("p",{className:"text-gray-600 mb-4",children:"An error occurred. The page will refresh automatically to resolve the issue."})]}),t("div",{className:"relative mb-4",children:f("div",{className:"w-32 h-32 mx-auto relative",children:[t("div",{className:"absolute inset-0 border-4 border-red-200 rounded-full animate-spin border-t-red-600"}),f("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[t("span",{className:"text-4xl font-bold text-red-600 mb-1",children:T}),t("span",{className:"text-xs text-gray-500 text-center leading-tight",children:"reloading..."})]})]})}),t("button",{onClick:()=>{window.location.reload()},className:"mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"Refresh Now"})]})}):f("div",{style:{height:"100vh",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",padding:"20px"},children:[t(q,{variant:"h6",color:"error",gutterBottom:!0,children:"Something went wrong"}),t(q,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"We encountered an error while loading this content."}),t(pe.Button,{onClick:Ct,variant:"filled",className:"mt-4",children:"Reload Page"})]});const dt=[{value:"South Africa",label:"South Africa"},{value:"Namibia",label:"Namibia"}],St=[{value:"",label:"Select Business Type"},{value:"Pty Ltd",label:"Pty Ltd"},{value:"CC",label:"CC"},{value:"Sole Trader",label:"Sole Trader"},{value:"Partnership",label:"Partnership"}],j=e=>{const{name:r,value:d,type:v,checked:b}=e.target;Y(W=>({...W,[r]:v==="checkbox"?b:d}
100))},_t=(e,r)=>{const d=r&&We.isDayjs(r)?r:null;Y(v=>({...v,[e]:d}))},xe=()=>{const e=document.querySelector('input[name="street"]');e&&e._autocompleteCleanup&&e._autocompleteCleanup();const r=document.querySelector(".pac-container");r&&(r.style.display="none",r.style.visibility="hidden",r.remove())},Pt=()=>{xe(),U(null),ce(null),Ue(null),Ie(null),be(null),C({}),Z({show:!1,message:"",severity:"error"}),l(!0)},Nt=e=>{U({...e,isUserChange:!1,country:e.country||"South Africa"});let r=null;if(e.latitude&&e.longitude){const d=parseFloat(e.latitude),v=parseFloat(e.longitude);!isNaN(d)&&!isNaN(v)&&(r={lat:d,lng:v},console.log("Loading address with valid coords:",r))}ce(r),Ge(e.zoom?parseInt(e.zoom):19),C({}),Z({show:!1,message:"",severity:"error"}),l(!0)},Ee=e=>{const{name:r,value:d}=e.target,v=r==="postalCode"?{postal_code:d,[r]:d}:{[r]:d},b={...n,...v,isUserChange:!1};if(U(b),C(W=>({...W,[r]:""})),r==="country"&&b.street&&b.city&&r!=="additional_instructions"){const W=[b.unit?`Unit ${b.unit},`:"",b.street,b.suburb,b.city,b.province,b.postal_code,b.country||"South Africa"].filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(rt.current&&je.current)try{rt.current.geocode({address:W},(P,y)=>{if(y==="OK"&&P[0]){const O=P[0].geometry.location;je.current.setCenter(O),je.current.setZoom(19);const F={lat:O.lat(),lng:O.lng()};ce(F)}})}catch(P){console.warn("Country change geocoding failed:",P)}}},ke=e=>{var v;const r=(v=e==null?void 0:e.target)==null?void 0:v.name;["street","unit","postal_code","postalCode"].includes(r)&&(n!=null&&n.street)&&(n!=null&&n.city)&&U(b=>({...b,isUserChange:!0}))},It=async()=>{var e,r,d,v,b,W,P,y,O,F,B,ue;try{const p={};if((e=n==null?void 0:n.street)!=null&&e.trim()||(p.street="Street address is required"),(r=n==null?void 0:n.city)!=null&&r.trim()||(p.city="City is required"),(d=n==null?void 0:n.province)!=null&&d.trim()||(p.province="Province is required"),(v=n==null?void 0:n.postal_code)!=null&&v.trim()||(p.postalCode="Postal code is required"),Object.keys(p).length>0){C(p),Z({show:!0,message:"Please fill in all required fields",severity:"error"});return}const x={street:n.street.trim(),suburb:((b=n.suburb)==null?void 0:b.trim())||"",city:n.city.trim(),province:((W=n.province)==null?void 0:W.trim())||"",postal_code:n.postal_code.trim(),unit:((P=n.unit)==null?void 0:P.trim())||"",building:((y=n.building)==null?void 0:y.trim())||"",country:n.country||"South Africa",latitude:((O=ae==null?void 0:ae.lat)==null?void 0:O.toString())||null,longitude:((F=ae==null?void 0:ae.lng)==null?void 0:F.toString())||null,zoom:_e,additional_instructions:((B=n.additional_instructions)==null?void 0:B.trim())||""};let $;if(n.id)if($=await ve.put(`/api/delivery-addresses/${n.id}/`,x),$.data)xe(),l(!1),m({open:!0,message:o("auth.profile.success.address.update"),severity:"success"}),ye();else throw new Error("No response data received");else if($=await ve.post("/api/delivery-addresses/",x),$.data)xe(),l(!1),m({open:!0,message:o("auth.profile.success.address.add"),severity:"success"}),ye();else throw new Error("No response data received")}catch(p){if(console.error("Error submitting address:",p),console.error("Error response:",p.response),(ue=p.response)!=null&&ue.data){const x={};p.response.data.street&&(x.street=p.response.data.street[0]),p.response.data.city&&(x.city=p.response.data.city[0]),p.response.data.postal_code&&(x.postalCode=p.response.data.postal_code[0]),C(x),Z({show:!0,message:p.response.data.error||o("auth.profile.addressModal.requiredFields"),severity:"error"})}else Z({show:!0,message:p.message||o("auth.profile.addressModal.saveFailed"),severity:"error"})}},pt=(e,r)=>{r!=="clickaway"&&m(d=>({...d,open:!1}))},Et=e=>{re(e),X(!0)},mt=async()=>{try{await ve.delete(`/api/delivery-addresses/${ge.id}/`),await ye(),m({open:!0,message:o("auth.profile.success.address.delete"),severity:"success"})}catch{m({open:!0,message:o("auth.profile.errors.address.deleteFailed"),severity:"error"})}finally{X(!1),re(null)}},kt=async e=>{try{K(r=>r.map(d=>({...d,is_default:d.id===e}))),await ve.post(`/api/delivery-addresses/${e}/set_default/`),m({open:!0,message:o("auth.profile.success.address.setDefault"),severity:"success"})}catch{ye(),m({open:!0,message:o("auth.profile.errors.address.setDefaultFailed"),severity:"error"})}},Rt=e=>{console.log("ð handleBillingProvinceSelect called with:",e),ut(e),Ve(null),Fe(null),Y(r=>{const d={...r,billingProvince:(e==null?void 0:e.name)||"",billingCity:""};return console.log("ð Updated formData after province change - billingState:",d.billingState,"billingProvince:",d.billingProvince),d})},Tt=e=>
100{console.log("ð handleBillingCitySelect called with:",e),Ve(e),Fe(null),Y(r=>{const d={...r,billingCity:(e==null?void 0:e.name)||""};return console.log("ð Updated formData after city change - billingState:",d.billingState,"billingCity:",d.billingCity),d})},Dt=e=>{console.log("ð handleBillingSuburbSelect called with:",e),Fe(e),Y(r=>{const d=(e==null?void 0:e.name)||"";console.log("ð Setting suburb value to:",d);const v={...r,billingState:d};return console.log("ð Updated formData billingState:",v.billingState),v})},Bt=e=>{Ue(e),Ie(null),be(null),U(r=>({...r,province:(e==null?void 0:e.name)||"",city:"",suburb:"",isUserChange:!0}))},Lt=e=>{Ie(e),be(null),U(r=>({...r,city:(e==null?void 0:e.name)||"",suburb:"",isUserChange:!0}))},Ot=e=>{be(e),U(r=>({...r,suburb:(e==null?void 0:e.name)||"",isUserChange:!0}))},Mt=async e=>{var v,b,W,P;e.preventDefault(),Pe({});const r={};if(c.title||(r.title="Title is required"),c.firstName||(r.firstName="First name is required"),c.lastName||(r.lastName="Last name is required"),(!c.birthDate||!We.isDayjs(c.birthDate)||!c.birthDate.isValid())&&(r.birthDate="Date of birth is required"),(c.billingAddress||c.billingCity||c.billingState||c.billingProvince||c.billingPostalCode)&&(c.billingAddress||(r.billingAddress="Billing address is required when providing billing information"),c.billingCity||(r.billingCity="Billing city is required when providing billing information"),c.billingProvince||(r.billingProvince="Billing province is required when providing billing information"),c.billingPostalCode||(r.billingPostalCode="Billing postal code is required when providing billing information")),Object.keys(r).length>0){Pe(r);return}try{const y={title:c.title,first_name:c.firstName,last_name:c.lastName,contact_number:c.contactNumber,birth_date:c.birthDate?c.birthDate.format("YYYY-MM-DD"):null,company_name:c.companyName,tax_number:c.vatNumber,company_reg_number:c.companyRegNumber,business_type:c.businessType,position:c.position,department:c.department,payment_person:c.paymentPerson,billing_unit:c.billingUnit,billing_building:c.billingBuilding,billing_address:c.billingAddress,billing_city:c.billingCity,billing_province:c.billingProvince,billing_state:c.billingState,billing_postal_code:c.billingPostalCode,billing_country:c.billingCountry,use_billing_in_checkout:c.useBillingInCheckout,subscribe_to_emails:c.subscribeToEmails};console.log("ð Form submission payload billing_state:",y.billing_state),console.log("ð Form submission payload billing_province:",y.billing_province);const O=await ve.put("/api/profile/",y);await ee(),m({open:!0,message:O.data.message||o("auth.profile.success.update"),severity:"success"})}catch(y){let O=o("auth.profile.errors.updateFailed");if((b=(v=y.response)==null?void 0:v.data)!=null&&b.details){const F=y.response.data.details;typeof F=="object"?O=Object.entries(F).map(([B,ue])=>`${B.split("_").map(x=>x.charAt(0).toUpperCase()+x.slice(1)).join(" ")}: ${Array.isArray(ue)?ue[0]:ue}`).join(` 101`):O=F}else(P=(W=y.response)==null?void 0:W.data)!=null&&P.error&&(O=y.response.data.error);m({open:!0,message:O,severity:"error"})}},At=300+1200+60,ft=Ye<At;return t(gt,{children:f("div",{className:"flex flex-col md:flex-row",children:[t(ht,{forceHidden:ft}),t(ht,{overlayMode:!0,open:xt,onClose:()=>ct(!1)}),f("div",{className:"flex-grow p-4 md:p-6",children:[f("div",{className:"flex items-center mb-4 md:mb-5",children:[ft&&t("button",{"aria-label":"Open navigation",className:"flex items-center justify-center w-10 h-10 bg-white border border-gray-200 rounded-full shadow hover:bg-gray-100 focus:outline-none mr-3",onClick:()=>ct(!0),tabIndex:0,children:t(Wt,{size:22})}),t("div",{className:"flex-1 flex justify-center",children:t("h1",{className:"text-xl md:text-2xl font-bold text-center",children:o("auth.profile.title")})})]}),t($t,{open:a.open,autoHideDuration:6e3,onClose:pt,anchorOrigin:{vertical:"top",horizontal:"center"},sx:{zIndex:e=>e.zIndex.drawer+1},children:t(nt,{onClose:pt,severity:a.severity,sx:{width:"100%"},children:a.message})}),f(h,{container:!0,spacing:4,children:[t(h,{item:!0,xs:12,children:f(qe,{elevation:3,sx:{p:{xs:3,md:4}},children:[L&&t(nt,{color:z?"green":"red",className:"mb-4",children:H}),f("form",{onSubmit:Mt,children:[f(G,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:2,cursor:"pointer",backgroundColor:"grey.100","&:hover":{backgroundColor:"primary.light"},p:1,pl:2,borderRadius:1,transition:"background-color 0.2s"},onClick:()=>{Xe(!Ze),Ne(!0)},children:[t(q,{variant:"h6",sx:{mb:0},children:"Company Details (if applicable)"}),t(ze,{size:"small",sx:{color:"text.secondary",transform:Ze?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s"},children:t(Qt,{})})]}),t(Vt,{in:Ze,timeout:vt?300:0,onExited:()=>Ne(!1),children:f(h,{container:!0,spacing:2,sx:{mb:1,p:2},children:[t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,label:"Company Name",name:"companyName",value:c.companyName,onChange:j})}),t(h,{item:!0,xs:12,sm:6,children:f(Re,{fullWidth:!0,children:[t(Te,{children:"Business Type"}),t(De,{name:"businessType",value:c.businessType||"",onChange:j,label:"Business Type",children:St.map(e=>t(ie,{value:e.value,children:e.label},e.value))})]})}),t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,label:"VAT/Tax Number",name:"vatNumber",value:c.vatNumber,onChange:j})}),t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,label:"Company Registration Number",name:"companyRegNumber",value:c.companyRegNumber,onChange:j})}),t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,label:"Position in Company",name:"position",value:c.position,onChange:j})}),t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,label:"Department",name:"department",value:c.department,onChange:j})}),t(h,{item:!0,xs:12,children:t(M,{fullWidth:!0,label:"Person Responsible for Payment",name:"paymentPerson",value:c.paymentPerson,onChange:j})})]})}),t(G,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:2,mt:2,p:1,pl:2,borderRadius:1,backgroundColor:"grey.100"},children:t(q,{variant:"h6",sx:{mb:0},children:o("auth.profile.personalInfo")})}),f(h,{container:!0,spacing:2,sx:{p:2},children:[t(h,{item:!0,xs:12,sm:4,children:f(Re,{fullWidth:!0,required:!0,error:!!I.title,children:[t(Te,{children:"Title"}),f(De,{name:"title",value:c.title,onChange:j,label:"Title",children:[t(ie,{value:"Mr",children:"Mr"}),t(ie,{value:"Mrs",children:"Mrs"}),t(ie,{value:"Ms",children:"Ms"}),t(ie,{value:"Dr",children:"Dr"}),t(ie,{value:"Prof",children:"Prof"})]}),I.title&&t(Yt,{children:I.title})]})}),t(h,{item:!0,xs:12,sm:4,children:t(M,{fullWidth:!0,required:!0,label:"First Name",name:"firstName",value:c.firstName,onChange:j,error:!!I.firstName,helperText:I.firstName})}),t(h,{item:!0,xs:12,sm:4,children:t(M,{fullWidth:!0,required:!0,label:"Last Name",name:"lastName",value:c.lastName,onChange:j,error:!!I.lastName,helperText:I.lastName})}),t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,label:"Contact Number",name:"contactNumber",value:c.contactNumber,onChange:j})}),t(h,{item:!0,xs:12,sm:6,children:t(Ht,{dateAdapter:Kt,children:t(Gt,{label:"Date of Birth",value:c.birthDate,onChange:e=>_t("birthDate",e),slotProps:{textField:{fullWidth:!0,required:!0,error:!!I.birthDate,helperText:I.birthDate}},maxDate:We().subtract(18,"year")})})})]}),t(G,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:2,mt:2,p:1,pl:2,borderRadius:1,backgroundColor:"grey.100"},children:t(q,{variant:"h6",sx:{mb:0},children:"Billing Address"})}),f(h,{container:!0,spacing:2,sx:{p:2},children:[t(h,{item:!0,xs:12,sm:2,children:t(M,{fullWidth:!0,label:"Unit",name:"billingUnit",value:c.billingUnit,onChange:j,placeholder:"Unit number"})}),t(h,{item:!0,xs:12,sm:2,children:t(M,{fullWidth:!0,label:"Building",name:"billingBuilding",value:c.billingBuilding,onChange:j,placeholder:"Building name"})}),t(h,{item:!0,xs:12,sm:8,children:t(M,{fullWidth:!0,label:"Street Address",name:"billingAddress",value:c.billingAddress,onChange:j,error:!!I.billingAddress,helperText:I.billingAddress})}),t(h,{item:!0,xs:12,sm:6,children:t(me,{type:"province",value:c.billingProvince||"",onChange:e=>{Y(r=>({...r,billingProvince:e})),I.billingProvince&&Pe(r=>({...r,billingProvince:""}))},onLocationSelect:Rt,label:"Province",required:!1,placeholder:"Select province...",disableFreeText:!0,loadAllOptions:!0,apiEndpoint:"/api/",error:!!I.billingProvince,helperText:I.billingProvince||""})}),t(h,{item:!0,xs:12,sm:6,children:t(me,{type:"city",value:c.billingCity||"",onChange:e=>{Y(r=>({...r,billingCity:e})),I.billingCity&&Pe(r=>({...r,billingCity:""}))},onLocationSelect:Tt,label:"City",required:!1,placeholder:"Search for city...",parentValue:Je==null?void 0:Je.id,parentType:"province",apiEndpoint:"/api/",error:!!I.billingCity,helperText:I.billingCity||""})}),t(h,{item:!0,xs:12,sm:6,children:t(me,{type:"suburb",value:c.billingState||"",onChange:e=>
101{console.log("ð Billing suburb onChange called with value:",e),Y(r=>{const d={...r,billingState:e||""};return console.log("ð Updated formData billingState via onChange:",d.billingState),d})},onLocationSelect:Dt,label:"Suburb",required:!1,placeholder:"Search for suburb...",parentValue:Qe==null?void 0:Qe.id,parentType:"city",apiEndpoint:"/api/"})}),t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,label:"Postal Code",name:"billingPostalCode",value:c.billingPostalCode,onChange:j,error:!!I.billingPostalCode,helperText:I.billingPostalCode})}),t(h,{item:!0,xs:12,sm:6,children:f(Re,{fullWidth:!0,children:[t(Te,{children:"Country"}),t(De,{name:"billingCountry",value:c.billingCountry,onChange:j,label:"Country",children:dt.map(e=>t(ie,{value:e.value,children:e.label},e.value))})]})}),t(h,{item:!0,xs:12,children:t(er,{control:t(Xt,{checked:c.useBillingInCheckout,onChange:j,name:"useBillingInCheckout"}),label:o("auth.profile.useBillingInCheckout")})})]}),t(G,{sx:{mt:4,display:"flex",justifyContent:"center"},children:t(pe.Button,{type:"submit",variant:"filled",style:{backgroundColor:it,color:"#fff"},children:o("auth.profile.updateButton")})})]})]})}),t(h,{item:!0,xs:12,children:f(qe,{elevation:3,sx:{p:{xs:2,md:3},"@media (max-width: 600px)":{borderRadius:0,margin:{xs:-2,md:0},borderLeft:"none",borderRight:"none"}},children:[f(G,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,"@media (max-width: 600px)":{flexDirection:"column",gap:2,alignItems:"stretch"}},children:[t(q,{variant:"h6",sx:{"@media (max-width: 600px)":{fontSize:"1.25rem",textAlign:"center"}},children:o("auth.profile.shippingAddresses")}),f(pe.Button,{variant:"filled",onClick:Pt,className:"flex items-center justify-center gap-2",style:{backgroundColor:it,color:"#fff"},sx:{"@media (max-width: 600px)":{width:"100%",padding:"12px",display:"flex",alignItems:"center",justifyContent:"center"}},children:[t(tr,{className:"h-5 w-5"}),t("span",{children:o("auth.profile.addAddress")})]})]}),we.length===0?f(G,{sx:{textAlign:"center",py:4,color:"text.secondary"},children:[t(q,{variant:"body1",sx:{mb:2},children:"No delivery addresses found"}),t(q,{variant:"body2",children:"Add your first delivery address to get started"})]}):we.map(e=>t(qe,{sx:{p:{xs:3,md:2},mb:{xs:3,md:2},position:"relative",borderLeft:e.is_default?"4px solid #3f51b5":"1px solid #e0e0e0","@media (max-width: 600px)":{borderRadius:2,boxShadow:"0 2px 4px rgba(0,0,0,0.1)"}},children:f(G,{sx:{display:"flex",flexDirection:{xs:"column",md:"row"},justifyContent:"space-between",alignItems:{xs:"stretch",md:"center"},gap:{xs:2,md:0}},children:[f(G,{sx:{flex:1},children:[f(G,{sx:{display:"flex",flexDirection:{xs:"column",md:"row"},alignItems:{xs:"flex-start",md:"center"},gap:{xs:1,md:2}},children:[t(q,{variant:"body1",sx:{fontWeight:500,"@media (max-width: 600px)":{fontSize:"1.1rem"}},children:[e.unit?`Unit ${e.unit}`:"",e.building||"",e.street,e.suburb,e.city,e.province,e.postal_code].filter(Boolean).join(", ")}),e.is_default&&t(bt,{label:o("auth.profile.defaultAddress"),size:"small",sx:{backgroundColor:"#3f51b5",color:"#fff","@media (max-width: 600px)":{alignSelf:"flex-start"}}})]}),t(q,{variant:"body2",sx:{color:"text.secondary",mt:1,"@media (max-width: 600px)":{fontSize:"0.95rem"}},children:e.country}),e.additional_instructions&&t(G,{sx:{mt:2,pt:2,borderTop:"1px solid",borderColor:"divider"},children:f(q,{variant:"body2",sx:{color:"text.secondary",fontStyle:"italic","@media (max-width: 600px)":{fontSize:"0.95rem"}},children:[t("strong",{children:"Delivery Instructions:"})," ",e.additional_instructions]})})]}),f(G,{sx:{display:"flex",gap:1,"@media (max-width: 600px)":{justifyContent:"flex-end",mt:2,pt:2,borderTop:"1px solid",borderColor:"divider"}},children:[!e.is_default&&t(pe.Button,{variant:"filled",size:"md",onClick:()=>kt(e.id),style:{backgroundColor:it,color:"#fff"},sx:{"@media (max-width: 600px)":{padding:"8px 16px",fontSize:"0.9rem"}},children:o("auth.profile.setDefault")}),t(ze,{onClick:()=>Nt(e),sx:{color:"text.secondary","@media (max-width: 600px)":{padding:"12px"}},children:t(rr,{})}),t(ze,{onClick:()=>Et(e),sx:{color:"error.main","@media (max-width: 600px)":{padding:"12px"}},children:t(nr,{})})]})]})},e.id))]})})]}),t(or,{open:Ae,onClose:(e,r)=>{r==="escapeKeyDown"&&(xe(),l(!1),Z({show:!1,message:"",severity:"error"}),C({}))},sx:{display:"flex",alignItems:"flex-start",justifyContent:"center",p:2,overflow:"auto",height:"100%","& .MuiModal-backdrop":{backgroundColor:"rgba(0, 0, 0, 0.5)"},"@media (max-width: 600px)":{p:0,"& .MuiPaper-root":{width:"100%",height:"100%",maxWidth:"none",maxHeight:"none",borderRadius:0,margin:0}}},disableEscapeKeyDown:!1,children:f(qe,{sx:{width:"100%",maxWidth:900,position:"relative",my:4,"@media (max-width: 600px)":{my:0,height:"100%",display:"flex",flexDirection:"column",overflow:"hidden"}},children:[t(ze,{"aria-label":"close",onClick:e=>{e.stopPropagation(),xe(),C({}),Z({show:!1,message:"",severity:"error"}),l(!1)},sx:{position:"absolute",right:8,top:8,color:e=>e.palette.grey[500],zIndex:1,"@media (max-width: 600px)":{right:16,top:16}},children:t(ur,{})}),f(G,{sx:{p:3,"@media (max-width: 600px)":{p:2,flex:1,overflow:"auto"}},children:[t(q,{variant:"h6",sx:{mb:2,"@media (max-width: 600px)":{mt:2,fontSize:"1.25rem"}},children:n!=null&&n.id?o("auth.profile.addressModal.editTitle"):o("auth.profile.addressModal.addTitle")}),ne.show&&t(nt,{severity:ne.severity,sx:{mb:2},onClose:()=>Z({...ne,show:!1}),children:ne.message}),f(h,{container:!0,spacing:2,children:[t(h,{item:!0,xs:12,sm:2,children:t(M,{fullWidth:!0,label:"Unit",name:"unit",value:(n==null?void 0:n.unit)||"",onChange:Ee,onBlur:ke})}),t(h,{item:!0,xs:12,sm:2,children:t(M,{fullWidth:!0,label:"Building",name:"building",value:(n==null?void 0:n.building)||"",onChange:Ee,onBlur:ke})}),t(h,{item:!0,xs:12,sm:8,children:t(M,{required:!0,fullWidth:!0,label:o("auth.profile.street"),name:"street",value:(n==null?void 0:n.street)||"",onChange:Ee,onBlur:ke,error:!!J.street,helperText:J.street||"ð Start typing for address suggestions",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false",inputProps:{autoComplete:"off","data-lpignore":"true","data-form-type":"other"},inputRef:e=>{if(e&&window.google&&window.google.maps&&window.google.maps.places){if(e._autocompleteInitialized)return;e._autocompleteInitialized=!0,console.log("Initializing Google Places autocomplete for street field"),setTimeout(()=>{try{const r=new window.google.maps.places.Autocomplete(e,{types:["address"],componentRestrictions:{country:["za","na"]},fields:["address_components","formatted_address","geometry","place_id"]});e._autocompleteInstance=r,r.addListener("place_changed",()=>{console.log("â
Google Places: place_changed event fired");const d=r.getPlace();if(console.log("ð Place selected:",d),d&&d.geometry&&d.place_id){console.log("â
Place has geometry and place_id, processing...");const v=d.address_components||[];let b="",W="",P="",y="",O="",F="",B="";v.forEach(p=>{const x=p.types;
101x.includes("street_number")?b=p.long_name:x.includes("route")?W=p.long_name:x.includes("sublocality_level_1")||x.includes("sublocality")||x.includes("neighborhood")?P=p.long_name:x.includes("locality")?y=p.long_name:x.includes("administrative_area_level_1")?B=p.long_name:x.includes("postal_code")?O=p.long_name:x.includes("country")&&(F=p.long_name)});const ue=`${b} ${W}`.trim();if(console.log("ð¦ Extracted data:",{street:ue,suburb:P,city:y,province:B,postalCode:O,country:F||"South Africa"}),console.log("ð Updating editingAddress state..."),U(p=>({...p,street:ue,suburb:P,city:y,province:B,postal_code:O,country:F||"South Africa",isUserChange:!0})),console.log("â
editingAddress state updated"),B&&fetch(`/api/locations/search/?q=${encodeURIComponent(B)}`).then(p=>p.json()).then(p=>{var $;const x=($=p.results)==null?void 0:$.find(de=>de.type==="province"&&de.name.toLowerCase()===B.toLowerCase());x&&Ue(x)}).catch(p=>console.warn("Province lookup failed:",p)),y&&B&&fetch(`/api/locations/search/?q=${encodeURIComponent(y)}`).then(p=>p.json()).then(p=>{var $;const x=($=p.results)==null?void 0:$.find(de=>de.type==="city"&&de.name.toLowerCase()===y.toLowerCase());x&&Ie(x)}).catch(p=>console.warn("City lookup failed:",p)),P&&y&&fetch(`/api/locations/search/?q=${encodeURIComponent(P)}`).then(p=>p.json()).then(p=>{var $;const x=($=p.results)==null?void 0:$.find(de=>de.type==="suburb"&&de.name.toLowerCase()===P.toLowerCase());x&&be(x)}).catch(p=>console.warn("Suburb lookup failed:",p)),d.geometry&&d.geometry.location){const p=d.geometry.location.lat(),x=d.geometry.location.lng(),$={lat:p,lng:x};console.log("ðºï¸ Setting coordinates:",$),ce($),console.log("â
Coordinates set - AddressMap will update marker via isUserChange flag")}else console.warn("â ï¸ No geometry data in place");setTimeout(()=>{const p=document.querySelector(".pac-container");p&&(p.style.display="none")},100)}else console.warn("â ï¸ Place missing geometry or place_id:",{hasPlace:!!d,hasGeometry:!!(d!=null&&d.geometry),hasPlaceId:!!(d!=null&&d.place_id)})}),console.log("â
Google Places autocomplete initialized for profile street field")}catch(r){console.error("Failed to initialize Google Places autocomplete:",r)}},100)}}})}),t(h,{item:!0,xs:12,sm:6,children:t(me,{type:"province",value:(n==null?void 0:n.province)||"",onChange:e=>{U(r=>({...r,province:e})),J.province&&C(r=>({...r,province:""}))},onLocationSelect:e=>{Bt(e),U(r=>({...r,province:(e==null?void 0:e.name)||""}))},label:"Province",required:!0,placeholder:"Select province...",disableFreeText:!0,loadAllOptions:!0,apiEndpoint:"/api/",error:!!J.province,helperText:J.province||"",popperZIndex:1400})}),t(h,{item:!0,xs:12,sm:6,children:t(me,{type:"city",value:(n==null?void 0:n.city)||"",onChange:e=>{U(r=>({...r,city:e})),J.city&&C(r=>({...r,city:""}))},onLocationSelect:e=>{Lt(e),U(r=>({...r,city:(e==null?void 0:e.name)||""}))},label:o("auth.profile.city"),required:!0,placeholder:"Search for city...",parentValue:et==null?void 0:et.id,parentType:"province",apiEndpoint:"/api/",error:!!J.city,helperText:J.city||"",popperZIndex:1400})}),t(h,{item:!0,xs:12,sm:6,children:t(me,{type:"suburb",value:(n==null?void 0:n.suburb)||"",onChange:e=>{U(r=>({...r,suburb:e}))},onLocationSelect:Ot,label:o("auth.profile.suburb"),required:!1,placeholder:"Search for suburb...",parentValue:tt==null?void 0:tt.id,parentType:"city",apiEndpoint:"/api/",popperZIndex:1400})}),t(h,{item:!0,xs:12,sm:6,children:t(M,{fullWidth:!0,required:!0,label:o("auth.profile.postalCode"),name:"postalCode",value:(n==null?void 0:n.postal_code)||"",onChange:Ee,onBlur:ke,error:!!J.postalCode,helperText:J.postalCode||""})}),t(h,{item:!0,xs:12,sm:6,children:f(Re,{fullWidth:!0,children:[t(Te,{id:"country-select-label",children:o("auth.profile.country")}),t(De,{labelId:"country-select-label",name:"country",value:(n==null?void 0:n.country)||"South Africa",onChange:Ee,onBlur:ke,label:o("auth.profile.country"),children:dt.map(e=>t(ie,{value:e.value,children:e.label},e.value))})]})}),t(h,{item:!0,xs:12,children:t(fr,{address:{street:(n==null?void 0:n.street)||"",suburb:(n==null?void 0:n.suburb)||"",city:(n==null?void 0:n.city)||"",province:(n==null?void 0:n.province)||"",postalCode:(n==null?void 0:n.postal_code)||"",country:(n==null?void 0:n.country)||"South Africa",isUserChange:n==null?void 0:n.isUserChange},initialCoords:ae,onCoordsChange:e=>{ce(e)},onMapInit:wt})}),t(h,{item:!0,xs:12,children:t(M,{fullWidth:!0,multiline:!0,rows:3,label:"Additional Delivery Instructions",name:"additional_instructions",value:(n==null?void 0:n.additional_instructions)||"",onChange:e=>{U(r=>({...r,additional_instructions:e.target.value}))},placeholder:"Enter any special instructions for delivery (e.g., gate code, building name, etc.)"})}
101),f(h,{item:!0,xs:12,sx:{display:"flex",justifyContent:"flex-end",gap:2,mt:2,"@media (max-width: 600px)":{position:"sticky",bottom:0,backgroundColor:"background.paper",p:2,borderTop:"1px solid",borderColor:"divider",zIndex:1}},children:[t(pe.Button,{onClick:e=>{e.stopPropagation(),xe(),C({}),Z({show:!1,message:"",severity:"error"}),l(!1)},variant:"filled",className:"bg-gray-500 hover:bg-gray-600",children:o("common.cancel")}),t(pe.Button,{onClick:It,variant:"filled",className:"bg-blue-500 hover:bg-blue-600",children:n!=null&&n.id?o("common.save"):o("common.add")})]})]})]})]})}),f(lr,{open:A,onClose:()=>X(!1),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",onKeyDown:e=>{e.key==="Enter"&&mt(),e.key==="Escape"&&X(!1)},children:[t(sr,{id:"alert-dialog-title",sx:{textAlign:"center"},children:o("auth.profile.deleteAddressConfirm.title")}),t(cr,{children:t(ir,{id:"alert-dialog-description",sx:{textAlign:"center"},children:o("auth.profile.deleteAddressConfirm.message")})}),f(ar,{sx:{justifyContent:"center",padding:"16px"},children:[t(pe.Button,{onClick:()=>X(!1),variant:"filled",className:"bg-gray-500 hover:bg-gray-600",children:o("common.cancel")}),t(pe.Button,{onClick:mt,variant:"filled",className:"bg-red-500 hover:bg-red-600 ml-4",children:o("common.confirm")})]})]})]})]})})};export{Gr 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.