PageSourceSearch

https://live-menu.vercel.app/assets/NewAdmin-UnaQZtSn.js

js live-menu.vercel.app collected 2026-10-03 07:14:39 UTC 219,305 bytes, 10 lines download raw bytes

1import{c as qe,F as se,j as e,r as f,x as Oe,G as ur,H as ls,I as Ie,B as D,s as L,l as He,A as cs,J as ys,a as ds,T as as,z as $,E as q,X as hs,K,L as Q,M as ve,N as mr,R as Nt,O as ce,S as bs,Q as xr,u as hr,U as pr}from"./index-jGBnbQC-.js";import{e as fr,s as gr,m as jr,Z as vr,F as yr,S as br,a as _t,u as wt,b as Nr,c as Ge,B as St,P as _r,d as wr,f as Ct,C as ua,g as Sr,h as Cr,i as kr,j as Er,k as rs,l as Mr,n as Pr,R as Us,T as Ar,o as Dr}from"./checkbox-lr5UD_EN.js";import{P as aa,C as Fr,u as Rr}from"./progress-FIv2FnqF.js";import{T as _s,a as ws,b as Ee,c as Me,L as Oa}from"./tabs-CfL2kHbF.js";import{M as ms,S as Re,a as Te,b as Le,c as Ve,d as le,e as xs,f as kt,C as Tr}from"./scroll-area-B8J19zKK.js";import{A as zs,a as $s,b as Os,c as qs,d as Bs,e as Hs,f as Gs,F as ma,g as xa,h as ha,S as Lr,i as Vr,j as Ir,k as Ur,l as zr}from"./alert-dialog-0eDW6vp8.js";import{I as X}from"./input-BmNAiWN8.js";import{T as Ds}from"./textarea-WuwM4jc2.js";import{L as ne,D as ps,a as Fs,b as fs,c as gs,d as js,e as Rs,f as Et}from"./label-7loGhNcu.js";import{S as ns,R as pa,C as Mt,X as Pt,Y as At,T as fa,B as Dt,a as $r,s as Ft,M as Or,b as Ws,P as qr}from"./generateCategoricalChart-DQYcY_4q.js";import{R as Br,g as ga,p as qa,T as Ba,u as Hr,a as Gr,b as Wr,c as Rt,d as Yr,e as Ha}from"./radio-group-CbLuAaSr.js";import{I as wa,U as Sa,f as As,G as Tt,B as Es,S as Zr}from"./formatPrice-m09SfIdc.js";import{L as pe}from"./loader-circle-B8RLev3C.js";import{S as es,e as Ce,T as Lt,a as Vt,b as Ys,c as Ye,d as It,f as Ze,U as Ca,g as Zs,P as ja,h as va,i as ya,D as Kr,M as Ga}from"./popover-CeAStRYn.js";import{f as be,s as Ut}from"./format-DXwivVnG.js";import{C as De}
vendor: 5,172 bytes, line 1
1from"./credit-card-ApVZtXPZ.js";import{C as We}from"./clock-D7lJxluA.js";import{a as Jr}from"./useRestaurantRating-Co7siHmM.js";import{P as Ns}from"./plus-Cty8tRqC.js";import{T as is}from"./trash-2-Blo1j_3u.js";import{E as zt}from"./eye-D-cN7Is8.js";import{E as Wa}from"./eye-off-DHYF3mBs.js";import{M as Xr}from"./map-pin-DPcwEIjU.js";import{B as re}from"./badge-DkelQ_aG.js";import{g as Qr}from"./subscriptionStorage-CfN4IVxt.js";import{C as ba}from"./circle-alert-B1KczL6o.js";import{C as en}from"./circle-check-Bbrn1qdO.js";import{P as Ya,S as Za}from"./star-DrUF8vFf.js";import{C as Na}from"./circle-x-CwqXHye0.js";import{C as Ts}from"./circle-check-big-CnZ1MxA4.js";import{E as Ks}from"./external-link-D2Z97oUx.js";import{R as sn}from"./RoleSelectorModal-CrX2YgIF.js";import{C as oa}from"./chef-hat-DKw1XbnL.js";import{S as Ka}from"./store-D39H8M9D.js";import{B as Ja}from"./shield-CWHdkG50.js";import"./territoryUtils-D6PWvH65.js";import"./chevron-right-ShywFxX4.js";import"./index-qrb7cCW9.js";import"./index-CuRk0cCp.js";import"./index-CP3QsO8B.js";const Xa=qe("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);const Qa=qe("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);const et=qe("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);const st=qe("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);const ka=qe("Infinity",[["path",{d:"M12 12c-2-2.67-4-4-6-4a4 4 0 1 0 0 8c2 0 4-1.33 6-4Zm0 0c2 2.67 4 4 6 4a4 4 0 0 0 0-8c-2 0-4 1.33-6 4Z",key:"1z0uae"}]]);const an=qe("ListOrdered",[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);const tn=qe("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);const rn=qe("MousePointerClick",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]);const nn=qe("MousePointer",[["path",{d:"M12.586 12.586 19 19",key:"ea5xo7"}],["path",{d:"M3.688 3.037a.497.497 0 0 0-.651.651l6.5 15.999a.501.501 0 0 0 .947-.062l1.569-6.083a2 2 0 0 1 1.448-1.479l6.124-1.579a.5.5 0 0 0 .063-.947z",key:"277e5u"}]]);const ln=qe("PartyPopper",[["path",{d:"M5.8 11.3 2 22l10.7-3.79",key:"gwxi1d"}],["path",{d:"M4 3h.01",key:"1vcuye"}],["path",{d:"M22 8h.01",key:"1mrtc2"}],["path",{d:"M15 2h.01",key:"1cjtqr"}],["path",{d:"M22 20h.01",key:"1mrys2"}],["path",{d:"m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10",key:"hbicv8"}],["path",{d:"m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17",key:"1i94pl"}],["path",{d:"m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7",key:"1cofks"}],["path",{d:"M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z",key:"4kbmks"}]]);const at=qe("Stethoscope",[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]]);const Ea=qe("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);const on=qe("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);var Ls=s=>s.type==="checkbox",us=s=>s instanceof Date,Ae=s=>s==null;const $t=s=>typeof s=="object";var Ne=s=>!Ae(s)&&!Array.isArray(s)&&$t(s)&&!us(s),Ot=s=>Ne(s)&&s.target?Ls(s.target)?s.target.checked:s.target.value:s,cn=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,qt=(s,t)=>s.has(cn(t)),dn=s=>{const t=s.constructor&&s.constructor.prototype;return Ne(t)&&t.hasOwnProperty("isPrototypeOf")},Ma=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Se(s){let t;const a=Array.isArray(s),r=typeof FileList<"u"?s instanceof FileList:!1;if(s instanceof Date)t=new Date(s);else if(!(Ma&&(s instanceof Blob||r))&&(a||Ne(s)))if(t=a?[]:{},!a&&!dn(s))t=s;else for(const n in s)s.hasOwnProperty(n)&&(t[n]=Se(s[n]));else return s;return t}var ta=s=>/^\w*$/.test(s),ye=s=>s===void 0,Pa=s=>
1Array.isArray(s)?s.filter(Boolean):[],Aa=s=>Pa(s.replace(/["|']|\]/g,"").split(/\.|\[/)),V=(s,t,a)=>{if(!t||!Ne(s))return a;const r=(ta(t)?[t]:Aa(t)).reduce((n,l)=>Ae(n)?n:n[l],s);return ye(r)||r===s?ye(s[t])?a:s[t]:r},$e=s=>typeof s=="boolean",xe=(s,t,a)=>{let r=-1;const n=ta(t)?[t]:Aa(t),l=n.length,h=l-1;for(;++r<l;){const u=n[r];let C=a;if(r!==h){const N=s[u];C=Ne(N)||Array.isArray(N)?N:isNaN(+n[r+1])?{}:[]}if(u==="__proto__"||u==="constructor"||u==="prototype")return;s[u]=C,s=s[u]}};const Js={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},Ke={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Qe={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},Da=se.createContext(null);Da.displayName="HookFormContext";const ra=()=>se.useContext(Da),un=s=>{const{children:t,...a}=s;return se.createElement(Da.Provider,{value:a},t)};var Bt=(s,t,a,r=!0)=>{const n={defaultValues:t._defaultValues};for(const l in s)Object.defineProperty(n,l,{get:()=>{const h=l;return t._proxyFormState[h]!==Ke.all&&(t._proxyFormState[h]=!r||Ke.all),a&&(a[h]=!0),s[h]}});return n};const Fa=typeof window<"u"?se.useLayoutEffect:se.useEffect;function mn(s){const t=ra(),{control:a=t.control,disabled:r,name:n,exact:l}=s||{},[h,u]=se.useState(a._formState),C=se.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return Fa(()=>a._subscribe({name:n,formState:C.current,exact:l,callback:N=>{!r&&u({...a._formState,...N})}}),[n,r,l]),se.useEffect(()=>{C.current.isValid&&a._setValid(!0)},[a]),se.useMemo(()=>Bt(h,a,C.current,!1),[h,a])}var Xe=s=>typeof s=="string",Ht=(s,t,a,r,n)=>Xe(s)?(r&&t.watch.add(s),V(a,s,n)):Array.isArray(s)?s.map(l=>(r&&t.watch.add(l),V(a,l))):(r&&(t.watchAll=!0),a),_a=s=>Ae(s)||!$t(s);function ss(s,t,a=new WeakSet){if(_a(s)||_a(t))return s===t;if(us(s)&&us(t))return s.getTime()===t.getTime();const r=Object.keys(s),n=Object.keys(t);if(r.length!==n.length)return!1;if(a.has(s)||a.has(t))return!0;a.add(s),a.add(t);for(const l of r){const h=s[l];if(!n.includes(l))return!1;if(l!=="ref"){const u=t[l];if(us(h)&&us(u)||Ne(h)&&Ne(u)||Array.isArray(h)&&Array.isArray(u)?!ss(h,u,a):h!==u)return!1}}return!0}function xn(s){const t=ra(),{control:a=t.control,name:r,defaultValue:n,disabled:l,exact:h,compute:u}=s||{},C=se.useRef(n),N=se.useRef(u),y=se.useRef(void 0);N.current=u;const v=se.useMemo(()=>a._getWatch(r,C.current),[a,r]),[i,S]=se.useState(N.current?N.current(v):v);return Fa(()=>a._subscribe({name:r,formState:{values:!0},exact:h,callback:I=>{if(!l){const d=Ht(r,a._names,I.values||a._formValues,!1,C.current);if(N.current){const w=N.current(d);ss(w,y.current)||(S(w),y.current=w)}else S(d)}}}),[a,l,r,h]),se.useEffect(()=>a._removeUnmounted()),i}function hn(s){const t=ra(),{name:a,disabled:r,control:n=t.control,shouldUnregister:l,defaultValue:h}=s,u=qt(n._names.array,a),C=se.useMemo(()=>V(n._formValues,a,V(n._defaultValues,a,h)),[n,a,h]),N=xn({control:n,name:a,defaultValue:C,exact:!0}),y=mn({control:n,name:a,exact:!0}),v=se.useRef(s),i=se.useRef(n.register(a,{...s.rules,value:N,...$e(s.disabled)?{disabled:s.disabled}:{}}));v.current=s;const S=se.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!V(y.errors,a)},isDirty:{enumerable:!0,get:()=>!!V(y.dirtyFields,a)},isTouched:{enumerable:!0,get:()=>!!V(y.touchedFields,a)},isValidating:{enumerable:!0,get:()=>!!V(y.validatingFields,a)},error:{enumerable:!0,get:()=>V(y.errors,a)}}),[y,a]),I=se.useCallback(c=>i.current.onChange({target:{value:Ot(c),name:a},type:Js.CHANGE}),[a]),d=se.useCallback(()=>i.current.onBlur({target:{value:V(n._formValues,a),name:a},type:Js.BLUR}),[a,n._formValues]),w=se.useCallback(c=>{const g=V(n._fields,a);g&&c&&(g._f.ref={focus:()=>c.focus&&c.focus(),select:()=>c.select&&c.select(),setCustomValidity:j=>c.setCustomValidity(j),reportValidity:()=>c.reportValidity()})},[n._fields,a]),b=se.useMemo(()=>({name:a,value:N,...$e(r)||y.disabled?{disabled:y.disabled||r}:{},onChange:I,onBlur:d,ref:w}),[a,r,y.disabled,I,d,w,N]);return se.useEffect(()=>{const c=n._options.shouldUnregister||l;n.register(a,{...v.current.rules,...$e(v.current.disabled)?{disabled:v.current.disabled}:{}});const g=(j,T)=>{const G=V(n._fields,j);G&&G._f&&(G._f.mount=T)};if(g(a,!0),c){const j=Se(V(n._options.defaultValues,a));xe(n._defaultValues,a,j),ye(V(n._formValues,a))&&xe(n._formValues,a,j)}return!u&&n.register(a),()=>{(u?c&&!n._state.action:c)?n.unregister(a):g(a,!1)}},[a,n,u,l]),se.useEffect(()=>{n._setDisabledField({disabled:r,name:a})},[r,a,n]),se.useMemo(()=>({field:b,formState:y,fieldState:S}),[b,y,S])}const pn=s=>s.render(hn(s));var fn=(s,t,a,r,n)=>t?{...a[s],types:{...a[s]&&a[s].types?a[s].types:{},[r]:n||!0}}:{},Ms=s=>Array.isArray(s)?s:[s],tt=()=>{let s=[];return{get observers(){return s},next:n=>{for(const l of s)l.next&&l.next(n)},subscribe:n=>(s.push(n),{unsubscribe:()=>{s=s.filter(l=>l!==n)}}),unsubscribe:()=>{s=[]}}},Fe=s=>Ne(s)&&!Object.keys(s).length,Ra=s=>s.type==="file",Je=s=>typeof s=="function",Xs=s=>{if(!Ma)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Gt=s=>s.type==="select-multiple",Ta=s=>s.type==="radio",gn=s=>Ta(s)||Ls(s),ca=s=>Xs(s)&&s.isConnected;function jn(s,t){const a=t.slice(0,-1).length;let r=0;for(;r<a;)s=ye(s)?r++:s[t[r++]];return s}function vn(s){for(const t in s)if(s.hasOwnProperty(t)&&!ye(s[t]))return!1;return!0}function we(s,t){const a=Array.isArray(t)?t:ta(t)?[t]:Aa(t),r=a.length===1?s:jn(s,a),n=a.length-1,l=a[n];return r&&delete r[l],n!==0&&(Ne(r)&&Fe(r)||Array.isArray(r)&&vn(r))&&we(s,a.slice(0,-1)),s}var Wt=s=>{for(const t in s)if(Je(s[t]))return!0;return!1};function Qs(s,t={}){const a=Array.isArray(s);if(Ne(s)||a)for(const r in s)Array.isArray(s[r])||Ne(s[r])&&!Wt(s[r])?(t[r]=Array.isArray(s[r])?[]:{},Qs(s[r],t[r])):Ae(s[r])||(t[r]=!0);return t}function Yt(s,t,a){const r=Array.isArray(s);if(Ne(s)||r)for(const n in s)Array.isArray(s[n])||Ne(s[n])&&!Wt(s[n])?ye(t)||_a(a[n])?a[n]=Array.isArray(s[n])?Qs(s[n],[]):{...Qs(s[n])}:Yt(s[n],Ae(t)?{}:t[n],a[n]):a[n]=!ss(s[n],t[n]);return a}var Ss=(s,t)=>Yt(s,t,Qs(t));const rt={value:!1,isValid:!1},nt={value:!0,isValid:!0};var Zt=s=>{if(Array.isArray(s)){if(s.length>1){const t=s.filter(a=>a&&a.checked&&!a.disabled).map(a=>a.value);return{value:t,isValid:!!t.length}}return s[0].checked&&!s[0].disabled?s[0].attributes&&!ye(s[0].attributes.value)?ye(s[0].value)||s[0].value===""?nt:{value:s[0].value,isValid:!0}:nt:rt}return rt},Kt=(s,{valueAsNumber:t,valueAsDate:a,setValueAs:r})=>ye(s)?s:t?s===""?NaN:s&&+s:a&&Xe(s)?new Date(s):r?r(s):s;const it={isValid:!1,value:null};var Jt=s=>Array.isArray(s)?s.reduce((t,a)=>a&&a.checked&&!a.disabled?{isValid:!0,value:a.value}:t,it):it;function lt(s){const t=s.ref;return Ra(t)?t.files:Ta(t)?Jt(s.refs).value:Gt(t)?[...t.selectedOptions].map(({value:a})=>a):Ls(t)?Zt(s.refs).value:Kt(ye(t.value)?s.ref.value:t.value,s)}var yn=(s,t,a,r)=>{const n={};for(const l of s){const h=V(t,l);h&&xe(n,l,h._f)}return{criteriaMode:a,names:[...s],fields:n,shouldUseNativeValidation:r}},ea=s=>s instanceof RegExp,Cs=s=>
vendor: 4,122 bytes, line 1
1ye(s)?s:ea(s)?s.source:Ne(s)?ea(s.value)?s.value.source:s.value:s,ot=s=>({isOnSubmit:!s||s===Ke.onSubmit,isOnBlur:s===Ke.onBlur,isOnChange:s===Ke.onChange,isOnAll:s===Ke.all,isOnTouch:s===Ke.onTouched});const ct="AsyncFunction";var bn=s=>!!s&&!!s.validate&&!!(Je(s.validate)&&s.validate.constructor.name===ct||Ne(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===ct)),Nn=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),dt=(s,t,a)=>!a&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const Ps=(s,t,a,r)=>{for(const n of a||Object.keys(s)){const l=V(s,n);if(l){const{_f:h,...u}=l;if(h){if(h.refs&&h.refs[0]&&t(h.refs[0],n)&&!r)return!0;if(h.ref&&t(h.ref,h.name)&&!r)return!0;if(Ps(u,t))break}else if(Ne(u)&&Ps(u,t))break}}};function ut(s,t,a){const r=V(s,a);if(r||ta(a))return{error:r,name:a};const n=a.split(".");for(;n.length;){const l=n.join("."),h=V(t,l),u=V(s,l);if(h&&!Array.isArray(h)&&a!==l)return{name:a};if(u&&u.type)return{name:l,error:u};if(u&&u.root&&u.root.type)return{name:`${l}.root`,error:u.root};n.pop()}return{name:a}}var _n=(s,t,a,r)=>{a(s);const{name:n,...l}=s;return Fe(l)||Object.keys(l).length>=Object.keys(t).length||Object.keys(l).find(h=>t[h]===(!r||Ke.all))},wn=(s,t,a)=>!s||!t||s===t||Ms(s).some(r=>r&&(a?r===t:r.startsWith(t)||t.startsWith(r))),Sn=(s,t,a,r,n)=>n.isOnAll?!1:!a&&n.isOnTouch?!(t||s):(a?r.isOnBlur:n.isOnBlur)?!s:(a?r.isOnChange:n.isOnChange)?s:!0,Cn=(s,t)=>!Pa(V(s,t)).length&&we(s,t),kn=(s,t,a)=>{const r=Ms(V(s,a));return xe(r,"root",t[a]),xe(s,a,r),s},Is=s=>Xe(s);function mt(s,t,a="validate"){if(Is(s)||Array.isArray(s)&&s.every(Is)||$e(s)&&!s)return{type:a,message:Is(s)?s:"",ref:t}}var vs=s=>Ne(s)&&!ea(s)?s:{value:s,message:""},xt=async(s,t,a,r,n,l)=>{const{ref:h,refs:u,required:C,maxLength:N,minLength:y,min:v,max:i,pattern:S,validate:I,name:d,valueAsNumber:w,mount:b}=s._f,c=V(a,d);if(!b||t.has(d))return{};const g=u?u[0]:h,j=m=>{n&&g.reportValidity&&(g.setCustomValidity($e(m)?"":m||""),g.reportValidity())},T={},G=Ta(h),te=Ls(h),Y=G||te,J=(w||Ra(h))&&ye(h.value)&&ye(c)||Xs(h)&&h.value===""||c===""||Array.isArray(c)&&!c.length,ge=fn.bind(null,d,r,T),oe=(m,k,E,P=Qe.maxLength,O=Qe.minLength)=>{const Z=m?k:E;T[d]={type:m?P:O,message:Z,ref:h,...ge(m?P:O,Z)}};if(l?!Array.isArray(c)||!c.length:C&&(!Y&&(J||Ae(c))||$e(c)&&!c||te&&!Zt(u).isValid||G&&!Jt(u).isValid)){const{value:m,message:k}=Is(C)?{value:!!C,message:C}:vs(C);if(m&&(T[d]={type:Qe.required,message:k,ref:g,...ge(Qe.required,k)},!r))return j(k),T}if(!J&&(!Ae(v)||!Ae(i))){let m,k;const E=vs(i),P=vs(v);if(!Ae(c)&&!isNaN(c)){const O=h.valueAsNumber||c&&+c;Ae(E.value)||(m=O>E.value),Ae(P.value)||(k=O<P.value)}else{const O=h.valueAsDate||new Date(c),Z=U=>new Date(new Date().toDateString()+" "+U),p=h.type=="time",M=h.type=="week";Xe(E.value)&&c&&(m=p?Z(c)>Z(E.value):M?c>E.value:O>new Date(E.value)),Xe(P.value)&&c&&(k=p?Z(c)<Z(P.value):M?c<P.value:O<new Date(P.value))}if((m||k)&&(oe(!!m,E.message,P.message,Qe.max,Qe.min),!r))return j(T[d].message),T}if((N||y)&&!J&&(Xe(c)||l&&Array.isArray(c))){const m=vs(N),k=vs(y),E=!Ae(m.value)&&c.length>+m.value,P=!Ae(k.value)&&c.length<+k.value;if((E||P)&&(oe(E,m.message,k.message),!r))return j(T[d].message),T}if(S&&!J&&Xe(c)){const{value:m,message:k}=vs(S);if(ea(m)&&!c.match(m)&&(T[d]={type:Qe.pattern,message:k,ref:h,...ge(Qe.pattern,k)},!r))return j(k),T}if(I){if(Je(I)){const m=await I(c,a),k=mt(m,g);if(k&&(T[d]={...k,...ge(Qe.validate,k.message)},!r))return j(k.message),T}else if(Ne(I)){let m={};for(const k in I){if(!Fe(m)&&!r)break;const E=mt(await I[k](c,a),g,k);E&&(m={...E,...ge(k,E.message)},j(E.message),r&&(T[d]=m))}if(!Fe(m)&&(T[d]={ref:g,...m},!r))return T}}return j(!0),T};const En={mode:Ke.onSubmit,reValidateMode:Ke.onChange,shouldFocusError:!0};function Mn(s={}){let t={...En,...s},a={submitCount:0,isDirty:!1,isReady:!1,isLoading:Je(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1}
1,r={},n=Ne(t.defaultValues)||Ne(t.values)?Se(t.defaultValues||t.values)||{}:{},l=t.shouldUnregister?{}:Se(n),h={action:!1,mount:!1,watch:!1},u={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},C,N=0;const y={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let v={...y};const i={array:tt(),state:tt()},S=t.criteriaMode===Ke.all,I=o=>x=>{clearTimeout(N),N=setTimeout(o,x)},d=async o=>{if(!t.disabled&&(y.isValid||v.isValid||o)){const x=t.resolver?Fe((await te()).errors):await J(r,!0);x!==a.isValid&&i.state.next({isValid:x})}},w=(o,x)=>{!t.disabled&&(y.isValidating||y.validatingFields||v.isValidating||v.validatingFields)&&((o||Array.from(u.mount)).forEach(_=>{_&&(x?xe(a.validatingFields,_,x):we(a.validatingFields,_))}),i.state.next({validatingFields:a.validatingFields,isValidating:!Fe(a.validatingFields)}))},b=(o,x=[],_,z,R=!0,A=!0)=>{if(z&&_&&!t.disabled){if(h.action=!0,A&&Array.isArray(V(r,o))){const H=_(V(r,o),z.argA,z.argB);R&&xe(r,o,H)}if(A&&Array.isArray(V(a.errors,o))){const H=_(V(a.errors,o),z.argA,z.argB);R&&xe(a.errors,o,H),Cn(a.errors,o)}if((y.touchedFields||v.touchedFields)&&A&&Array.isArray(V(a.touchedFields,o))){const H=_(V(a.touchedFields,o),z.argA,z.argB);R&&xe(a.touchedFields,o,H)}(y.dirtyFields||v.dirtyFields)&&(a.dirtyFields=Ss(n,l)),i.state.next({name:o,isDirty:oe(o,x),dirtyFields:a.dirtyFields,errors:a.errors,isValid:a.isValid})}else xe(l,o,x)},c=(o,x)=>{xe(a.errors,o,x),i.state.next({errors:a.errors})},g=o=>{a.errors=o,i.state.next({errors:a.errors,isValid:!1})},j=(o,x,_,z)=>{const R=V(r,o);if(R){const A=V(l,o,ye(_)?V(n,o):_);ye(A)||z&&z.defaultChecked||x?xe(l,o,x?A:lt(R._f)):E(o,A),h.mount&&d()}},T=(o,x,_,z,R)=>{let A=!1,H=!1;const ie={name:o};if(!t.disabled){if(!_||z){(y.isDirty||v.isDirty)&&(H=a.isDirty,a.isDirty=ie.isDirty=oe(),A=H!==ie.isDirty);const me=ss(V(n,o),x);H=!!V(a.dirtyFields,o),me?we(a.dirtyFields,o):xe(a.dirtyFields,o,!0),ie.dirtyFields=a.dirtyFields,A=A||(y.dirtyFields||v.dirtyFields)&&H!==!me}if(_){const me=V(a.touchedFields,o);me||(xe(a.touchedFields,o,_),ie.touchedFields=a.touchedFields,A=A||(y.touchedFields||v.touchedFields)&&me!==_)}A&&R&&i.state.next(ie)}return A?ie:{}},G=(o,x,_,z)=>{const R=V(a.errors,o),A=(y.isValid||v.isValid)&&$e(x)&&a.isValid!==x;if(t.delayError&&_?(C=I(()=>c(o,_)),C(t.delayError)):(clearTimeout(N),C=null,_?xe(a.errors,o,_):we(a.errors,o)),(_?!ss(R,_):R)||!Fe(z)||A){const H={...z,...A&&$e(x)?{isValid:x}:{},errors:a.errors,name:o};a={...a,...H},i.state.next(H)}},te=async o=>{w(o,!0);const x=await t.resolver(l,t.context,yn(o||u.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return w(o),x},Y=async o=>{const{errors:x}=await te(o);if(o)for(const _ of o){const z=V(x,_);z?xe(a.errors,_,z):we(a.errors,_)}else a.errors=x;return x},J=async(o,x,_={valid:!0})=>{for(const z in o){const R=o[z];if(R){const{_f:A,...H}=R;if(A){const ie=u.array.has(A.name),me=R._f&&bn(R._f);me&&y.validatingFields&&w([z],!0);const Be=await xt(R,u.disabled,l,S,t.shouldUseNativeValidation&&!x,ie);if(me&&y.validatingFields&&w([z]),Be[A.name]&&(_.valid=!1,x))break;!x&&(V(Be,A.name)?ie?kn(a.errors,Be,A.name):xe(a.errors,A.name,Be[A.name]):we(a.errors,A.name))}!Fe(H)&&await J(H,x,_)}}return _.valid},ge=()=>{for(const o of u.unMount){const x=V(r,o);x&&(x._f.refs?x._f.refs.every(_=>!ca(_)):!ca(x._f.ref))&&ze(o)}u.unMount=new Set},oe=(o,x)=>!t.disabled&&(o&&x&&xe(l,o,x),!ss(U(),n)),m=(o,x,_)=>Ht(o,u,{...h.mount?l:ye(x)?n:Xe(o)?{[o]:x}:x},_,x),k=o=>Pa(V(h.mount?l:n,o,t.shouldUnregister?V(n,o,[]):[])),E=(o,x,_={})=>{const z=V(r,o);let R=x;if(z){const A=z._f;A&&(!A.disabled&&xe(l,o,Kt(x,A)),R=Xs(A.ref)&&Ae(x)?"":x,Gt(A.ref)?[...A.ref.options].forEach(H=>H.selected=R.includes(H.value)):A.refs?Ls(A.ref)?A.refs.forEach(H=>{(!H.defaultChecked||!H.disabled)&&(Array.isArray(R)?H.checked=!!R.find(ie=>ie===H.value):H.checked=R===H.value||!!R)}):A.refs.forEach(H=>H.checked=H.value===R):Ra(A.ref)?A.ref.value="":(A.ref.value=R,A.ref.type||i.state.next({name:o,values:Se(l)})))}(_.shouldDirty||_.shouldTouch)&&T(o,R,_.shouldTouch,_.shouldDirty,!0),_.shouldValidate&&M(o)},P=(o,x,_)=>{for(const z in x){if(!x.hasOwnProperty(z))return;const R=x[z],A=o+"."+z,H=V(r,A);(u.array.has(o)||Ne(R)||H&&!H._f)&&!us(R)?P(A,R,_):E(A,R,_)}},O=(o,x,_={})=>{const z=V(r,o),R=u.array.has(o),A=Se(x);xe(l,o,A),R?(i.array.next({name:o,values:Se(l)}),(y.isDirty||y.dirtyFields||v.isDirty||v.dirtyFields)&&_.shouldDirty&&i.state.next({name:o,dirtyFields:Ss(n,l),isDirty:oe(o,A)})):z&&!z._f&&!Ae(A)?P(o,A,_):E(o,A,_),dt(o,u)&&i.state.next({...a,name:o}),i.state.next({name:h.mount?o:void 0,values:Se(l)})},Z=async o=>{h.mount=!0;const x=o.target;let _=x.name,z=!0;const R=V(r,_),A=me=>{z=Number.isNaN(me)||us(me)&&isNaN(me.getTime())||ss(me,V(l,_,me))},H=ot(t.mode),ie=ot(t.reValidateMode);if(R){let me,Be;const Vs=x.type?lt(R._f):Ot(o),ts=o.type===Js.BLUR||o.type===Js.FOCUS_OUT,or=!Nn(R._f)&&!t.resolver&&!V(a.errors,_)&&!R._f.deps||Sn(ts,V(a.touchedFields,_),a.isSubmitted,ie,H),ia=dt(_,u,ts);xe(l,_,Vs),ts?(R._f.onBlur&&R._f.onBlur(o),C&&C(0)):R._f.onChange&&R._f.onChange(o);const la=T(_,Vs,ts),cr=!Fe(la)||ia;if(!ts&&i.state.next({name:_,type:o.type,values:Se(l)}),or)return(y.isValid||v.isValid)&&(t.mode==="onBlur"?ts&&d():ts||d()),cr&&i.state.next({name:_,...ia?{}:la});if(!ts&&ia&&i.state.next({...a}),t.resolver){const{errors:za}=await te([_]);if(A(Vs),z){const dr=ut(a.errors,r,_),$a=ut(za,r,dr.name||_);me=$a.error,_=$a.name,Be=Fe(za)}}else w([_],!0),me=(await xt(R,u.disabled,l,S,t.shouldUseNativeValidation))[_],w([_]),A(Vs),z&&(me?Be=!1:(y.isValid||v.isValid)&&(Be=await J(r,!0)));z&&(R._f.deps&&M(R._f.deps),G(_,Be,me,la))}},p=(o,x)=>
vendor: 4,421 bytes, line 1
1{if(V(a.errors,x)&&o.focus)return o.focus(),1},M=async(o,x={})=>{let _,z;const R=Ms(o);if(t.resolver){const A=await Y(ye(o)?o:R);_=Fe(A),z=o?!R.some(H=>V(A,H)):_}else o?(z=(await Promise.all(R.map(async A=>{const H=V(r,A);return await J(H&&H._f?{[A]:H}:H)}))).every(Boolean),!(!z&&!a.isValid)&&d()):z=_=await J(r);return i.state.next({...!Xe(o)||(y.isValid||v.isValid)&&_!==a.isValid?{}:{name:o},...t.resolver||!o?{isValid:_}:{},errors:a.errors}),x.shouldFocus&&!z&&Ps(r,p,o?R:u.mount),z},U=o=>{const x={...h.mount?l:n};return ye(o)?x:Xe(o)?V(x,o):o.map(_=>V(x,_))},F=(o,x)=>({invalid:!!V((x||a).errors,o),isDirty:!!V((x||a).dirtyFields,o),error:V((x||a).errors,o),isValidating:!!V(a.validatingFields,o),isTouched:!!V((x||a).touchedFields,o)}),W=o=>{o&&Ms(o).forEach(x=>we(a.errors,x)),i.state.next({errors:o?a.errors:{}})},ee=(o,x,_)=>{const z=(V(r,o,{_f:{}})._f||{}).ref,R=V(a.errors,o)||{},{ref:A,message:H,type:ie,...me}=R;xe(a.errors,o,{...me,...x,ref:z}),i.state.next({name:o,errors:a.errors,isValid:!1}),_&&_.shouldFocus&&z&&z.focus&&z.focus()},ke=(o,x)=>Je(o)?i.state.subscribe({next:_=>"values"in _&&o(m(void 0,x),_)}):m(o,x,!0),Ue=o=>i.state.subscribe({next:x=>{wn(o.name,x.name,o.exact)&&_n(x,o.formState||y,lr,o.reRenderRoot)&&o.callback({values:{...l},...a,...x,defaultValues:n})}}).unsubscribe,Pe=o=>(h.mount=!0,v={...v,...o.formState},Ue({...o,formState:v})),ze=(o,x={})=>{for(const _ of o?Ms(o):u.mount)u.mount.delete(_),u.array.delete(_),x.keepValue||(we(r,_),we(l,_)),!x.keepError&&we(a.errors,_),!x.keepDirty&&we(a.dirtyFields,_),!x.keepTouched&&we(a.touchedFields,_),!x.keepIsValidating&&we(a.validatingFields,_),!t.shouldUnregister&&!x.keepDefaultValue&&we(n,_);i.state.next({values:Se(l)}),i.state.next({...a,...x.keepDirty?{isDirty:oe()}:{}}),!x.keepIsValid&&d()},B=({disabled:o,name:x})=>{($e(o)&&h.mount||o||u.disabled.has(x))&&(o?u.disabled.add(x):u.disabled.delete(x))},ae=(o,x={})=>{let _=V(r,o);const z=$e(x.disabled)||$e(t.disabled);return xe(r,o,{..._||{},_f:{..._&&_._f?_._f:{ref:{name:o}},name:o,mount:!0,...x}}),u.mount.add(o),_?B({disabled:$e(x.disabled)?x.disabled:t.disabled,name:o}):j(o,!0,x.value),{...z?{disabled:x.disabled||t.disabled}:{},...t.progressive?{required:!!x.required,min:Cs(x.min),max:Cs(x.max),minLength:Cs(x.minLength),maxLength:Cs(x.maxLength),pattern:Cs(x.pattern)}:{},name:o,onChange:Z,onBlur:Z,ref:R=>{if(R){ae(o,x),_=V(r,o);const A=ye(R.value)&&R.querySelectorAll&&R.querySelectorAll("input,select,textarea")[0]||R,H=gn(A),ie=_._f.refs||[];if(H?ie.find(me=>me===A):A===_._f.ref)return;xe(r,o,{_f:{..._._f,...H?{refs:[...ie.filter(ca),A,...Array.isArray(V(n,o))?[{}]:[]],ref:{type:A.type,name:o}}:{ref:A}}}),j(o,!1,void 0,A)}else _=V(r,o,{}),_._f&&(_._f.mount=!1),(t.shouldUnregister||x.shouldUnregister)&&!(qt(u.array,o)&&h.action)&&u.unMount.add(o)}}},_e=()=>t.shouldFocusError&&Ps(r,p,u.mount),rr=o=>{$e(o)&&(i.state.next({disabled:o}),Ps(r,(x,_)=>{const z=V(r,_);z&&(x.disabled=z._f.disabled||o,Array.isArray(z._f.refs)&&z._f.refs.forEach(R=>{R.disabled=z._f.disabled||o}))},0,!1))},La=(o,x)=>async _=>{let z;_&&(_.preventDefault&&_.preventDefault(),_.persist&&_.persist());let R=Se(l);if(i.state.next({isSubmitting:!0}),t.resolver){const{errors:A,values:H}=await te();a.errors=A,R=Se(H)}else await J(r);if(u.disabled.size)for(const A of u.disabled)we(R,A);if(we(a.errors,"root"),Fe(a.errors)){i.state.next({errors:{}});try{await o(R,_)}catch(A){z=A}}else x&&await x({...a.errors},_),_e(),setTimeout(_e);if(i.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fe(a.errors)&&!z,submitCount:a.submitCount+1,errors:a.errors}),z)throw z},nr=(o,x={})=>{V(r,o)&&(ye(x.defaultValue)?O(o,Se(V(n,o))):(O(o,x.defaultValue),xe(n,o,Se(x.defaultValue))),x.keepTouched||we(a.touchedFields,o),x.keepDirty||(we(a.dirtyFields,o),a.isDirty=x.defaultValue?oe(o,Se(V(n,o))):oe()),x.keepError||(we(a.errors,o),y.isValid&&d()),i.state.next({...a}))},Va=(o,x={})=>{const _=o?Se(o):n,z=Se(_),R=Fe(o),A=R?n:z;if(x.keepDefaultValues||(n=_),!x.keepValues){if(x.keepDirtyValues){const H=new Set([...u.mount,...Object.keys(Ss(n,l))]);for(const ie of Array.from(H))V(a.dirtyFields,ie)?xe(A,ie,V(l,ie)):O(ie,V(A,ie))}else{if(Ma&&ye(o))for(const H of u.mount){const ie=V(r,H);if(ie&&ie._f){const me=Array.isArray(ie._f.refs)?ie._f.refs[0]:ie._f.ref;if(Xs(me)){const Be=me.closest("form");if(Be){Be.reset();break}}}}if(x.keepFieldsRef)for(const H of u.mount)O(H,V(A,H));else r={}}
1l=t.shouldUnregister?x.keepDefaultValues?Se(n):{}:Se(A),i.array.next({values:{...A}}),i.state.next({values:{...A}})}u={mount:x.keepDirtyValues?u.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},h.mount=!y.isValid||!!x.keepIsValid||!!x.keepDirtyValues,h.watch=!!t.shouldUnregister,i.state.next({submitCount:x.keepSubmitCount?a.submitCount:0,isDirty:R?!1:x.keepDirty?a.isDirty:!!(x.keepDefaultValues&&!ss(o,n)),isSubmitted:x.keepIsSubmitted?a.isSubmitted:!1,dirtyFields:R?{}:x.keepDirtyValues?x.keepDefaultValues&&l?Ss(n,l):a.dirtyFields:x.keepDefaultValues&&o?Ss(n,o):x.keepDirty?a.dirtyFields:{},touchedFields:x.keepTouched?a.touchedFields:{},errors:x.keepErrors?a.errors:{},isSubmitSuccessful:x.keepIsSubmitSuccessful?a.isSubmitSuccessful:!1,isSubmitting:!1})},Ia=(o,x)=>Va(Je(o)?o(l):o,x),ir=(o,x={})=>{const _=V(r,o),z=_&&_._f;if(z){const R=z.refs?z.refs[0]:z.ref;R.focus&&(R.focus(),x.shouldSelect&&Je(R.select)&&R.select())}},lr=o=>{a={...a,...o}},Ua={control:{register:ae,unregister:ze,getFieldState:F,handleSubmit:La,setError:ee,_subscribe:Ue,_runSchema:te,_focusError:_e,_getWatch:m,_getDirty:oe,_setValid:d,_setFieldArray:b,_setDisabledField:B,_setErrors:g,_getFieldArray:k,_reset:Va,_resetDefaultValues:()=>Je(t.defaultValues)&&t.defaultValues().then(o=>{Ia(o,t.resetOptions),i.state.next({isLoading:!1})}),_removeUnmounted:ge,_disableForm:rr,_subjects:i,_proxyFormState:y,get _fields(){return r},get _formValues(){return l},get _state(){return h},set _state(o){h=o},get _defaultValues(){return n},get _names(){return u},set _names(o){u=o},get _formState(){return a},get _options(){return t},set _options(o){t={...t,...o}}},subscribe:Pe,trigger:M,register:ae,handleSubmit:La,watch:ke,setValue:O,getValues:U,reset:Ia,resetField:nr,clearErrors:W,unregister:ze,setError:ee,setFocus:ir,getFieldState:F};return{...Ua,formControl:Ua}}function Xt(s={}){const t=se.useRef(void 0),a=se.useRef(void 0),[r,n]=se.useState({isDirty:!1,isValidating:!1,isLoading:Je(s.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:s.errors||{},disabled:s.disabled||!1,isReady:!1,defaultValues:Je(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!Je(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:h,...u}=Mn(s);t.current={...u,formState:r}}const l=t.current.control;return l._options=s,Fa(()=>{const h=l._subscribe({formState:l._proxyFormState,callback:()=>n({...l._formState}),reRenderRoot:!0});return n(u=>({...u,isReady:!0})),l._formState.isReady=!0,h},[l]),se.useEffect(()=>l._disableForm(s.disabled),[l,s.disabled]),se.useEffect(()=>{s.mode&&(l._options.mode=s.mode),s.reValidateMode&&(l._options.reValidateMode=s.reValidateMode)},[l,s.mode,s.reValidateMode]),se.useEffect(()=>{s.errors&&(l._setErrors(s.errors),l._focusError())},[l,s.errors]),se.useEffect(()=>{s.shouldUnregister&&l._subjects.state.next({values:l._getWatch()})},[l,s.shouldUnregister]),se.useEffect(()=>{if(l._proxyFormState.isDirty){const h=l._getDirty();h!==r.isDirty&&l._subjects.state.next({isDirty:h})}},[l,r.isDirty]),se.useEffect(()=>{s.values&&!ss(s.values,a.current)?(l._reset(s.values,{keepFieldsRef:!0,...l._options.resetOptions}),a.current=s.values,n(h=>({...h}))):l._resetDefaultValues()},[l,s.values]),se.useEffect(()=>{l._state.mount||(l._setValid(),l._state.mount=!0),l._state.watch&&(l._state.watch=!1,l._subjects.state.next({...l._formState})),l._removeUnmounted()}),t.current.formState=Bt(r,l),t.current}const Qt=un,er=f.createContext({}),he=({...s})=>e.jsx(er.Provider,{value:{name:s.name},children:e.jsx(pn,{...s})}),na=()=>{const s=f.useContext(er),t=f.useContext(sr),{getFieldState:a,formState:r}=ra(),n=a(s.name,r);if(!s)throw new Error("useFormField should be used within <FormField>");const{id:l}=t;return{id:l,name:s.name,formItemId:`${l}-form-item`,formDescriptionId:`${l}-form-item-description`,formMessageId:`${l}-form-item-message`,...n}},sr=f.createContext({}),de=f.forwardRef(({className:s,...t},a)=>{const r=f.useId();return e.jsx(sr.Provider,{value:{id:r},children:e.jsx("div",{ref:a,className:Oe("space-y-2",s),...t})})});de.displayName="FormItem";const fe=f.forwardRef(({className:s,...t},a)=>{const{error:r,formItemId:n}=na();return e.jsx(ne,{ref:a,className:Oe(r&&"text-destructive",s),htmlFor:n,...t})});fe.displayName="FormLabel";const ue=f.forwardRef(({...s},t)=>{const{error:a,formItemId:r,formDescriptionId:n,formMessageId:l}=na();return e.jsx(ur,{ref:t,id:r,"aria-describedby":a?`${n} ${l}`:`${n}`,"aria-invalid":!!a,...s})});ue.displayName="FormControl";const Pn=f.forwardRef(({className:s,...t},a)=>{const{formDescriptionId:r}=na();return e.jsx("p",{ref:a,id:r,className:Oe("text-sm text-muted-foreground",s),...t})});Pn.displayName="FormDescription";const je=f.forwardRef(({className:s,children:t,...a},r)=>{const{error:n,formMessageId:l}=na(),h=n?String(n?.message):t;return h?e.jsx("p",{ref:r,id:l,className:Oe("text-sm font-medium text-destructive",s),...a,children:h}):null});
1je.displayName="FormMessage";const ar=({subscriptionStatus:s="unknown",nextPaymentDue:t=null,children:a})=>{const{currentRestaurant:r,userRestaurants:n}=ls(),{toast:l}=Ie(),[h,u]=f.useState(!1),[C,N]=f.useState(!1),y=r||n?.[0],[v,i]=f.useState({restaurantName:y?.name||"",restaurantId:y?.id||"",email:y?.email||"",phone:y?.phone||"",subject:"Consulta sobre Suscripción",message:"",subscriptionStatus:s,nextPaymentDue:t||"No disponible"}),S=(w,b)=>{i(c=>({...c,[w]:b}))},I=async w=>{w.preventDefault(),N(!0);try{try{fr.parse(v.email),gr.parse(v.subject),jr.parse(v.message)}catch(j){if(j instanceof vr){l({variant:"destructive",title:"Datos inválidos",description:j.errors[0].message}),N(!1);return}throw j}let b=null;if(t&&t!=="No disponible")try{b=new Date(t).toISOString()}catch{b=null}const{data:c,error:g}=await L.from("support_messages").insert([{restaurant_id:v.restaurantId,restaurant_name:v.restaurantName,contact_email:v.email,contact_phone:v.phone,subject:v.subject,message:v.message,subscription_status:v.subscriptionStatus,next_payment_due:b,status:"pending"}]).select().single();if(g)throw g;l({title:"✅ Mensaje enviado exitosamente",description:"Tu mensaje ha sido enviado al equipo de soporte. Te responderemos pronto.",duration:5e3}),i(j=>({...j,message:"",subject:"Consulta sobre Suscripción"})),setTimeout(()=>{u(!1)},1500)}catch(b){console.error("Error al enviar mensaje:",b),l({variant:"destructive",title:"Error al enviar mensaje",description:b.message||"No se pudo enviar el mensaje. Por favor, intenta de nuevo o contacta por WhatsApp."})}finally{N(!1)}},d=w=>{switch(w){case"active":return"Activa ✓";case"pending":return"Pendiente ⏳";case"suspended":return"Suspendida ⚠️";default:return w}};return e.jsxs(ps,{open:h,onOpenChange:u,children:[e.jsx(Fs,{asChild:!0,children:a||e.jsxs(D,{variant:"default",className:"flex items-center gap-2",children:[e.jsx(ms,{className:"h-4 w-4"}),"Enviar Email"]})}),e.jsxs(fs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(gs,{children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(ms,{className:"h-5 w-5 text-primary"}),"Contactar Soporte"]}),e.jsx(Rs,{children:"Completa el formulario para contactar con nuestro equipo de soporte. Los datos de tu restaurante ya están precargados."})]}),e.jsxs("form",{onSubmit:I,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-4 p-4 bg-muted/50 rounded-lg",children:[e.jsx("h4",{className:"font-medium text-sm text-muted-foreground",children:"Información del Restaurante"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"restaurantName",children:"Nombre del Restaurante"}),e.jsx(X,{id:"restaurantName",value:v.restaurantName,readOnly:!0,className:"bg-background"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"restaurantId",children:"ID del Restaurante"}),e.jsx(X,{id:"restaurantId",value:v.restaurantId,readOnly:!0,className:"bg-background text-xs"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"subscriptionStatus",children:"Estado de Suscripción"}),e.jsx(X,{id:"subscriptionStatus",value:d(v.subscriptionStatus),readOnly:!0,className:"bg-background"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"nextPaymentDue",children:"Próximo Vencimiento"}),e.jsx(X,{id:"nextPaymentDue",value:v.nextPaymentDue,readOnly:!0,className:"bg-background"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm text-muted-foreground",children:"Datos de Contacto"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email",children:"Email de Contacto *"}),e.jsx(X,{id:"email",type:"email",value:v.email,onChange:w=>S("email",w.target.value),placeholder:"[email protected]",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"phone",children:"Teléfono"}),e.jsx(X,{id:"phone",type:"tel",value:v.phone,onChange:w=>S("phone",w.target.value),placeholder:"+1234567890"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"subject",children:"Asunto *"}),e.jsxs(Re,{value:v.subject,onValueChange:w=>S("subject",w),children:[e.jsx(Te,{id:"subject",children:e.jsx(Le,{placeholder:"Selecciona un asunto"})}),e.jsxs(Ve,{children:[e.jsx(le,{value:"Consulta sobre Suscripción",children:"Consulta sobre Suscripción"}),e.jsx(le,{value:"Renovación de Suscripción",children:"Renovación de Suscripción"}),e.jsx(le,{value:"Problema Técnico",children:"Problema Técnico"}),e.jsx(le,{value:"Actualización de Datos",children:"Actualización de Datos"}),e.jsx(le,{value:"Cambio de Plan",children:"Cambio de Plan"}),e.jsx(le,{value:"Facturación",children:"Facturación"}),e.jsx(le,{value:"Cancelación de Servicio",children:"Cancelación de Servicio"}),e.jsx(le,{value:"Otro",children:"Otro"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"message",children:"Mensaje *"}),e.jsx(Ds,{id:"message",value:v.message,onChange:w=>S("message",w.target.value),placeholder:"Describe tu consulta o problema...",rows:6,required:!0,className:"resize-none"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Mínimo 10 caracteres. Sé lo más específico posible."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 pt-4",children:[e.jsx(D,{type:"submit",disabled:C||!v.message||v.message.length<10,className:"flex-1",children:C?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 mr-2 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2"}),"Enviar Mensaje"]})}),e.jsx(D,{type:"button",variant:"outline",onClick:()=>u(!1),disabled:C,children:"Cancelar"})]}),e.jsx("div",{className:"text-xs text-muted-foreground text-center pt-2",children:'Al hacer clic en "Enviar Mensaje", tu consulta será enviada directamente al equipo de soporte. Recibirás una respuesta por email en las próximas 24-48 horas.'})]})]})]})},An=()=>{const{currentRestaurant:s,userRestaurants:t}=ls(),[a,r]=f.useState(null),[n,l]=f.useState(!0);f.useEffect(()=>{const v=s?.id||t?.[0]?.id;v?h(v):l(!1)},[s,t]);const h=async v=>{if(v)try{He.log("Fetching subscription status for restaurant:",v);const{data:i,error:S}=await L.rpc("get_restaurant_subscription_status",{p_restaurant_id:v});if(He.log("Subscription status response:",{data:i,error:S}),S)throw S;i&&i.length>0?(r(i[0]),He.log("Setting subscription status:",i[0])):(He.log("No subscription status found, creating default"),r({status:"pending",next_payment_due:null,days_until_due:null,suspension_message:"Servicio temporalmente no disponible debido a suscripción pendiente."}))}catch(i){He.error("Error fetching subscription status:",i),r({status:"pending",next_payment_due:null,days_until_due:null,suspension_message:"Error al verificar el estado de suscripción. Contacte al administrador."})}finally{l(!1)}};if(n)return e.jsx("div",{className:"mb-6",children:e.jsx("div",{className:"animate-pulse bg-muted h-16 rounded-lg"})});if(!a||(He.log("Banner condition check:",{status:a.status,days_until_due:a.days_until_due,shouldShow:a.status!=="active"||a.days_until_due&&a.days_until_due<=7}),a.status==="active"&&(!a.days_until_due||a.days_until_due>15)))return null;const u=()=>{const{status:v,days_until_due:i}=a;return v==="suspended"?"destructive":v==="pending"?i!==null&&i<0?"destructive":"default":i!==null&&i<=2?"destructive":"default"},C=()=>{switch(a.status){case"suspended":return e.jsx(as,{className:"h-4 w-4"});
1case"pending":return e.jsx(We,{className:"h-4 w-4"});default:return e.jsx(De,{className:"h-4 w-4"})}},N=()=>{switch(a.status){case"suspended":return"🚫 Servicio Suspendido";case"pending":return"⚠️ Pago Pendiente";default:return"📅 Próximo Vencimiento"}},y=()=>a.status==="suspended"?a.suspension_message:a.status==="pending"?a.days_until_due&&a.days_until_due<0?`Su suscripción venció hace ${Math.abs(a.days_until_due)} días. Su menú digital está deshabilitado hasta que se procese el pago.`:"Su suscripción está pendiente de pago. Contacte al administrador para renovar su suscripción.":a.days_until_due&&a.days_until_due<=15?a.days_until_due<=2?`⚠️ ¡Urgente! Su suscripción vence en ${a.days_until_due} ${a.days_until_due===1?"día":"días"}. Renueve ahora para evitar interrupciones.`:a.days_until_due<=7?`Su suscripción vence en ${a.days_until_due} días. Le recomendamos renovar pronto.`:`Su suscripción vence en ${a.days_until_due} días. Contacte al administrador para renovar.`:"";return e.jsx("div",{className:"mb-6",children:e.jsxs(cs,{variant:u(),children:[C(),e.jsx(ys,{children:N()}),e.jsx(ds,{className:"mt-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:y()}),a.next_payment_due&&e.jsxs("p",{className:"text-sm",children:[e.jsx("strong",{children:"Fecha de vencimiento:"})," ",be(new Date(a.next_payment_due),"dd 'de' MMMM 'de' yyyy",{locale:Ce})]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(ar,{subscriptionStatus:a.status,nextPaymentDue:a.next_payment_due?be(new Date(a.next_payment_due),"dd 'de' MMMM 'de' yyyy",{locale:Ce}):"No disponible",children:e.jsxs(D,{size:"sm",variant:a.status==="suspended"?"default":"outline",children:[e.jsx(De,{className:"h-3 w-3 mr-2"}),"Contactar Administrador"]})}),a.status!=="suspended"&&e.jsx(D,{size:"sm",variant:"ghost",onClick:()=>window.open("https://wa.me/584121353788","_blank"),children:"📞 WhatsApp"}),e.jsxs(ps,{children:[e.jsx(Fs,{asChild:!0,children:e.jsxs(D,{size:"sm",variant:"outline",children:[e.jsx(wa,{className:"h-3 w-3 mr-2"}),"Prueba Gratis"]})}),e.jsx(fs,{children:e.jsxs(gs,{children:[e.jsx(js,{children:"🎉 Servicio de Prueba Gratuito"}),e.jsxs(Rs,{className:"pt-4 text-base",children:["Para activar tu servicio de prueba sin costo, ve a la pestaña 'Suscripción' y usa el código ",e.jsx("strong",{className:"text-primary",children:"'Gratis 2025'"})," al notificar el pago."]})]})})]})]})]})})]})})};function Dn(){const s=document.createElement("canvas");return s.width=1,s.height=1,s.toDataURL("image/webp").indexOf("data:image/webp")===0}async function Fn(s,t={}){const{targetRatio:a=1.6,maxWidth:r=800,quality:n=.82}=t;return new Promise((l,h)=>{const u=new FileReader;u.onload=C=>{const N=new Image;N.onload=()=>{const y=N.width/N.height;let v=0,i=0,S=N.width,I=N.height;y<a?(I=N.width/a,i=(N.height-I)/2):y>a&&(S=N.height*a,v=(N.width-S)/2);let d=S,w=I;d>r&&(d=r,w=r/a);const b=document.createElement("canvas");b.width=Math.round(d),b.height=Math.round(w);const c=b.getContext("2d");if(!c){h(new Error("No se pudo obtener el contexto del canvas"));return}c.drawImage(N,v,i,S,I,0,0,b.width,b.height),b.toBlob(g=>{if(!g){h(new Error("No se pudo procesar la imagen"));return}const j=s.name.replace(/\.(jpg|jpeg|png|gif|webp)$/i,".webp"),T=new File([g],j,{type:"image/webp",lastModified:Date.now()});l(T)},"image/webp",n)},N.onerror=()=>h(new Error("No se pudo cargar la imagen")),C.target?.result&&(N.src=C.target.result)},u.onerror=()=>h(new Error("No se pudo leer el archivo")),u.readAsDataURL(s)})}async function ht(s){return new Promise((t,a)=>{const r=new FileReader;r.onload=n=>{const l=new Image;l.onload=()=>{t({width:l.width,height:l.height,mimeType:s.type,size:s.size})},l.onerror=()=>{a(new Error("No se pudo cargar la imagen"))},n.target?.result&&(l.src=n.target.result)},r.onerror=()=>{a(new Error("No se pudo leer el archivo"))},r.readAsDataURL(s)})}const da=["Entradas","Sopas y Cremas","Platos Principales","Acompañantes","Postres","Bebidas"],os="menu_item_draft",Rn=()=>{const[s,t]=f.useState([]),[a,r]=f.useState(!0),[n,l]=f.useState(null),[h,u]=f.useState(!1),[C,N]=f.useState(!1),[y,v]=f.useState(!1),[i,S]=f.useState(null),[I,d]=f.useState([]),{currentRestaurant:w}=ls(),{toast:b}=Ie(),{summary:c}=Jr(w?.id),g=Xt({defaultValues:{name:"",description:"",detailed_description:"",price:"",category:"",is_visible:!0,is_promotion:!1,is_featured:!1},mode:"onChange"});f.useEffect(()=>{const p=localStorage.getItem(os);if(p)try{const M=JSON.parse(p);M.restaurantId===w?.id&&M.data&&v(!0)}catch{localStorage.removeItem(os)}},[w]),f.useEffect(()=>{const p=g.watch(M=>
1{if(!n&&w&&(M.name||M.description||M.price||M.category)){const F={restaurantId:w.id,data:M,savedAt:new Date().toISOString()};localStorage.setItem(os,JSON.stringify(F)),v(!0)}});return()=>p.unsubscribe()},[g,n,w]),f.useEffect(()=>{w&&j()},[w]);const j=async()=>{if(w)try{const[p,M]=await Promise.all([L.from("menu_items").select("*").eq("restaurant_id",w.id).order("created_at",{ascending:!1}),L.rpc("get_menu_items_usage",{p_restaurant_id:w.id})]);if(p.error)throw p.error;t(p.data||[]),!M.error&&M.data&&S(M.data)}catch(p){console.error("Error fetching menu items:",p),b({variant:"destructive",title:"Error",description:"No se pudieron cargar los elementos del menú."})}finally{r(!1)}},T=async p=>{try{const M=await ht(p);He.info("Imagen original:",{name:p.name,type:M.mimeType,size:`${(M.size/1024).toFixed(2)} KB`,dimensions:`${M.width}x${M.height}`});let U=p,F=p.name.split(".").pop()?.toLowerCase()||"";if(Dn())try{He.info("Procesando imagen para menú (recorte 16:10 + WebP)..."),U=await Fn(p),F="webp";const Pe=await ht(U);He.info("Imagen procesada para menú:",{name:U.name,size:`${(U.size/1024).toFixed(2)} KB`,dimensions:`${Pe.width}x${Pe.height}`,reduction:`${((p.size-U.size)/p.size*100).toFixed(1)}%`}),b({title:"Imagen optimizada",description:`${Pe.width}x${Pe.height}px WebP · Reducción: ${((p.size-U.size)/p.size*100).toFixed(0)}%`})}catch(Pe){He.error("Error al procesar imagen, usando original:",Pe)}const W=`${Math.random()}.${F}`,ee=`${w?.id}/${W}`,{error:ke}=await L.storage.from("menu-images").upload(ee,U);if(ke)throw ke;const{data:Ue}=L.storage.from("menu-images").getPublicUrl(ee);return He.info("Imagen subida exitosamente:",Ue.publicUrl),Ue.publicUrl}catch(M){return He.error("Error uploading image:",M),b({variant:"destructive",title:"Error",description:"No se pudo subir la imagen."}),null}},G=p=>{const M=p.map(U=>({id:U.id,label:U.label.trim(),price:U.price.trim(),is_default:!!U.is_default})).filter(U=>U.label&&U.price);if(M.length===0)return[];if(!M.some(U=>U.is_default))M[0].is_default=!0;else{let U=!1;for(const F of M)F.is_default&&(U?F.is_default=!1:U=!0)}return M},te=async p=>{if(!w){b({variant:"destructive",title:"Error",description:"No hay restaurante seleccionado."});return}N(!0);try{let M=n?.image_url||null;if(p.image&&p.image.length>0){const F=await T(p.image[0]);F&&(M=F)}const U=G(I);if(n){const{error:F}=await L.from("menu_items").update({name:p.name,description:p.description,detailed_description:p.detailed_description,price:p.price,category:p.category,image_url:M,is_visible:p.is_visible,is_promotion:p.is_promotion,is_featured:p.is_featured,variants:U}).eq("id",n.id);if(F)throw F;b({title:"¡Elemento actualizado!",description:"El elemento del menú se ha actualizado correctamente."})}else{const{error:F}=await L.from("menu_items").insert([{name:p.name,description:p.description,detailed_description:p.detailed_description,price:p.price,category:p.category,image_url:M,restaurant_id:w.id,is_visible:p.is_visible,is_promotion:p.is_promotion,is_featured:p.is_featured,variants:U}]);if(F)throw F;b({title:"¡Elemento agregado!",description:"El nuevo elemento se ha agregado al menú."})}g.reset(),d([]),l(null),u(!1),localStorage.removeItem(os),v(!1),j()}catch(M){console.error("Error saving menu item:",M),b({variant:"destructive",title:"Error",description:"No se pudo guardar el elemento del menú."})}finally{N(!1)}},Y=async p=>{try{const{error:M}=await L.from("menu_items").delete().eq("id",p);if(M)throw M;b({title:"Elemento eliminado",description:"El elemento ha sido eliminado del menú."}),j()}catch(M){console.error("Error deleting menu item:",M),b({variant:"destructive",title:"Error",description:"No se pudo eliminar el elemento."})}},J=async p=>{if(w){if(O){b({variant:"destructive",title:"Límite alcanzado",description:"No puedes duplicar el plato porque has alcanzado el límite de ítems de tu plan."});return}try{const{error:M}=await L.from("menu_items").insert([{name:`${p.name} (copia)`,description:p.description,detailed_description:p.detailed_description||null,price:p.price,category:p.category,image_url:p.image_url||null,restaurant_id:w.id,is_visible:!1,is_featured:!1,variants:qa(p.variants)}]);if(M)throw M;b({title:"¡Plato duplicado!",description:`Se ha creado una copia de "${p.name}" como oculto.`}),j()}catch(M){console.error("Error duplicating menu item:",M),b({variant:"destructive",title:"Error",description:"No se pudo duplicar el elemento."})}}},ge=p=>
1{l(p),d(qa(p.variants)),g.reset({name:p.name,description:p.description,detailed_description:p.detailed_description||"",price:p.price,category:p.category,is_visible:p.is_visible??!0,is_promotion:p.is_promotion??!1,is_featured:p.is_featured??!1}),u(!0)},oe=()=>{l(null),d([]);const p=localStorage.getItem(os);if(p)try{const M=JSON.parse(p);if(M.restaurantId===w?.id&&M.data){g.reset({name:M.data.name||"",description:M.data.description||"",detailed_description:M.data.detailed_description||"",price:M.data.price||"",category:M.data.category||"",is_visible:M.data.is_visible??!0,is_promotion:M.data.is_promotion??!1,is_featured:M.data.is_featured??!1}),b({title:"Borrador restaurado",description:"Se han recuperado los datos del formulario anterior."}),u(!0);return}}catch{localStorage.removeItem(os)}g.reset({name:"",description:"",detailed_description:"",price:"",category:"",is_visible:!0,is_promotion:!1,is_featured:!1}),u(!0)},m=()=>{localStorage.removeItem(os),v(!1),g.reset({name:"",description:"",detailed_description:"",price:"",category:"",is_visible:!0,is_promotion:!1,is_featured:!1}),b({title:"Borrador eliminado",description:"Se ha eliminado el borrador guardado."})},k=p=>{u(p),!p&&n&&l(null)};if(!w)return e.jsx($,{className:"border-0 shadow-elegant",children:e.jsx(q,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Selecciona un restaurante para gestionar su menú."})})});if(a)return e.jsx($,{className:"border-0 shadow-elegant",children:e.jsxs(q,{className:"p-8 text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Cargando elementos del menú..."})]})});const E=i?i.current_count/i.max_items*100:0,P=E>=80,O=i?.at_limit||!1,Z=p=>{switch(p?.toLowerCase()){case"premium":return"Premium";case"basico":case"basic":return"Básico";default:return"Gratuito"}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(An,{}),c&&c.total_reviews>0&&e.jsx($,{children:e.jsxs(q,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Calificación del restaurante:"}),e.jsx(Br,{averageRating:c.average_rating,totalReviews:c.total_reviews,size:"sm"})]})}),i&&e.jsx($,{className:`border ${O?"border-destructive bg-destructive/5":P?"border-amber-400 bg-amber-50":"border-border"}`,children:e.jsx(q,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[O?e.jsx(as,{className:"h-5 w-5 text-destructive flex-shrink-0 mt-0.5"}):P?e.jsx(as,{className:"h-5 w-5 text-amber-500 flex-shrink-0 mt-0.5"}):e.jsx(wa,{className:"h-5 w-5 text-primary flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:`font-medium ${O?"text-destructive":P?"text-amber-700":"text-foreground"}`,children:O?"¡Límite de ítems alcanzado!":P?"Cerca del límite de ítems":"Uso de ítems del menú"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Plan ",Z(i.plan_type),": ",i.current_count," de ",i.max_items," ítems",i.remaining>0&&` (${i.remaining} disponibles)`]})]}),(P||O)&&e.jsx(D,{variant:"outline",size:"sm",className:"flex-shrink-0",onClick:()=>{b({title:"Actualiza tu plan",description:"Contacta a soporte o accede a tu suscripción para aumentar el límite de ítems."})},children:"Actualizar Plan"})]}),e.jsx(aa,{value:E,className:`h-2 ${O?"[&>div]:bg-destructive":P?"[&>div]:bg-amber-500":""}`})]})]})})}),e.jsxs("div",{className:"flex justify-between items-start gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Gestión de Menú"}),e.jsxs("p",{className:"text-muted-foreground",children:["Administra los elementos del menú de ",w.name]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[y&&!n&&e.jsxs("div",{className:"flex items-center gap-1 text-sm text-amber-600 bg-amber-50 px-3 py-1.5 rounded-md border border-amber-200",children:[e.jsx(yr,{className:"h-4 w-4"}),e.jsx("span",{children:"Borrador guardado"}),e.jsx(D,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 ml-1 hover:bg-amber-100",onClick:p=>{p.stopPropagation(),m()},children:e.jsx(hs,{className:"h-3 w-3"})})]}),e.jsxs(ps,{open:h,onOpenChange:k,children:[e.jsx(Fs,{asChild:!0,children:e.jsxs(D,{onClick:oe,disabled:O&&!n,children:[e.jsx(Ns,{className:"h-4 w-4 mr-2"}),O?"Límite alcanzado":y?"Continuar Borrador":"Agregar Elemento"]})}),e.jsxs(fs,{className:"max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(gs,{children:e.jsx(js,{children:n?"Editar Elemento":"Agregar Nuevo Elemento"})}),e.jsx(Qt,{...g,children:e.jsxs("form",{onSubmit:g.handleSubmit(te),className:"space-y-4",children:[e.jsx(he,{control:g.control,name:"name",rules:{required:"El nombre es requerido"},render:({field:p})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Nombre"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"Nombre del plato",...p})}),e.jsx(je,{})]})}),e.jsx(he,{control:g.control,name:"description",rules:{required:"La descripción corta es requerida"},render:({field:p})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Descripción Corta"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"Descripción breve del plato",...p})}),e.jsx(je,{})]})}),e.jsx(he,{control:g.control,name:"detailed_description",render:({field:p})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Descripción Detallada"}),e.jsx(ue,{children:e.jsx(Ds,{placeholder:"Descripción completa del plato (opcional)",...p})}),e.jsx(je,{})]})}),e.jsx(he,{control:g.control,name:"price",rules:{required:"El precio es requerido"},render:({field:p})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Precio"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"$0.00",...p})}),e.jsx(je,{})]})}),e.jsx(he,{control:g.control,name:"category",rules:{required:"La categoría es requerida"},render:({field:p})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Categoría"}),e.jsxs(Re,{onValueChange:p.onChange,value:p.value||void 0,defaultValue:p.value||void 0,children:[e.jsx(ue,{children:e.jsx(Te,{children:e.jsx(Le,{placeholder:"Selecciona una categoría"})})}),e.jsx(Ve,{className:"bg-background z-50",children:da.map(M=>e.jsx(le,{value:M,children:M},M))})]}),e.jsx(je,{})]})}),e.jsx(he,{control:g.control,name:"image",render:({field:p})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Imagen"}),e.jsx(ue,{children:e.jsx(X,{type:"file",accept:"image/*",onChange:M=>p.onChange(M.target.files)})}),e.jsx(je,{})]})}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Tamaños / Variantes (opcional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agrega tamaños con su propio precio (ej. Personal, Mediana, Familiar). Si no agregas variantes se usará el precio principal."})]}),e.jsxs(D,{type:"button",size:"sm",variant:"outline",onClick:()=>d(p=>[...p,{id:crypto.randomUUID(),label:"",price:"",is_default:p.length===0}]),children:[e.jsx(Ns,{className:"h-4 w-4 mr-1"})," Agregar"]})]}),I.length>0&&e.jsx("div",{className:"space-y-2",children:I.map((p,M)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(X,{placeholder:"Nombre (ej. Mediana)",value:p.label,onChange:U=>d(F=>F.map((W,ee)=>ee===M?{...W,label:U.target.value}:W)),className:"flex-1"}),e.jsx(X,{placeholder:"Precio",value:p.price,onChange:U=>d(F=>F.map((W,ee)=>ee===M?{...W,price:U.target.value}:W)),className:"w-28"}),e.jsxs("label",{className:"flex items-center gap-1 text-xs text-muted-foreground whitespace-nowrap",title:"Predeterminada",children:[e.jsx("input",{type:"radio",name:"variant-default",checked:!!p.is_default,onCh
1ange:()=>d(U=>U.map((F,W)=>({...F,is_default:W===M})))}),"Pred."]}),e.jsx(D,{type:"button",size:"sm",variant:"ghost",onClick:()=>d(U=>{const F=U.filter((W,ee)=>ee!==M);return F.length>0&&!F.some(W=>W.is_default)&&(F[0].is_default=!0),F}),children:e.jsx(is,{className:"h-4 w-4 text-destructive"})})]},p.id))})]}),e.jsx(he,{control:g.control,name:"is_visible",render:({field:p})=>e.jsxs(de,{className:"flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(fe,{children:"Visibilidad del Plato"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:p.value?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zt,{className:"h-3 w-3"}),"Visible para los clientes"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wa,{className:"h-3 w-3"}),"Oculto (solo tú puedes verlo)"]})})]}),e.jsx(ue,{children:e.jsx(ns,{checked:p.value,onCheckedChange:p.onChange})})]})}),e.jsx(he,{control:g.control,name:"is_promotion",render:({field:p})=>e.jsxs(de,{className:"flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(fe,{children:"Marcar como Promoción"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:p.value?e.jsx("span",{className:"flex items-center gap-1 text-destructive",children:"🔥 Aparecerá en el popup de promociones"}):e.jsx("span",{children:"No es una promoción activa"})})]}),e.jsx(ue,{children:e.jsx(ns,{checked:p.value,onCheckedChange:p.onChange})})]})}),e.jsx(he,{control:g.control,name:"is_featured",render:({field:p})=>e.jsxs(de,{className:"flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(fe,{children:"⭐ Destacado en categoría"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:p.value?e.jsx("span",{className:"flex items-center gap-1 text-amber-600",children:"Aparecerá como destacado en su categoría"}):e.jsx("span",{children:"Solo 1 plato destacado por categoría — reemplazará al anterior."})})]}),e.jsx(ue,{children:e.jsx(ns,{checked:p.value,onCheckedChange:p.onChange})})]})}),e.jsx(D,{type:"submit",className:"w-full",disabled:C,children:C?e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),e.jsx("span",{children:"Guardando..."})]}):n?"Actualizar Elemento":"Agregar Elemento"})]})})]})]})]})]}),s.length===0?e.jsx($,{className:"border-0 shadow-elegant",children:e.jsxs(q,{className:"p-8 text-center",children:[e.jsx(Sa,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No hay elementos en el menú"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Comienza agregando elementos a tu menú"}),e.jsxs(D,{onClick:oe,children:[e.jsx(Ns,{className:"h-4 w-4 mr-2"}),"Agregar Primer Elemento"]})]})}):e.jsx("div",{className:"space-y-8",children:Array.from(new Set(s.map(p=>p.category).filter(Boolean))).sort((p,M)=>{const U=da.indexOf(p),F=da.indexOf(M);return U!==-1&&F!==-1?U-F:U!==-1?-1:F!==-1?1:p.localeCompare(M)}).map(p=>{const M=s.filter(U=>U.category===p);return M.length===0?null:e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-bold text-foreground mb-4 pb-2 border-b border-border",children:p}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:M.map(U=>e.jsxs($,{className:"border-0 shadow-elegant overflow-hidden",children:[e.jsxs("div",{className:"aspect-video relative bg-muted",children:[ga(U.name,U.image_url)?e.jsx("img",{src:ga(U.name,U.image_url),alt:U.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Ea,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1.5",children:[e.jsx(D,{size:"sm",variant:"secondary",onClick:()=>J(U),title:"Duplicar plato",children:e.jsx(Fr,{className:"h-4 w-4"})}),e.jsx(D,{size:"sm",variant:"secondary",onClick:()=>ge(U),title:"Editar plato",children:e.jsx(br,{className:"h-4 w-4"})}),e.jsx(D,{size:"sm",variant:"destructive",onClick:()=>Y(U.id),title:"Eliminar plato",children:e.jsx(is,{className:"h-4 w-4"})})]})]}),e.jsxs(K,{className:"pb-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsx(Q,{className:"text-lg",children:U.name}),e.jsx("span",{className:"text-lg font-bold text-primary",children:As(U.price)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs px-2 py-1 bg-primary/10 text-primary rounded-full",children:U.category}),U.is_visible===!1&&e.jsxs("span",{className:"text-xs px-2 py-1 bg-muted text-muted-foreground rounded-full flex items-center gap-1",children:[e.jsx(Wa,{className:"h-3 w-3"}),"Oculto"]}),U.is_promotion&&e.jsx("span",{className:"text-xs px-2 py-1 bg-destructive/10 text-destructive rounded-full flex items-center gap-1",children:"🔥 Promo"}),U.is_featured&&e.jsx("span",{className:"text-xs px-2 py-1 bg-amber-100 text-amber-700 rounded-full flex items-center gap-1",children:"⭐ Destacado"})]})]}),e.jsxs(q,{className:"pt-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:U.description}),U.detailed_description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-2",children:U.detailed_description})]})]},U.id))})]},p)})})]})},ks=[{value:"cash",label:"Efectivo",placeholder:"Detalles opcionales (ej: pago contra entrega)"},{value:"mobile_payment",label:"Pago Móvil",placeholder:"Banco / Cédula / Teléfono"},{value:"zelle",label:"Zelle",placeholder:"[email protected] / Nombre del titular"},{value:"binance",label:"Binance",placeholder:"ID Binance Pay / Correo"},{value:"transfer",label:"Transferencia Bancaria",placeholder:"Banco / Tipo / N° de cuenta / Titular"},{value:"card",label:"Tarjeta",placeholder:"Detalles (ej: aceptamos punto de venta)"},{value:"other",label:"Otro",placeholder:"Detalles del método"}],pt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`id_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,Tn=({restaurantId:s,initialPaymentMethods:t,initialExtras:a,onSaved:r})=>{const{toast:n}=Ie(),[l,h]=f.useState(t),[u,C]=f.useState(a),[N,y]=f.useState(!1);f.useEffect(()=>{h(t)},[t]),f.useEffect(()=>{C(a)},[a]);const v=()=>{h(c=>[...c,{id:pt(),type:"cash",label:"Efectivo",details:"",enabled:!0}])},i=(c,g)=>{h(j=>j.map(T=>{if(T.id!==c)return T;const G={...T,...g};if(g.type&&g.type!==T.type){const te=ks.find(Y=>Y.value===T.type);if(!T.label||T.label===te?.label){const Y=ks.find(J=>J.value===g.type);G.label=Y?.label??T.label}}return G}))},S=c=>{h(g=>g.filter(j=>j.id!==c))},I=()=>{C(c=>[...c,{id:pt(),name:"",amount:0}])},d=(c,g)=>{C(j=>
1j.map(T=>T.id===c?{...T,...g}:T))},w=c=>{C(g=>g.filter(j=>j.id!==c))},b=async()=>{const c=u.map(j=>({...j,name:j.name.trim(),amount:Number.isFinite(j.amount)?Math.max(0,Number(j.amount)):0,per_unit:!!j.per_unit})).filter(j=>j.name.length>0),g=l.map(j=>({...j,label:j.label.trim()||ks.find(T=>T.value===j.type)?.label||"Método",details:j.details.trim()})).filter(j=>j.label.length>0);y(!0);try{const{error:j}=await L.from("restaurants").update({delivery_payment_methods:g,delivery_extras:c}).eq("id",s);if(j)throw j;h(g),C(c),n({title:"Configuración de Delivery guardada",description:"Los métodos de pago y extras se actualizaron correctamente."}),r?.()}catch(j){console.error("Error saving delivery settings:",j),n({variant:"destructive",title:"Error",description:"No se pudo guardar la configuración de Delivery."})}finally{y(!1)}};return e.jsxs($,{className:"border-0 shadow-elegant",children:[e.jsx(K,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Ba,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Q,{children:"Configuración de Delivery"}),e.jsx(ve,{children:"Define los métodos de pago aceptados y los cargos adicionales del pedido"})]})]})}),e.jsxs(q,{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"font-semibold text-foreground",children:"Métodos de Pago"})]}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",onClick:v,children:[e.jsx(Ns,{className:"h-4 w-4 mr-1"}),"Añadir método"]})]}),l.length===0?e.jsx("div",{className:"border border-dashed rounded-lg p-6 text-center bg-muted/30",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Aún no has configurado métodos de pago. Añade los que aceptas para delivery."})}):e.jsx("div",{className:"space-y-3",children:l.map(c=>{const g=ks.find(j=>j.value===c.type);return e.jsx("div",{className:"rounded-lg border bg-background/50 p-4 space-y-3",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-12 gap-3 items-start",children:[e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Tipo"}),e.jsxs(Re,{value:c.type,onValueChange:j=>i(c.id,{type:j}),children:[e.jsx(Te,{className:"mt-1",children:e.jsx(Le,{})}),e.jsx(Ve,{children:ks.map(j=>e.jsx(le,{value:j.value,children:j.label},j.value))})]})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Etiqueta visible"}),e.jsx(X,{className:"mt-1",placeholder:g?.label,value:c.label,onChange:j=>i(c.id,{label:j.target.value}),maxLength:60})]}),e.jsxs("div",{className:"md:col-span-5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Detalles"}),e.jsx(X,{className:"mt-1",placeholder:g?.placeholder,value:c.details,onChange:j=>i(c.id,{details:j.target.value}),maxLength:200})]}),e.jsxs("div",{className:"md:col-span-1 flex md:flex-col items-center justify-between md:justify-center gap-2 md:pt-5",children:[e.jsx(ns,{checked:c.enabled,onCheckedChange:j=>i(c.id,{enabled:j}),"aria-label":"Activar método"}),e.jsx(D,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>S(c.id),"aria-label":"Eliminar método",children:e.jsx(is,{className:"h-4 w-4"})})]})]})},c.id)})})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ba,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"font-semibold text-foreground",children:"Extras del pedido"})]}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",onClick:I,children:[e.jsx(Ns,{className:"h-4 w-4 mr-1"}),"Añadir extra"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:["Estos cargos (envío, envases, propina sugerida, etc.) se sumarán automáticamente al total del pedido. Activa ",e.jsx("strong",{children:"Por plato"})," para cobrarlo por cada unidad pedida (ej: un envase por plato)."]}),u.length===0?e.jsx("div",{className:"border border-dashed rounded-lg p-6 text-center bg-muted/30",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No hay extras configurados. Añade los cargos adicionales que aplican a tus pedidos."})}):e.jsx("div",{className:"space-y-3",children:u.map(c=>e.jsxs("div",{className:"rounded-lg border bg-background/50 p-3 grid grid-cols-12 gap-3 items-end",children:[e.jsxs("div",{className:"col-span-12 sm:col-span-6",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Concepto"}),e.jsx(X,{className:"mt-1",placeholder:"Ej: Envase, Envío, Propina sugerida",value:c.name,onChange:g=>d(c.id,{name:g.target.value}),maxLength:60})]}),e.jsxs("div",{className:"col-span-9 sm:col-span-3",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Monto"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground",children:"$"}),e.jsx(X,{type:"number",min:"0",step:"0.01",className:"pl-7",placeholder:"0.00",value:Number.isFinite(c.amount)?c.amount:0,onChange:g=>d(c.id,{amount:parseFloat(g.target.value)||0})})]})]}),e.jsxs("div",{className:"col-span-9 sm:col-span-2 flex flex-col items-start gap-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Por plato"}),e.jsx("div",{className:"h-9 flex items-center",children:e.jsx(ns,{checked:!!c.per_unit,onCheckedChange:g=>d(c.id,{per_unit:g}
1),"aria-label":"Cobrar por cada plato (ej: envase)"})})]}),e.jsx("div",{className:"col-span-3 sm:col-span-1 flex justify-end",children:e.jsx(D,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 text-destructive hover:text-destructive",onClick:()=>w(c.id),"aria-label":"Eliminar extra",children:e.jsx(is,{className:"h-4 w-4"})})})]},c.id))})]}),e.jsxs(D,{type:"button",onClick:b,disabled:N,className:"w-full",children:[N?e.jsx(pe,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(_t,{className:"h-4 w-4 mr-2"}),N?"Guardando...":"Guardar configuración de Delivery"]})]})]})},sa=s=>s.toString().padStart(2,"0"),Ln=s=>{if(!s||!s.includes(":"))return{hour12:"",minute:"",period:"AM"};const[t,a]=s.split(":"),r=parseInt(t,10),n=parseInt(a,10);if(isNaN(r)||isNaN(n))return{hour12:"",minute:"",period:"AM"};const l=r>=12?"PM":"AM",h=r%12===0?12:r%12;return{hour12:String(h),minute:sa(n),period:l}},Vn=(s,t,a)=>{if(!s||!t)return"";let r=parseInt(s,10);const n=parseInt(t,10);return isNaN(r)||isNaN(n)?"":(a==="AM"?r===12&&(r=0):r!==12&&(r+=12),`${sa(r)}:${sa(n)}`)},ft=({value:s,onChange:t,ariaLabel:a})=>{const{hour12:r,minute:n,period:l}=f.useMemo(()=>Ln(s),[s]),h=f.useMemo(()=>Array.from({length:12},(N,y)=>String(y+1)),[]),u=f.useMemo(()=>Array.from({length:12},(N,y)=>sa(y*5)),[]),C=(N,y,v)=>{t(Vn(N,y,v))};return e.jsxs("div",{className:"flex items-center gap-1.5","aria-label":a,children:[e.jsxs(Re,{value:r,onValueChange:N=>C(N,n||"00",l),children:[e.jsx(Te,{className:"w-[72px]","aria-label":"Hora",children:e.jsx(Le,{placeholder:"--"})}),e.jsx(Ve,{className:"max-h-60",children:h.map(N=>e.jsx(le,{value:N,children:N},N))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(Re,{value:n,onValueChange:N=>C(r||"12",N,l),children:[e.jsx(Te,{className:"w-[72px]","aria-label":"Minutos",children:e.jsx(Le,{placeholder:"--"})}),e.jsx(Ve,{className:"max-h-60",children:u.map(N=>e.jsx(le,{value:N,children:N},N))})]}),e.jsxs(Re,{value:l,onValueChange:N=>C(r||"12",n||"00",N),children:[e.jsx(Te,{className:"w-[78px]","aria-label":"AM o PM",children:e.jsx(Le,{})}),e.jsxs(Ve,{children:[e.jsx(le,{value:"AM",children:"AM"}),e.jsx(le,{value:"PM",children:"PM"})]})]})]})},In=[{value:"America/Caracas",label:"Venezuela (Caracas) — GMT-4"},{value:"America/Bogota",label:"Colombia (Bogotá) — GMT-5"},{value:"America/Lima",label:"Perú (Lima) — GMT-5"},{value:"America/Guayaquil",label:"Ecuador (Guayaquil) — GMT-5"},{value:"America/La_Paz",label:"Bolivia (La Paz) — GMT-4"},{value:"America/Santiago",label:"Chile (Santiago) — GMT-4/-3"},{value:"America/Argentina/Buenos_Aires",label:"Argentina (Buenos Aires) — GMT-3"},{value:"America/Montevideo",label:"Uruguay (Montevideo) — GMT-3"},{value:"America/Asuncion",label:"Paraguay (Asunción) — GMT-4/-3"},{value:"America/Sao_Paulo",label:"Brasil (São Paulo) — GMT-3"},{value:"America/Mexico_City",label:"México (CDMX) — GMT-6"},{value:"America/Cancun",label:"México (Cancún) — GMT-5"},{value:"America/Tijuana",label:"México (Tijuana) — GMT-8/-7"},{value:"America/Guatemala",label:"Guatemala — GMT-6"},{value:"America/El_Salvador",label:"El Salvador — GMT-6"},{value:"America/Tegucigalpa",label:"Honduras — GMT-6"},{value:"America/Managua",label:"Nicaragua — GMT-6"},{value:"America/Costa_Rica",label:"Costa Rica — GMT-6"},{value:"America/Panama",label:"Panamá — GMT-5"},{value:"America/Havana",label:"Cuba (La Habana) — GMT-5/-4"},{value:"America/Santo_Domingo",label:"Rep. Dominicana — GMT-4"},{value:"America/Puerto_Rico",label:"Puerto Rico — GMT-4"},{value:"America/New_York",label:"EE.UU. Este (New York) — GMT-5/-4"},{value:"America/Chicago",label:"EE.UU. Central (Chicago) — GMT-6/-5"},{value:"America/Denver",label:"EE.UU. Montaña (Denver) — GMT-7/-6"},{value:"America/Los_Angeles",label:"EE.UU. Pacífico (Los Angeles) — GMT-8/-7"},{value:"Europe/Madrid",label:"España (Madrid) — GMT+1/+2"},{value:"UTC",label:"UTC (GMT+0)"}],Un=()=>{const{currentRestaurant:s,fetchUserRestaurants:t}=ls(),{toast:a}=Ie(),r=wt(),[n,l]=f.useState(!1),[h,u]=f.useState(!1),[C,N]=f.useState(!1),y=Xt({defaultValues:{name:"",description:"",address:"",phone:"",email:"",website:"",instagram:"",delivery_phone:"",country:"",latitude:"",longitude:"",address_radius:"100",monday_open:"",monday_close:"",tuesday_open:"",tuesday_close:"",wednesday_o
1pen:"",wednesday_close:"",thursday_open:"",thursday_close:"",friday_open:"",friday_close:"",saturday_open:"",saturday_close:"",sunday_open:"",sunday_close:"",timezone:"America/Caracas"}});f.useEffect(()=>{if(s){const d=s.hours||{};y.reset({name:s.name||"",description:s.description||"",address:s.address||"",phone:s.phone||"",email:s.email||"",website:s.website||"",instagram:s.instagram||"",delivery_phone:s.delivery_phone||"",country:s.country||"",latitude:s.latitude?.toString()||"",longitude:s.longitude?.toString()||"",address_radius:s.address_radius?.toString()||"100",monday_open:d.monday?.open||"",monday_close:d.monday?.close||"",tuesday_open:d.tuesday?.open||"",tuesday_close:d.tuesday?.close||"",wednesday_open:d.wednesday?.open||"",wednesday_close:d.wednesday?.close||"",thursday_open:d.thursday?.open||"",thursday_close:d.thursday?.close||"",friday_open:d.friday?.open||"",friday_close:d.friday?.close||"",saturday_open:d.saturday?.open||"",saturday_close:d.saturday?.close||"",sunday_open:d.sunday?.open||"",sunday_close:d.sunday?.close||"",timezone:s.timezone||"America/Caracas"})}},[s,y]);const v=async(d,w)=>{try{const b=d.name.split(".").pop(),c=`${w}.${b}`,g=`${s?.id}/${c}`,{error:j}=await L.storage.from("menu-images").upload(g,d,{upsert:!0});if(j)throw j;const{data:T}=L.storage.from("menu-images").getPublicUrl(g);return T.publicUrl}catch(b){return console.error("Error uploading logo:",b),a({variant:"destructive",title:"Error",description:"No se pudo subir el logo."}),null}},i=()=>{r?S():N(!0)},S=()=>{if(N(!1),!navigator.geolocation){a({variant:"destructive",title:"Error",description:"La geolocalización no está disponible en este navegador."});return}u(!0),navigator.geolocation.getCurrentPosition(d=>{y.setValue("latitude",d.coords.latitude.toString()),y.setValue("longitude",d.coords.longitude.toString()),u(!1),a({title:"Ubicación detectada",description:"Las coordenadas GPS han sido establecidas automáticamente."})},d=>{u(!1);let w="No se pudo obtener la ubicación";d.code===d.PERMISSION_DENIED&&(w="Permiso de ubicación denegado"),a({variant:"destructive",title:"Error",description:w})},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})},I=async d=>{if(s){l(!0);try{let w=s.logo_url,b=s.banner_url;if(d.logo&&d.logo.length>0){const j=await v(d.logo[0],"logo");j&&(w=j)}if(d.banner&&d.banner.length>0){const j=await v(d.banner[0],"banner");j&&(b=j)}const c={monday:{open:d.monday_open,close:d.monday_close},tuesday:{open:d.tuesday_open,close:d.tuesday_close},wednesday:{open:d.wednesday_open,close:d.wednesday_close},thursday:{open:d.thursday_open,close:d.thursday_close},friday:{open:d.friday_open,close:d.friday_close},saturday:{open:d.saturday_open,close:d.saturday_close},sunday:{open:d.sunday_open,close:d.sunday_close}},{error:g}=await L.from("restaurants").update({name:d.name,description:d.description,address:d.address,phone:d.phone,email:d.email,website:d.website,instagram:d.instagram,delivery_phone:d.delivery_phone||null,country:d.country,latitude:d.latitude?parseFloat(d.latitude):null,longitude:d.longitude?parseFloat(d.longitude):null,address_radius:d.address_radius?parseInt(d.address_radius):100,logo_url:w,banner_url:b,hours:c,timezone:d.timezone||"America/Caracas"}).eq("id",s.id);if(g)throw g;a({title:"¡Configuración actualizada!",description:"La información del restaurante se ha actualizado correctamente."}),await t()}catch(w){console.error("Error updating restaurant:",w),a({variant:"destructive",title:"Error",description:"No se pudo actualizar la información del restaurante."})}finally{l(!1)}}};return s?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Configuración del Restaurante"}),e.jsxs("p",{className:"text-muted-foreground",children:["Actualiza la información de ",s.name]})]}),e.jsxs($,{className:"border-0 shadow-elegant",children:[e.jsx(K,{children:e.jsx(Q,{children:"Información General"})}),e.jsx(q,{children:e.jsx(Qt,{...y,children:e.jsxs("form",{onSubmit:y.handleSubmit(I),className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(he,{control:y.control,name:"name",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Nombre del Restaurante"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"Nombre del restaurante",...d})}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"email",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Email"}),e.jsx(ue,{children:e.jsx(X,{type:"email",placeholder:"[email protected]",...d})}),e.jsx(je,{})]})})]}),e.jsx(he,{control:y.control,name:"country",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Territorio de Operación"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"Ej: Caracas, Ciudad de México, Bogotá",...d})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ingresa la ciudad o región donde opera tu restaurante"}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"description",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Descripción"}),e.jsx(ue,{children:e.jsx(Ds,{placeholder:"Describe tu restaurante...",rows:3,...d})}),e.jsx(je,{})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(he,{control:y.control,name:"phone",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Teléfono"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"+52 555 123 4567",...d})}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"website",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Sitio Web"}),e.jsx(ue,{children:e.jsx(X,{type:"url",placeholder:"https://turestaurante.com",...d})}),e.jsx(je,{})]})})]}),e.jsx(he,{control:y.control,name:"instagram",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Instagram"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"@turestaurante",...d})}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"delivery_phone",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Delivery"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"Número de Whatsapp",...d})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Número de WhatsApp para pedidos de delivery (incluir código de país, ej: +58 412 1234567)"}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"address",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Dirección"}),e.jsx(ue,{children:e.jsx(X,{placeholder:"Dirección completa del restaurante",...d})}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"logo",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Logo del Restaurante"}),e.jsx(ue,{children:e.jsx(X,{type:"file",accept:"image/*",onChange:w=>d.onChange(w.target.files)})}),e.jsx(je,{})]})}),s.logo_url&&e.jsxs("div",{className:"flex items-center gap-4 p-4 bg-muted rounded-lg",children:[e.jsx("img",{src:s.logo_url,alt:s.name,className:"w-16 h-16 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Logo actual"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sube una nueva imagen para reemplazarlo"})]})]}),e.jsx(he,{control:y.control,name:"banner",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Imagen de Portada / Banner"}),e.jsx(ue,{children:e.jsx(X,{type:"file",accept:"image/*",onChange:w=>d.onChange(w.target.files)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Imagen panorámica que se mostrará como fondo del encabezado del menú. Recomendado: 1200×400px"}),e.jsx(je,{})]})}),s.banner_url&&e.jsxs("div",{className:"p-4 bg-muted rounded-lg space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Banner actual"}),e.jsx("img",{src:s.banner_url,alt:"Banner del restaurante",className:"w-full h-32 rounded-lg object-cover"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sube una nueva imagen para reemplazarlo"})]}),e.jsxs("div",{className:"space-y-4 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Ubicación GPS"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configura la ubicación para detección automática"})]}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",onClick:i,disabled:h,children:[h?e.jsx(pe,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Xr,{className:"h-4 w-4 mr-2"}),h?"Detectando...":"Detectar ubicación"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(he,{control:y.control,name:"latitude",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Latitud"}),e.jsx(ue,{children:e.jsx(X,{type:"number",step:"any",placeholder:"19.4326",...d})}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"longitude",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Longitud"}),e.jsx(ue,{children:e.jsx(X,{type:"number",step:"any",placeholder:"-99.1332",...d})}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:"address_radius",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Radio (metros)"}),e.jsx(ue,{children:e.jsx(X,{type:"number",placeholder:"100",...d})}),e.jsx(je,{})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Los usuarios serán dirigidos automáticamente a tu menú cuando estén dentro del radio especificado."})]}),e.jsxs("div",{className:"space-y-4 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Horarios de Apertura"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configura los horarios de tu restaurante"})]}),e.jsx(he,{control:y.control,name:"timezone",render:({field:d})=>e.jsxs(de,{children:[e.jsx(fe,{children:"Zona horaria del restaurante"}),e.jsxs(Re,{value:d.value||"America/Caracas",onValueChange:d.onChange,children:[e.jsx(ue,{children:e.jsx(Te,{children:e.jsx(Le,{placeholder:"Selecciona la zona horaria"})})}),e.jsx(Ve,{className:"max-h-72",children:In.map(w=>e.jsx(le,{value:w.value,children:w.label},w.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Los horarios se interpretan en la zona horaria del restaurante, sin importar dónde se encuentre el visitante."}),e.jsx(je,{})]})}),e.jsx("div",{className:"space-y-3",children:[{key:"monday",label:"Lunes"},{key:"tuesday",label:"Martes"},{key:"wednesday",label:"Miércoles"},{key:"thursday",label:"Jueves"},{key:"friday",label:"Viernes"},{key:"saturday",label:"Sábado"},{key:"sunday",label:"Domingo"}].map(({key:d,label:w})=>e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 items-center",children:[e.jsx("label",{className:"text-sm font-medium",children:w}),e.jsx(he,{control:y.control,name:`${d}_open`,render:({field:b})=>e.jsxs(de,{children:[e.jsx(ue,{children:e.jsx(ft,{value:b.value||"",onChange:b.onChange,ariaLabel:`Apertura ${w}`})}),e.jsx(je,{})]})}),e.jsx(he,{control:y.control,name:`${d}_close`,render:({field:b})=>e.jsxs(de,{children:[e.jsx(ue,{children:e.jsx(ft,{value:b.value||"",onChange:b.onChange,ariaLabel:`Cierre ${w}`})}),e.jsx(je,{})]})})]},d))})]}),e.jsxs(D,{type:"submit",className:"w-full",disabled:n,children:[e.jsx(_t,{className:"h-4 w-4 mr-2"}),n?"Guardando...":"Guardar Cambios"]})]})})})]}),e.jsx(Tn,{restaurantId:s.id,initialPaymentMethods:s.delivery_payment_methods??[],initialExtras:s.delivery_extras??[],onSaved:t}),e.jsxs($,{className:"border-0 shadow-elegant",children:[e.jsx(K,{children:e.jsx(Q,{children:"URL del Restaurante"})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:"URL pública"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("code",{className:"flex-1 p-2 bg-muted rounded text-sm",children:[window.location.origin,"/restaurant/",s.slug]}),e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(`${window.location.origin}/restaurant/${s.slug}`),a({title:"URL copiada",description:"La URL del restaurante ha sido copiada al portapapeles."})},children:"Copiar"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Esta es la URL pública donde los clientes pueden ver tu menú"})]})})})]}),e.jsx(zs,{open:C,onOpenChange:N,children:e.jsxs($s,{children:[e.jsxs(Os,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-full",children:e.jsx(Nr,{className:"h-6 w-6 text-primary"})}),e.jsx(qs,{children:"💡 Consejo"})]}),e.jsx(Bs,{className:"text-base",children:"Obtén tu ubicación exacta más rápido. Por favor, usa tu dispositivo móvil."})]}),e.jsx(Hs,{children:e.jsx(Gs,{onClick:S,children:"Entendido, continuar"})})]})})]}):e.jsx($,{className:"border-0 shadow-elegant",children:e.jsx(q,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Selecciona un restaurante para configurar."})})})},zn={sent:"Enviado",confirmed_by_customer:"Confirmado por cliente",auto_confirmed:"Auto-confirmado",cancelled_by_restaurant:"Cancelado"},$n={sent:"outline",confirmed_by_customer:"default",auto_confirmed:"secondary",cancelled_by_restaurant:"destructive"};function On({restaurantId:s,billingModel:t}){const[a,r]=f.useState([]),[n,l]=f.useState(!0),[h,u]=f.useState(null),{toast:C}=Ie(),N=async()=>
1{l(!0);const{data:i,error:S}=await L.from("delivery_orders").select("*").eq("restaurant_id",s).order("created_at",{ascending:!1}).limit(100);S?C({title:"Error",description:S.message,variant:"destructive"}):r(i||[]),l(!1)};f.useEffect(()=>{s&&N()},[s]);const y=async i=>{const S=window.prompt("Motivo de cancelación (opcional):")??"";u(i);const{error:I}=await L.rpc("cancel_delivery_order",{_order_id:i,_reason:S});u(null),I?C({title:"Error al cancelar",description:I.message,variant:"destructive"}):(C({title:"Pedido cancelado"}),N())},v=t==="subscription";return e.jsxs($,{children:[e.jsxs(K,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsx(Q,{children:"Pedidos Delivery"}),t&&e.jsx(re,{variant:v?"secondary":"default",children:v?"Modo Suscripción":"Modo Revenue Share"})]}),e.jsx(ve,{children:v?"Modo Suscripción — los pedidos se muestran solo de forma informativa y no se facturan por Revenue Share.":"Pedidos enviados por WhatsApp. Si un pedido no se va a entregar, cancélalo para que no se facture."})]}),e.jsx(q,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(pe,{className:"h-6 w-6 animate-spin"})}):a.length===0?e.jsx("p",{className:"text-muted-foreground text-sm text-center py-8",children:"Aún no hay pedidos. Los pedidos enviados por el cliente vía WhatsApp aparecerán aquí."}):e.jsx("div",{className:"space-y-3",children:a.map(i=>e.jsxs("div",{className:"border rounded-lg p-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(re,{variant:$n[i.status]||"outline",children:zn[i.status]||i.status}),e.jsx("span",{className:"text-sm font-semibold",children:As(String(i.total))}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(i.created_at).toLocaleString()})]}),i.customer_name&&e.jsxs("p",{className:"text-sm mt-1",children:[i.customer_name," ",i.customer_phone?`· ${i.customer_phone}`:""]}),Array.isArray(i.items)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:i.items.map(S=>`${S.quantity||1}× ${S.name}`).join(", ")}),i.cancellation_reason&&e.jsxs("p",{className:"text-xs text-destructive mt-1",children:["Motivo: ",i.cancellation_reason]})]}),i.status==="sent"&&e.jsxs(D,{size:"sm",variant:"outline",onClick:()=>y(i.id),disabled:h===i.id,children:[h===i.id?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsx(hs,{className:"h-4 w-4 mr-1"}),"Cancelar"]})]},i.id))})})]})}const qn={draft:"Borrador",issued:"Emitida",paid:"Pagada",cancelled:"Cancelada",overdue:"Vencida"},Bn={draft:"outline",issued:"secondary",paid:"default",cancelled:"outline",overdue:"destructive"};function Hn({restaurantId:s}){const[t,a]=f.useState([]),[r,n]=f.useState(!0),{toast:l}=Ie(),h=async()=>{n(!0);const{data:u,error:C}=await L.from("revenue_share_invoices").select("*").eq("restaurant_id",s).order("period_start",{ascending:!1});C?l({title:"Error",description:C.message,variant:"destructive"}):a(u||[]),n(!1)};return f.useEffect(()=>{s&&h()},[s]),e.jsxs($,{children:[e.jsxs(K,{children:[e.jsx(Q,{children:"Facturas Revenue Share"}),e.jsx(ve,{children:"Comisión mensual sobre los pedidos delivery confirmados. Coordina el pago con tu Operador o L.U.C. local."})]}),e.jsx(q,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(pe,{className:"h-6 w-6 animate-spin"})}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-sm text-center py-8",children:"Aún no tienes facturas generadas."}):e.jsx("div",{className:"space-y-3",children:t.map(u=>e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(re,{variant:Bn[u.status]||"outline",children:qn[u.status]||u.status}),e.jsxs("span",{className:"ml-2 text-sm font-medium",children:[u.period_start," → ",u.period_end]})]}),e.jsx("span",{className:"text-lg font-bold",children:As(String(u.commission_amount))})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-2 grid grid-cols-2 gap-1",children:[e.jsxs("span",{children:["Pedidos: ",u.orders_count]}),e.jsxs("span",{children:["Bruto: ",As(String(u.gross_orders_total))]}),e.jsxs("span",{children:["Comisión: ",u.commission_percentage,"%"]}),u.due_date&&e.jsxs("span",{children:["Vence: ",u.due_date]}),u.paid_at&&e.jsxs("span",{children:["Pagada: ",new Date(u.paid_at).toLocaleDateString()]}
1),u.payment_reference&&e.jsxs("span",{children:["Ref: ",u.payment_reference]})]})]},u.id))})})]})}const Gn=({hourlyData:s,loading:t})=>{if(t)return e.jsxs($,{children:[e.jsx(K,{children:e.jsx(Ge,{className:"h-6 w-48"})}),e.jsx(q,{children:e.jsx(Ge,{className:"h-64 w-full"})})]});const a=Math.max(...s.map(n=>n.click_count),1),r=s.map(n=>({hour:`${n.hour_of_day.toString().padStart(2,"0")}:00`,clicks:n.click_count,fill:n.click_count>=a*.75?"hsl(var(--primary))":n.click_count>=a*.5?"hsl(var(--primary) / 0.7)":n.click_count>=a*.25?"hsl(var(--primary) / 0.5)":"hsl(var(--primary) / 0.3)"}));return e.jsxs($,{children:[e.jsxs(K,{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(We,{className:"h-5 w-5"}),"Actividad por Hora del Día"]}),e.jsx(ve,{children:"Distribución de clicks por hora (0-23h)"})]}),e.jsx(q,{children:e.jsx(pa,{width:"100%",height:300,children:e.jsxs(St,{data:r,layout:"horizontal",children:[e.jsx(Mt,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Pt,{dataKey:"hour",tick:{fill:"hsl(var(--foreground))",fontSize:11},stroke:"hsl(var(--border))",interval:1}),e.jsx(At,{tick:{fill:"hsl(var(--foreground))"},stroke:"hsl(var(--border))",allowDecimals:!1}),e.jsx(fa,{contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"},formatter:n=>[n,"Clicks"]}),e.jsx(Dt,{dataKey:"clicks",fill:"hsl(var(--primary))",radius:[4,4,0,0]})]})})})]})},Wn=({recentClicks:s,loading:t})=>t?e.jsxs($,{children:[e.jsx(K,{children:e.jsx(Ge,{className:"h-6 w-48"})}),e.jsx(q,{children:e.jsx(Ge,{className:"h-64 w-full"})})]}):e.jsxs($,{children:[e.jsxs(K,{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(an,{className:"h-5 w-5"}),"Clicks Recientes"]}),e.jsx(ve,{children:"Últimas 20 interacciones con el menú"})]}),e.jsx(q,{children:s.length===0?e.jsx("div",{className:"text-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"No hay clicks registrados aún"})}):e.jsxs(Lt,{children:[e.jsx(Vt,{children:e.jsxs(Ys,{children:[e.jsx(Ye,{children:"Plato"}),e.jsx(Ye,{children:"Categoría"}),e.jsx(Ye,{children:"Hora"}),e.jsx(Ye,{children:"Sesión"})]})}),e.jsx(It,{children:s.map((a,r)=>e.jsxs(Ys,{children:[e.jsx(Ze,{className:"font-medium",children:a.menu_item_name}),e.jsx(Ze,{children:e.jsx(re,{variant:"outline",children:a.menu_item_category})}),e.jsx(Ze,{className:"text-sm text-muted-foreground whitespace-nowrap",children:be(new Date(a.clicked_at),"dd MMM yyyy, HH:mm",{locale:Ce})}),e.jsxs(Ze,{className:"text-xs text-muted-foreground font-mono truncate max-w-[120px]",children:[a.session_id.replace("session-","").substring(0,12),"…"]})]},`${a.clicked_at}-${r}`))})]})})]}),gt=["hsl(var(--primary))","hsl(var(--secondary))","hsl(var(--accent))","hsl(var(--muted))"],Yn=({restaurantId:s})=>{const[t,a]=f.useState("30"),{analyticsData:r,loading:n,error:l,refetchAnalytics:h}=Hr(s),{hourlyData:u,loading:C,refetchHourly:N}=Gr(s),{recentClicks:y,loading:v}=Wr(s),i=c=>{a(c);const g=parseInt(c),j=Ft(new Date,g),T=new Date;h(j,T),N(j,T)},S=()=>{const G="\uFEFF"+[["Plato","Categoría","Total Clicks","Sesiones Únicas","Hoy","Esta Semana","Este Mes"].map(J=>`"${J}"`).join(";"),...r.map(J=>[`"${J.menu_item_name.replace(/"/g,'""')}"`,`"${J.menu_item_category.replace(/"/g,'""')}"`,`"${J.total_clicks}"`,`"${J.unique_sessions}"`,`"${J.clicks_today}"`,`"${J.clicks_this_week}"`,`"${J.clicks_this_month}"`].join(";"))].join(`\r
2`),te=new Blob([G],{type:"text/csv;charset=utf-8;"}),Y=document.createElement("a");Y.href=URL.createObjectURL(te),Y.download=`analisis_menu_${be(new Date,"yyyy-MM-dd")}.csv`,document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),URL.revokeObjectURL(Y.href)},I=()=>r.reduce((c,g)=>({totalClicks:c.totalClicks+g.total_clicks,totalSessions:c.totalSessions+g.unique_sessions,clicksToday:c.clicksToday+g.clicks_today,clicksThisWeek:c.clicksThisWeek+g.clicks_this_week}),{totalClicks:0,totalSessions:0,clicksToday:0,clicksThisWeek:0}),d=(c=5)=>[...r].sort((g,j)=>j.total_clicks-g.total_clicks).slice(0,c),w=()=>{const c=r.reduce((g,j)=>(g[j.menu_item_category]||(g[j.menu_item_category]={name:j.menu_item_category,clicks:0}),g[j.menu_item_category].clicks+=j.total_clicks,g),{});return Object.values(c)},b=I();return n?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:Array.from({length:4}).map((c,g)=>e.jsx($,{children:e.jsxs(K,{className:"pb-2",children:[e.jsx(Ge,{className:"h-4 w-24"}),e.jsx(Ge,{className:"h-8 w-16"})]})},g))}),e.jsxs($,{children:[e.jsx(K,{children:e.jsx(Ge,{className:"h-6 w-32"})}),e.jsx(q,{children:e.jsx(Ge,{className:"h-64 w-full"})})]})]}):l?e.jsx($,{children:e.jsx(q,{className:"pt-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-muted-foreground",children:l}),e.jsx(D,{onClick:()=>h(),className:"mt-4",children:"Reintentar"})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-between items-start",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Análisis del Menú"}),e.jsx("p",{className:"text-muted-foreground",children:"Métricas de interacción con los platos"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Re,{value:t,onValueChange:i,children:[e.jsxs(Te,{className:"w-32",children:[e.jsx(xs,{className:"h-4 w-4 mr-2"}),e.jsx(Le,{})]}),e.jsxs(Ve,{children:[e.jsx(le,{value:"7",children:"7 días"}),e.jsx(le,{value:"30",children:"30 días"}),e.jsx(le,{value:"90",children:"90 días"})]})]}),e.jsxs(D,{onClick:S,variant:"outline",children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Exportar"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs($,{children:[e.jsxs(K,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Q,{className:"text-sm font-medium",children:"Clicks Totales"}),e.jsx(nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(q,{children:[e.jsx("div",{className:"text-2xl font-bold",children:b.totalClicks}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.clicksToday," hoy"]})]})]}),e.jsxs($,{children:[e.jsxs(K,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Q,{className:"text-sm font-medium",children:"Sesiones Únicas"}),e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(q,{children:[e.jsx("div",{className:"text-2xl font-bold",children:b.totalSessions}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visitantes únicos"})]})]}),e.jsxs($,{children:[e.jsxs(K,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Q,{className:"text-sm font-medium",children:"Esta Semana"}),e.jsx(Zs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(q,{children:[e.jsx("div",{className:"text-2xl font-bold",children:b.clicksThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks últimos 7 días"})]})]}),e.jsxs($,{children:[e.jsxs(K,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Q,{className:"text-sm font-medium",children:"Platos Populares"}),e.jsx(Zs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(q,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d(3).length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Con más interacciones"})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs($,{children:[e.jsxs(K,{children:[e.jsx(Q,{children:"Platos Más Populares"}),e.jsx(ve,{children:"Top 5 platos por número de clicks"})]}),e.jsx(q,{children:e.jsx(pa,{width:"100%",height:300,children:e.jsxs(St,{data:d(),children:[e.jsx(Mt,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Pt,{dataKey:"menu_item_name",tick:{fill:"hsl(var(--foreground))",fontSize:12},stroke:"hsl(var(--border))",angle:-45,textAnchor:"end",height:80}
2),e.jsx(At,{tick:{fill:"hsl(var(--foreground))"},stroke:"hsl(var(--border))"}),e.jsx(fa,{contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Dt,{dataKey:"total_clicks",fill:"hsl(var(--primary))",name:"Clicks"})]})})})]}),e.jsxs($,{children:[e.jsxs(K,{children:[e.jsx(Q,{children:"Clicks por Categoría"}),e.jsx(ve,{children:"Distribución de interacciones por categoría"})]}),e.jsx(q,{children:e.jsx(pa,{width:"100%",height:300,children:e.jsxs(_r,{children:[e.jsx(wr,{data:w(),cx:"50%",cy:"50%",labelLine:!1,label:({name:c,percent:g})=>`${c} ${(g*100).toFixed(0)}%`,outerRadius:80,fill:"#8884d8",dataKey:"clicks",children:w().map((c,g)=>e.jsx($r,{fill:gt[g%gt.length]},`cell-${g}`))}),e.jsx(fa,{contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}})]})})})]})]}),e.jsx(Gn,{hourlyData:u,loading:C}),e.jsx(Wn,{recentClicks:y,loading:v}),e.jsxs($,{children:[e.jsxs(K,{children:[e.jsx(Q,{children:"Análisis Detallado por Plato"}),e.jsx(ve,{children:"Métricas completas de cada elemento del menú"})]}),e.jsxs(q,{children:[e.jsxs(Lt,{children:[e.jsx(Vt,{children:e.jsxs(Ys,{children:[e.jsx(Ye,{children:"Plato"}),e.jsx(Ye,{children:"Categoría"}),e.jsx(Ye,{className:"text-center",children:"Total Clicks"}),e.jsx(Ye,{className:"text-center",children:"Sesiones Únicas"}),e.jsx(Ye,{className:"text-center",children:"Hoy"}),e.jsx(Ye,{className:"text-center",children:"Esta Semana"}),e.jsx(Ye,{className:"text-center",children:"Este Mes"})]})}),e.jsx(It,{children:r.map(c=>e.jsxs(Ys,{children:[e.jsx(Ze,{className:"font-medium",children:c.menu_item_name}),e.jsx(Ze,{children:e.jsx(re,{variant:"outline",children:c.menu_item_category})}),e.jsx(Ze,{className:"text-center font-bold",children:c.total_clicks}),e.jsx(Ze,{className:"text-center",children:c.unique_sessions}),e.jsx(Ze,{className:"text-center",children:c.clicks_today}),e.jsx(Ze,{className:"text-center",children:c.clicks_this_week}),e.jsx(Ze,{className:"text-center",children:c.clicks_this_month})]},c.menu_item_id))})]}),r.length===0&&e.jsx("div",{className:"text-center py-8",children:e.jsx("p",{className:"text-muted-foreground",children:"No hay datos de analytics disponibles para este período"})})]})]})]})},tr=[{id:"promo_day",name:"Promoción del día",icon:Tt,title:"🎉 ¡Promoción especial!",body:"Hoy tenemos una oferta especial para ti. ¡No te la pierdas!",color:"text-green-600",bgColor:"bg-green-500/10 hover:bg-green-500/20"},{id:"new_dish",name:"Nuevo platillo",icon:Sa,title:"🍽️ ¡Nuevo en el menú!",body:"Hemos agregado un nuevo platillo a nuestro menú. ¡Ven a probarlo!",color:"text-orange-600",bgColor:"bg-orange-500/10 hover:bg-orange-500/20"},{id:"happy_hour",name:"Happy Hour",icon:We,title:"⏰ ¡Happy Hour activo!",body:"De 4pm a 7pm disfruta de promociones especiales en bebidas.",color:"text-blue-600",bgColor:"bg-blue-500/10 hover:bg-blue-500/20"},{id:"event",name:"Evento especial",icon:ln,title:"📅 ¡Evento este fin de semana!",body:"Tenemos un evento especial preparado para ti. ¡Reserva tu lugar!",color:"text-purple-600",bgColor:"bg-purple-500/10 hover:bg-purple-500/20"},{id:"announcement",name:"Anuncio general",icon:Or,title:"📢 ¡Tenemos noticias!",body:"Queremos compartir algo importante contigo.",color:"text-amber-600",bgColor:"bg-amber-500/10 hover:bg-amber-500/20"}];function Zn({onSelectTemplate:s,selectedTemplateId:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Plantillas rápidas"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:tr.map(a=>{const r=a.icon,n=t===a.id;return e.jsxs(D,{variant:"ghost",size:"sm",onClick:()=>s(a.title,a.body),className:Oe("gap-2 border transition-all",a.bgColor,a.color,n&&"ring-2 ring-primary ring-offset-2"),children:[e.jsx(r,{className:"h-4 w-4"}),a.name]},a.id)})})]})}function Kn({title:s,body:t,restaurantName:a,logoUrl:r,imageUrl:n}){const l=s.trim()||t.trim();return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Vista previa"}),e.jsx("div",{className:"rounded-xl bg-gradient-to-br from-secondary/80 to-secondary p-1 shadow-lg border",children:e.jsxs("div",{className:"bg-background/95 backdrop-blur-sm rounded-lg p-3 shadow-sm",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg overflow-hidden flex-shrink-0 bg-primary/10 flex items-center justify-center",children:r?e.jsx("img",{src:r,alt:a,className:"w-full h-full object-cover"}):e.jsx(Es,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 mb-0.5",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Live Menu"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"ahora"})]}),e.jsx("p",{className:Oe("font-semibold text-sm line-clamp-1",!l&&"text-muted-foreground
2/50 italic"),children:s.trim()||"Título de la notificación"}),e.jsx("p",{className:Oe("text-sm text-muted-foreground line-clamp-2 mt-0.5",!l&&"opacity-50 italic"),children:t.trim()||"El mensaje de tu notificación aparecerá aquí..."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:a})]}),e.jsx("button",{className:"p-1 rounded-full hover:bg-accent transition-colors flex-shrink-0",children:e.jsx(hs,{className:"h-3.5 w-3.5 text-muted-foreground"})})]}),n&&e.jsx("div",{className:"mt-3 rounded-lg overflow-hidden",children:e.jsx("img",{src:n,alt:"Imagen de notificación",className:"w-full h-32 object-cover"})}),e.jsxs("div",{className:"flex gap-2 mt-3 pt-2 border-t",children:[e.jsx("button",{className:"flex-1 text-xs font-medium text-primary py-1.5 rounded-md hover:bg-primary/10 transition-colors",children:"Ver más"}),e.jsx("button",{className:"flex-1 text-xs font-medium text-muted-foreground py-1.5 rounded-md hover:bg-accent transition-colors",children:"Cerrar"})]})]})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Así verán la notificación tus seguidores"})]})}function Jn({restaurantId:s}){const[t,a]=f.useState([]),[r,n]=f.useState([]),[l,h]=f.useState(!0),[u,C]=f.useState(null),[N,y]=f.useState(!1),[v,i]=f.useState(0),[S,I]=f.useState(0),[d,w]=f.useState(0),[b,c]=f.useState({from:void 0,to:void 0}),{toast:g}=Ie(),j=f.useCallback(async()=>{try{h(!0);const{data:m,error:k}=await L.rpc("get_notification_engagement_stats",{p_restaurant_id:s});if(k)throw k;const E=m||[];a(E),n(E);const P=E.reduce((Z,p)=>Z+Number(p.click_count),0),O=E.reduce((Z,p)=>Z+p.success_count,0);I(P),w(O),i(O>0?P/O*100:0)}catch(m){console.error("Error fetching engagement stats:",m)}finally{h(!1)}},[s]);f.useEffect(()=>{j()},[j]),f.useEffect(()=>{if(!b.from&&!b.to){n(t);return}const m=t.filter(P=>{const O=new Date(P.sent_at),Z=b.from?Ut(b.from):null,p=b.to?Ct(b.to):null;return Z&&p?O>=Z&&O<=p:Z?O>=Z:p?O<=p:!0});n(m);const k=m.reduce((P,O)=>P+Number(O.click_count),0),E=m.reduce((P,O)=>P+O.success_count,0);I(k),w(E),i(E>0?k/E*100:0)},[b,t]);const T=async m=>{try{C(m);const{error:k}=await L.rpc("delete_notification_log",{p_notification_log_id:m});if(k)throw k;g({title:"Métrica eliminada",description:"El registro de notificación ha sido eliminado correctamente."}),await j()}catch(k){console.error("Error deleting notification:",k),g({variant:"destructive",title:"Error",description:"No se pudo eliminar el registro de notificación."})}finally{C(null)}},G=async()=>{try{y(!0);const{error:m}=await L.rpc("delete_all_notification_logs",{p_restaurant_id:s});if(m)throw m;g({title:"Métricas eliminadas",description:"Todos los registros de notificación han sido eliminados."}),await j()}catch(m){console.error("Error deleting all notifications:",m),g({variant:"destructive",title:"Error",description:"No se pudieron eliminar los registros de notificación."})}finally{y(!1)}},te=()=>{c({from:void 0,to:void 0})},Y=m=>{const k=new Date,E=Ft(k,m);c({from:E,to:k})},J=m=>new Date(m).toLocaleString("es-MX",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"}),ge=m=>m>=20?"text-green-600":m>=10?"text-yellow-600":"text-muted-foreground",oe=m=>m>=20?"default":m>=10?"secondary":"outline";return l?e.jsx($,{children:e.jsx(q,{className:"py-8",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(pe,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx($,{className:"bg-gradient-to-br from-blue-500/10 to-blue-600/5 border-blue-500/20",children:e.jsx(q,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Total Enviadas"}),e.jsx("p",{className:"text-2xl font-bold",children:d})]}),e.jsx(Ca,{className:"h-8 w-8 text-blue-500 opacity-80"})]})})}),e.jsx($,{className:"bg-gradient-to-br from-green-500/10 to-green-600/5 border-green-500/20",children:e.jsx(q,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Total Clics"}),e.jsx("p",{className:"text-2xl font-bold",children:S})]}),e.jsx(rn,{className:"h-8 w-8 text-green-500 opacity-80"})]})})}),e.jsx($,{className:"bg-gradient-to-br from-primary/10 to-accent/5 border-primary/20",children:e.jsx(q,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Tasa de Apertura"}),e.jsxs("p",{className:"text-2xl font-bold",children:[v.toFixed(1),"%"]})]}),e.jsx(Zs,{className:"h-8 w-8 text-primary opacity-80"})]})})})]}),e.jsx($,{children:e.jsx(K,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Filtrar por fecha"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(D,{variant:"outline",size:"sm",onClick:()=>Y(7),className:"text-xs",children:"Última semana"}),e.jsx(D,{variant:"outline",size:"sm",onClick:()=>Y(30),className:"text-xs",children:"Último mes"}),e.jsxs(ja,{children:[e.jsx(va,{asChild:!0,children:e.jsxs(D,{variant:"outline",size:"sm",className:"text-xs",children:[e.jsx(xs,{className:"h-3 w-3 mr-1"}),b.from?b.to?e.jsxs(e.Fragment,{children:[be(b.from,"dd MMM",{locale:Ce})," - ",be(b.to,"dd MMM",{locale:Ce})]}):be(b.from,"dd MMM yyyy",{locale:Ce}):"Rango personalizado"]})}),e.jsx(ya,{className:"w-auto p-0",align:"end",children:e.jsx(ua,{mode:"range",selected:{from:b.from,to:b.to},onSelect:m=>c({from:m?.from,to:m?.to}),numberOfMonths:1,locale:Ce,className:Oe("p-3 pointer-events-auto")})})]}),(b.from||b.to)&&e.jsxs(D,{variant:"ghost",size:"sm",onClick:te,className:"text-xs",children:[e.jsx(hs,{className:"h-3 w-3 mr-1"}),"Limpiar"]})]})]})})}),e.jsxs($,{children:[e.jsx(K,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-5 w-5"}),"Métricas por Notificación"]}),e.jsx(ve,{children:b.from||b.to?`${r.length} notificaciones en el rango seleccionado`:`Engagement detallado de las últimas ${t.length} notificaciones`})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{variant:"ghost",size:"sm",onClick:j,disabled:l,children:e.jsx(Nt,{className:Oe("h-4 w-4",l&&"animate-spin")})}),t.length>0&&e.jsxs(zs,{children:[e.jsx(xa,{asChild:!0,children:e.jsx(D,{variant:"destructive",size:"sm",disabled:N,children:N?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(is,{className:"h-4 w-4 mr-1"}),"Borrar todo"]})})}),e.jsxs($s,{children:[e.jsxs(Os,{children:[e.jsx(qs,{children:"¿Eliminar todas las métricas?"}),e.jsx(Bs,{children:"Esta acción eliminará permanentemente todos los registros de notificaciones y sus métricas de engagement. Esta acción no se puede deshacer."})]}),e.jsxs(Hs,{children:[e.jsx(ha,{children:"Cancelar"}),e.jsx(Gs,{onClick:G,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Eliminar todo"})]})]})]})]})]})}),e.jsx(q,{children:r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ba,{className:"h-12 w-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No hay datos de engagement disponibles"}),e.jsx("p",{className:"text-sm mt-1",children:b.from||b.to?"No hay notificaciones en el rango de fechas seleccionado":"Envía notificaciones para ver las métricas aquí"})]}):e.jsx("div",{className:"space-y-4",children:r.map(m=>e.jsxs("div",{className:"p-4 border rounded-lg hover:bg-accent/30 transition-colors group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:m.title}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:m.body}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:J(m.sent_at)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(re,{variant:oe(Number(m.click_rate)),children:[Number(m.click_rate).toFixed(1),"% apertura"]}),e.jsxs(zs,{children:[e.jsx(xa,{asChild:!0,children:e.jsx(D,{variant:"ghost",size:"icon",className:"opacity-0 group-hover:opacity-100 transition-opacity h-8 w-8",disabled:u===m.notification_log_id,children:u===m.notification_log_id?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsx(is,{className:"h-4 w-4 text-destructive"})})}),e.jsxs($s,{children:[e.jsxs(Os,{children:[e.jsx(qs,{children:"¿Eliminar esta métrica?"}),e.jsxs(Bs,{children:['Se eliminará el registro de la notificación "',m.title,'" y sus métricas de engagement. Esta acción no se puede deshacer.']})]}),e.jsxs(Hs,{children:[e.jsx(ha,{children:"Cancelar"}),e.jsx(Gs,{onClick:()=>T(m.notification_log_id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Eliminar"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:[m.click_count," clics de ",Number(m.delivered_count)>0?`${m.delivered_count} recibidas`:`${m.success_count} enviadas`]}),e.jsxs("span",{className:`font-medium ${ge(Number(m.click_rate))}`,children:[Number(m.click_rate).toFixed(1),"%"]})]}),e.jsx(aa,{value:Number(m.click_rate),className:"h-2"})]})]},m.notification_log_id))})})]})]})}const Xn=5*1024*1024,Qn=["image/jpeg","image/png","image/webp"];function ei({restaurantId:s,selectedImageUrl:t,onSelectImage:a}){const[r,n]=f.useState([]),[l,h]=f.useState(!0),[u,C]=f.useState(!1),[N,y]=f.useState(!1),v=f.useRef(null);f.useEffect(()=>{s&&(async()=>{try{const{data:w,error:b}=await L.from("menu_items").select("id, name, image_url, category").eq("restaurant_id",s).eq("is_visible",!0).not("image_url","is",null).order("category",{ascending:!0});if(b)throw b;n(w||[])}catch(w){console.error("Error fetching menu items:",w)}finally{h(!1)}})()},[s]);const i=()=>{a(null)},S=()=>{v.current?.click()},I=async d=>{const w=d.target.files?.[0];if(w){if(!Qn.includes(w.type)){ce.error("Formato no soportado. Usa JPG, PNG o WebP.");return}if(w.size>Xn){ce.error("La imagen es muy grande. Máximo 5MB.");return}y(!0);try{const b=w.name.split(".").pop()?.toLowerCase()||"jpg",c=`notification-${Date.now()}.${b}`,g=`${s}/notifications/${c}`,{error:j}=await L.storage.from("menu-images").upload(g,w,{cacheControl:"3600",upsert:!1});if(j)throw j;const{data:T}=L.storage.from("menu-images").getPublicUrl(g);T?.publicUrl&&(a(T.publicUrl),ce.success("Imagen subida correctamente"))}catch(b){console.error("Error uploading image:",b),ce.error(b.message||"Error al subir la imagen")}finally{y(!1),v.current&&(v.current.value="")}}};return l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(pe,{className:"h-4 w-4 animate-spin"}),"Cargando imágenes..."]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{ref:v,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:I,className:"hidden"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(D,{type:"button",variant:"ghost",size:"sm",onClick:()=>C(!u),className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(st,{className:"h-4 w-4"}),u?"Ocultar imágenes":"Añadir imagen del menú",t&&e.jsx("span",{className:"text-xs bg-primary/20 text-primary px-1.5 py-0.5 rounded",children:"1 seleccionad
2a"})]}),t&&e.jsxs(D,{type:"button",variant:"ghost",size:"sm",onClick:i,className:"gap-1 text-muted-foreground hover:text-destructive",children:[e.jsx(hs,{className:"h-3 w-3"}),"Quitar"]})]}),u&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:N,className:"w-full gap-2 border-dashed",children:N?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 animate-spin"}),"Subiendo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ea,{className:"h-4 w-4"}),"Subir imagen desde dispositivo"]})}),r.length>0?e.jsx(kt,{className:"h-32 rounded-lg border bg-muted/30 p-2",children:e.jsx("div",{className:"flex gap-2",children:r.map(d=>{const w=d.image_url||ga(d.name),b=t===w;return e.jsxs("button",{type:"button",onClick:()=>a(b?null:w),className:Oe("relative flex-shrink-0 w-24 h-24 rounded-lg overflow-hidden transition-all","ring-2 ring-offset-2 ring-offset-background",b?"ring-primary scale-105":"ring-transparent hover:ring-primary/50"),children:[e.jsx("img",{src:w,alt:d.name,className:"w-full h-full object-cover",loading:"lazy"}),e.jsx("div",{className:Oe("absolute inset-0 bg-black/40 flex items-center justify-center transition-opacity",b?"opacity-100":"opacity-0"),children:e.jsx(Tr,{className:"h-6 w-6 text-white"})}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-1",children:e.jsx("p",{className:"text-[10px] text-white font-medium line-clamp-1",children:d.name})})]},d.id)})})}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground p-3 bg-muted/50 rounded-lg",children:[e.jsx(st,{className:"h-4 w-4"}),"No hay platillos con imágenes disponibles"]})]}),t&&!u&&e.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded-lg",children:[e.jsx("img",{src:t,alt:"Imagen seleccionada",className:"w-12 h-12 rounded object-cover"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Imagen incluida en la notificación"})]})]})}const jt=[{v:1,label:"Lun"},{v:2,label:"Mar"},{v:3,label:"Mié"},{v:4,label:"Jue"},{v:5,label:"Vie"},{v:6,label:"Sáb"},{v:0,label:"Dom"}],si=Array.from({length:24},(s,t)=>t),vt=()=>({name:"",days_of_week:[],hours_local:[],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",menu_item_ids:[],is_active:!0,custom_image_url:null});function ai({restaurantId:s,disabled:t}){const[a,r]=f.useState([]),[n,l]=f.useState([]),[h,u]=f.useState(!0),[C,N]=f.useState(!1),[y,v]=f.useState(null),[i,S]=f.useState(vt()),[I,d]=f.useState(!1),w=f.useCallback(async()=>{u(!0);try{const[{data:m,error:k},{data:E,error:P}]=await Promise.all([L.from("auto_promo_schedules").select("*").eq("restaurant_id",s).order("created_at"),L.from("menu_items").select("id, name, price, image_url").eq("restaurant_id",s).eq("is_promotion",!0).eq("is_visible",!0).order("name")]);if(k)throw k;if(P)throw P;r(m||[]),l(E||[])}catch(m){console.error(m),ce.error("Error al cargar las reglas")}finally{u(!1)}},[s]);f.useEffect(()=>{w()},[w]);const b=()=>{v(null),S(vt()),N(!0)},c=m=>{v(m.id),S({name:m.name||"",days_of_week:m.days_of_week||[],hours_local:m.hours_local||[],timezone:m.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",menu_item_ids:m.menu_item_ids||[],is_active:m.is_active,custom_image_url:m.custom_image_url||null}),N(!0)},g=(m,k)=>m.includes(k)?m.filter(E=>E!==k):[...m,k],j=async()=>{if(i.days_of_week.length===0)return ce.error("Selecciona al menos un día");if(i.hours_local.length===0)return ce.error("Selecciona al menos una hora");if(i.menu_item_ids.length===0&&!i.custom_image_url)return ce.error("Selecciona al menos una promoción o sube una imagen");if(i.menu_item_ids.length===0&&i.custom_image_url&&!i.name?.trim())return ce.error("Cuando uses solo imagen, escribe un nombre para la regla (será el mensaje)");d(!0);try{const m={restaurant_id:s,name:i.name?.trim()||null,days_of_week:i.days_of_week,hours_local:i.hours_local,timezone:i.timezone,menu_item_ids:i.menu_item_ids,is_active:i.is_active,custom_image_url:i.custom_image_url||null},{error:k}=y?await L.from("auto_promo_schedules").update(m).eq("id",y):await L.from("auto_promo_schedules").insert(m);if(k)throw k;ce.success(y?"Regla actualizada":"Regla creada"),N(!1),w()}catch(m){console.error(m),ce.error("Error al guardar la regla")}finally{d(!1)}},T=async(m,k)=>{try{const{error:E}=await L.from("auto_promo_schedules").update({is_active:k}).eq("id",m.id);if(E)throw E;r(P=>P.map(O=>O.id===m.id?{...O,is_active:k}:O))}catch(E){console.error(E),ce.error("Error al actualizar")}},[G,te]=f.useState(!1),Y=async m=>{if(!m.type.startsWith("image/")){ce.error("Solo se permiten imágenes");return}if(m.size>5*1024*1024){ce.error("La imagen debe pesar menos de 5 MB");return}m.size>500*1024&&ce.warning("La imagen pesa más de 500 KB. Puede tardar en cargar o no mostrarse en algunos dispositivos.");try{const k=await new Promise((P,O)=>{const Z=new Image;Z.onload=()=>
2P({w:Z.naturalWidth,h:Z.naturalHeight}),Z.onerror=O,Z.src=URL.createObjectURL(m)});k.w/k.h<1.5?ce.warning("La imagen es muy vertical. Para mejores resultados usa una imagen horizontal (ratio 2:1, ej. 1024×512 px)."):k.w<600&&ce.warning("La imagen tiene baja resolución. Recomendado mínimo 1024×512 px.")}catch{}te(!0);try{const k=m.name.split(".").pop()||"jpg",E=`${s}/auto-promo/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${k}`,{error:P}=await L.storage.from("menu-images").upload(E,m,{cacheControl:"3600",upsert:!1});if(P)throw P;const{data:O}=L.storage.from("menu-images").getPublicUrl(E);S(Z=>({...Z,custom_image_url:O.publicUrl})),ce.success("Imagen subida")}catch(k){console.error(k),ce.error("Error al subir la imagen")}finally{te(!1)}},J=async m=>{if(confirm("¿Eliminar esta regla?"))try{const{error:k}=await L.from("auto_promo_schedules").delete().eq("id",m);if(k)throw k;ce.success("Regla eliminada"),r(E=>E.filter(P=>P.id!==m))}catch(k){console.error(k),ce.error("Error al eliminar")}},ge=m=>jt.filter(k=>m.includes(k.v)).map(k=>k.label).join(", ")||"—",oe=m=>[...m].sort((k,E)=>k-E).map(k=>`${k.toString().padStart(2,"0")}:00`).join(", ")||"—";return e.jsx($,{children:e.jsxs(q,{className:"py-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Notificaciones automáticas de promociones"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Programa días, horas y promociones específicas a enviar"})]})]}),e.jsxs(D,{size:"sm",onClick:b,disabled:t||h,className:"gap-1",children:[e.jsx(Ns,{className:"h-4 w-4"})," Nueva regla"]})]}),h?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(pe,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No hay reglas configuradas. Crea una para programar envíos automáticos."}):e.jsx("div",{className:"space-y-2",children:a.map(m=>e.jsx("div",{className:"border rounded-lg p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:m.name||"Sin nombre"}),!m.is_active&&e.jsx(re,{variant:"secondary",className:"text-[10px]",children:"Inactiva"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-1",children:[e.jsxs("p",{className:"flex items-center gap-1",children:[e.jsx(xs,{className:"h-3 w-3"}),ge(m.days_of_week)]}),e.jsxs("p",{className:"flex items-center gap-1",children:[e.jsx(We,{className:"h-3 w-3"}),oe(m.hours_local)]}),e.jsxs("p",{children:[m.menu_item_ids.length," promoción(es)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ns,{checked:m.is_active,onCheckedChange:k=>T(m,k),disabled:t}),e.jsx(D,{size:"icon",variant:"ghost",onClick:()=>c(m),disabled:t,children:e.jsx(qr,{className:"h-4 w-4"})}),e.jsx(D,{size:"icon",variant:"ghost",onClick:()=>J(m.id),disabled:t,children:e.jsx(is,{className:"h-4 w-4 text-destructive"})})]})]})},m.id))}),e.jsx(ps,{open:C,onOpenChange:N,children:e.jsxs(fs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(gs,{children:e.jsx(js,{children:y?"Editar regla":"Nueva regla de envío"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Nombre (opcional)"}),e.jsx(X,{value:i.name||"",onChange:m=>S({...i,name:m.target.value}),placeholder:"Ej: Happy Hour",maxLength:60})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Días de la semana"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:jt.map(m=>e.jsx("button",{type:"button",onClick:()=>S({...i,days_of_week:g(i.days_of_week,m.v)}),className:`px-3 py-1.5 rounded text-xs font-medium transition-colors ${i.days_of_week.includes(m.v)?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-accent"}`,children:m.label},m.v))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{children:["Horas (zona local: ",i.timezone,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:si.map(m=>e.jsxs("button",{type:"button",onClick:()=>S({...i,hours_local:g(i.hours_local,m)}),className:`px-2 py-1 rounded text-xs font-medium transition-colors ${i.hours_local.includes(m)?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-accent"}`,children:[m.toString().padStart(2,"0"),":00"]},m))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Promociones a enviar"}),n.length===0?e.jsx("p",{className:"text-xs text-muted-foreground border rounded p-3",children:'No hay platos marcados como promoción. Marca "Promoción" en el menú primero.'}):e.jsx("div",{className:"border rounded-lg max-h-56 overflow-y-auto divide-y",children:n.map(m=>e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-accent/50",children:[e.jsx(Sr,{checked:i.menu_item_ids.includes(m.id),onCheckedChange:()=>S({...i,menu_item_ids:g(i.menu_item_ids,m.id)})}),m.image_url&&e.jsx("img",{src:m.image_url,alt:m.name,className:"h-8 w-8 rounded object-cover"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:m.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:As(m.price)})]})]},m.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Imagen externa (opcional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Si subes una imagen aquí, sustituirá a la imagen del primer plato en la notificación."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("strong",{children:"Recomendado:"})," ratio horizontal 2:1 (ej. 1024 × 512 px), peso menor a 500 KB. Formatos: WebP, JPG o PNG."]}),i.custom_image_url?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:i.custom_image_url,alt:"Imagen personalizada",className:"h-24 w-24 rounded object-cover border"}),e.jsx("button",{type:"button",onClick:()=>S(m=>({...m,custom_image_url:null})),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 shadow","aria-label":"Quitar imagen",children:e.jsx(hs,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("label",{className:"inline-flex items-center gap-2 px-3 py-2 rounded border border-dashed text-sm cursor-pointer hover:bg-accent",children:[G?e.jsx(pe,{className:"h-4 w-4 animate-spin"}):e.jsx(Ea,{className:"h-4 w-4"}),e.jsx("span",{children:G?"Subiendo...":"Subir imagen"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:G,onChange:m=>{const k=m.target.files?.[0];k&&Y(k),m.target.value=""}})]}),e.jsx(X,{placeholder:"o pega una URL https://...",onBlur:m=>{const k=m.target.value.trim();k&&S(E=>({...E,custom_image_url:k}))},className:"flex-1"})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx(ne,{htmlFor:"active-switch",className:"text-sm",children:"Regla activa"}),e.jsx(ns,{id:"active-switch",checked:i.is_active,onCheckedChange:m=>S({...i,is_active:m})})]})]}),e.jsxs(Et,{children:[e.jsx(D,{variant:"outline",onClick:()=>N(!1),disabled:I,children:"Cancelar"}),e.jsxs(D,{onClick:j,disabled:I,children:[I&&e.jsx(pe,{className:"h-4 w-4 animate-spin mr-2"}),y?"Guardar":"Crear"]})]})]})})]})})}function ti({restaurantId:s,restaurantName:t,restaurantSlug:a,restaurantLogo:r}){const[n,l]=f.useState(0),[h,u]=f.useState(!0),[C,N]=f.useState(!1),[y,v]=f.useState(""),[i,S]=f.useState(""),[I,d]=f.useState(null),[w,b]=f.useState([]),[c,g]=f.useState(!0),[j,T]=f.useState(),[G,te]=f.useState(!0),[Y,J]=f.useState(null),[ge,oe]=f.useState(!0),[m,k]=f.useState(!1),[E,P]=f.useState(null);f.useEffect(()=>{(async()=>{try{const{data:W,error:ee}=await L.rpc("can_restaurant_send_notification",{p_restaurant_id:s});if(ee)throw ee;J(W)}catch(W){console.error("Error fetching rate limit info:",W)}finally{oe(!1)}})()},[s]),f.useEffect(()=>{(async()=>{try{const{data:W,error:ee}=await L.rpc("get_restaurant_followers_count",{p_restaurant_id:s});if(ee)throw ee;l(W||0)}catch(W){console.error("Error fetching followers count:",W)}finally{u(!1)}})()},[s]),f.useEffect(()=>{(async()=>{try{const{data:W,error:ee}=await L.from("push_notifications_log").select("id, title, body, sent_at, success_count, failure_count, recipients_count").eq("restaurant_id",s).order("sent_at",{ascending:!1}).limit(10);if(ee)throw ee;b(W||[])}catch(W){console.error("Error fetching notification logs:",W)}finally{g(!1)}})()},[s]);const O=(F,W)=>{v(F),S(W);const ee=tr.find(ke=>ke.title===F);T(ee?.id)},Z=async()=>
2{if(!y.trim()||!i.trim()){ce.error("Por favor completa el título y el mensaje");return}if(n===0){ce.error("No hay seguidores para enviar notificaciones");return}if(Y&&!Y.can_send){ce.error("Has alcanzado el límite diario de notificaciones");return}N(!0);try{const{data:F,error:W}=await L.functions.invoke("send-push-notification",{body:{restaurantId:s,title:y.trim(),body:i.trim(),url:`/restaurant/${a}`,type:"promotion",imageUrl:I}});if(W)throw W;if(F?.success){ce.success(`Notificación enviada a ${F.sent} seguidores`),v(""),S(""),d(null),T(void 0);const{data:ee}=await L.from("push_notifications_log").select("id, title, body, sent_at, success_count, failure_count, recipients_count").eq("restaurant_id",s).order("sent_at",{ascending:!1}).limit(10);ee&&b(ee);const{data:ke}=await L.rpc("can_restaurant_send_notification",{p_restaurant_id:s});ke&&J(ke)}else throw new Error(F?.error||"Error desconocido")}catch(F){console.error("Error sending notification:",F),ce.error("Error al enviar la notificación")}finally{N(!1)}},p=async()=>{if(!("serviceWorker"in navigator))return"no disponible";try{const W=(await navigator.serviceWorker.ready).active;return W?await new Promise(ee=>{const ke=new MessageChannel,Ue=setTimeout(()=>ee("versión antigua (sin respuesta)"),2500);ke.port1.onmessage=Pe=>{clearTimeout(Ue),ee(Pe.data?.version||"desconocida")},W.postMessage({type:"GET_SW_VERSION"},[ke.port2])}):"no activo"}catch{return"no disponible"}},M=async()=>{k(!0),P(null);const F=[];try{const W=typeof Notification<"u"?Notification.permission:"default";F.push(`Permiso en este navegador: ${W==="granted"?"concedido":W}`);const ee=await p();F.push(`Componente de avisos activo: ${ee}`);const ke=await Qr();if(!ke){F.push("Este dispositivo no está suscrito. Activa las notificaciones desde el menú público y vuelve a probar."),P(F);return}const{data:Ue,error:Pe}=await L.functions.invoke("send-push-notification",{body:{restaurantId:s,subscriptionId:ke,type:"test",title:"🔔 Prueba de notificación",body:"Si ves este aviso, las notificaciones funcionan en este dispositivo.",url:`/restaurant/${a}`}}
2);if(Pe)throw Pe;F.push(`Aceptado por el servicio de envío: ${Ue?.sent>0?"sí":"no"}`);const ze=Ue?.notification_log_id;if(!ze||!Ue?.sent){F.push("El envío no salió; revisa que la suscripción de este dispositivo siga activa."),P(F);return}await new Promise(_e=>setTimeout(_e,5e3));const{data:B}=await L.from("push_notification_events").select("event_type").eq("notification_log_id",ze),ae=(B||[]).map(_e=>_e.event_type);ae.includes("delivered")?F.push("El navegador confirmó que mostró el aviso. Si no lo viste, revísalo en el centro de notificaciones del sistema."):ae.includes("show_failed")?F.push("El navegador recibió el aviso pero no pudo mostrarlo."):F.push("El navegador nunca recibió el aviso. Suele deberse a una versión antigua del componente: cierra y vuelve a abrir el navegador y repite la prueba."),P(F)}catch(W){console.error("Error running notification test:",W),F.push("No se pudo completar la prueba."),P(F),ce.error("Error al ejecutar la prueba")}finally{k(!1)}},U=F=>new Date(F).toLocaleString("es-MX",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{className:"bg-gradient-to-br from-primary/5 to-accent/5 border-primary/20",children:[e.jsxs(K,{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-5 w-5 text-primary"}),"Seguidores"]}),e.jsxs(ve,{children:["Usuarios suscritos a las notificaciones de ",t]})]}),e.jsx(q,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[h?e.jsx(pe,{className:"h-6 w-6 animate-spin text-muted-foreground"}):e.jsx("div",{className:"text-4xl font-bold text-primary",children:n}),e.jsx("span",{className:"text-muted-foreground",children:n===1?"seguidor activo":"seguidores activos"})]})})]}),e.jsx(ai,{restaurantId:s,disabled:n===0}),e.jsxs(_s,{defaultValue:"send",className:"w-full",children:[e.jsxs(ws,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ee,{value:"send",className:"gap-2",children:[e.jsx(es,{className:"h-4 w-4"}),"Enviar"]}),e.jsxs(Ee,{value:"analytics",className:"gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Métricas"]})]}),e.jsxs(Me,{value:"send",className:"space-y-6 mt-6",children:[e.jsxs($,{children:[e.jsxs(K,{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"h-5 w-5"}),"Enviar Notificación"]}),e.jsx(ve,{children:"Envía una notificación push a todos tus seguidores"})]}),e.jsxs(q,{className:"space-y-6",children:[e.jsx(Zn,{onSelectTemplate:O,selectedTemplateId:j}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"notification-title",children:"Título"}),e.jsx(X,{id:"notification-title",placeholder:"Ej: ¡Nueva promoción disponible!",value:y,onChange:F=>{v(F.target.value),T(void 0)},maxLength:50,disabled:C}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[y.length,"/50"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"notification-message",children:"Mensaje"}),e.jsx(Ds,{id:"notification-message",placeholder:"Ej: Hoy 2x1 en todos nuestros platillos principales. ¡No te lo pierdas!",value:i,onChange:F=>{S(F.target.value),T(void 0)},maxLength:200,rows:4,disabled:C}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[i.length,"/200"]})]}),e.jsx(ei,{restaurantId:s,selectedImageUrl:I,onSelectImage:d}),!ge&&Y&&e.jsxs("div",{className:`p-3 rounded-lg border ${Y.can_send?"bg-primary/5 border-primary/20":"bg-destructive/5 border-destructive/20"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[Y.can_send?e.jsx(Es,{className:"h-4 w-4 text-primary"}):e.jsx(Xa,{className:"h-4 w-4 text-destructive"}),"Envíos restantes hoy"]}),e.jsxs(re,{variant:Y.can_send?"secondary":"destructive",children:[Y.remaining," / ",Y.daily_limit]})]}),e.jsx(aa,{value:Y.remaining/Y.daily_limit*100,className:"h-2"}),!Y.can_send&&e.jsx("p",{className:"text-xs text-destructive mt-2",children:"Has alcanzado el límite diario. Podrás enviar más mañana."})]}),n===0&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg",children:[e.jsx(ba,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Aún no tienes seguidores. Los clientes pueden seguirte desde tu menú."})]}),e.jsx(D,{onClick:Z,disabled:C||n===0||!y.trim()||!i.trim()||Y&&!Y.can_send,className:"w-full gap-2",size:"lg",children:C?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 animate-spin"}),"Enviando..."]}):Y&&!Y.can_send?e.jsxs(e.Fragment,{children:[e.jsx(Xa,{className:"h-4 w-4"}),"Límite diario alcanzado"]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4"}),"Enviar a ",n," ",n===1?"seguidor":"seguidores"]})})]}),e.jsxs(Cr,{open:G,onOpenChange:te,children:[e.jsx(kr,{asChild:!0,children:e.jsxs(D,{variant:"ghost",size:"sm",className:"w-full justify-between mb-2 md:hidden",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(zt,{className:"h-4 w-4"}),"Vista previa"]}),e.jsx(re,{variant:"outline",children:G?"Ocultar":"Mostrar"})]})}),e.jsx(Er,{className:"md:block",children:e.jsx(Kn,{title:y,body:i,restaurantName:t,logoUrl:r,imageUrl:I})})]})]})]})]}),e.jsxs($,{children:[e.jsxs(K,{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(at,{className:"h-5 w-5"}),"Probar notificación en este dispositivo"]}),e.jsx(ve,{children:"Envía un aviso solo a este dispositivo y verifica si el navegador lo muestra"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsx(D,{variant:"outline",onClick:M,disabled:m,className:"gap-2",children:m?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 animate-spin"}),"Probando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(at,{className:"h-4 w-4"}),"Ejecutar prueba"]})}),E&&e.jsx("ul",{className:"space-y-1 rounded-lg border bg-muted/40 p-3 text-sm",children:E.map((F,W)=>e.jsxs("li",{className:"text-muted-foreground",children:["• ",F]},W))})]})]}),e.jsxs($,{children:[e.jsxs(K,{children:[e.jsx(Q,{children:"Historial de Notificaciones"}),e.jsx(ve,{children:"Últimas 10 notificaciones enviadas"})]}),e.jsx(q,{children:c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(pe,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Es,{className:"h-12 w-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{children:"No has enviado notificaciones aún"})]}):e.jsx("div",{className:"space-y-4",children:w.map(F=>e.jsxs("div",{className:"p-4 border rounded-lg space-y-2 hover:bg-accent/50 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-medium",children:F.title}),e.jsxs("div",{className:"flex items-center gap-1",children:[F.success_count>0&&e.jsxs(re,{variant:"outline",className:"gap-1 text-green-600 border-green-600",children:[e.jsx(en,{className:"h-3 w-3"}),F.success_count]}),F.failure_count>0&&e.jsxs(re,{variant:"outline",className:"gap-1 text-destructive border-destructive",children:[e.jsx(ba,{className:"h-3 w-3"}),F.failure_count]})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:F.body}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U(F.sent_at)})]},F.id))})})]})]}),e.jsx(Me,{value:"analytics",className:"mt-6",children:e.jsx(Jn,{restaurantId:s})})]})]})}const ri=()=>{const{currentRestaurant:s}=ls(),{loading:t}=Rt(s?.id),{toast:a}=Ie(),[r,n]=f.useState(!1),[l,h]=f.useState([]),[u,C]=f.useState(!1);f.useEffect(()=>{s&&(N(),y())},[s]);const N=async()=>
2{if(s)try{const{data:S,error:I}=await L.from("menu_items").select("*").eq("restaurant_id",s.id);if(I)throw I;h(S||[])}catch(S){console.error("Error fetching menu items:",S)}},y=async()=>{if(s)try{const{data:S,error:I}=await L.from("restaurants").select("promotion_popup_enabled").eq("id",s.id).single();if(I)throw I;n(S?.promotion_popup_enabled||!1)}catch(S){console.error("Error fetching restaurant settings:",S)}},v=async S=>{if(s){if(S&&l.filter(d=>d.is_promotion).length===0){a({variant:"destructive",title:"No se puede activar",description:"Necesitas tener al menos un elemento en la categoría 'Promociones' para activar el pop-up."});return}C(!0);try{const{error:I}=await L.from("restaurants").update({promotion_popup_enabled:S}).eq("id",s.id);if(I)throw I;n(S),a({title:"Pop-up desactivado",description:"El pop-up de promociones está desactivado."})}catch(I){console.error("Error updating promotion popup setting:",I),a({variant:"destructive",title:"Error",description:"No se pudo actualizar la configuración."})}finally{C(!1)}}};if(!s)return e.jsx($,{className:"border-0 shadow-elegant",children:e.jsx(q,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"Selecciona un restaurante para acceder a las funciones extras."})})});if(t)return e.jsx($,{className:"border-0 shadow-elegant",children:e.jsxs(q,{className:"p-8 text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Cargando permisos..."})]})});const i=l.filter(S=>S.is_promotion);return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex justify-between items-start",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(bs,{className:"h-6 w-6 text-primary"}),"Funciones Extras"]}),e.jsx("p",{className:"text-muted-foreground",children:"Funcionalidades avanzadas para potenciar tu restaurante"})]})}),e.jsxs(_s,{defaultValue:"promotions",className:"w-full",children:[e.jsxs(ws,{className:"grid w-full grid-cols-3 h-auto p-1.5 bg-secondary/50 backdrop-blur-sm rounded-xl border border-border/50 shadow-sm",children:[e.jsxs(Ee,{value:"promotions",className:"flex items-center gap-2 py-3 px-4 rounded-lg data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-accent data-[state=active]:text-primary-foreground data-[state=active]:shadow-md transition-all duration-200 hover:bg-background/60",children:[e.jsx(bs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pop-up"})]}),e.jsxs(Ee,{value:"notifications",className:"flex items-center gap-2 py-3 px-4 rounded-lg data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-accent data-[state=active]:text-primary-foreground data-[state=active]:shadow-md transition-all duration-200 hover:bg-background/60",children:[e.jsx(Es,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Notificaciones"})]}),e.jsxs(Ee,{value:"analytics",className:"flex items-center gap-2 py-3 px-4 rounded-lg data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-accent data-[state=active]:text-primary-foreground data-[state=active]:shadow-md transition-all duration-200 hover:bg-background/60",children:[e.jsx(Ws,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Análisis"})]})]}),e.jsx(Me,{value:"promotions",className:"space-y-4",children:e.jsxs($,{className:"border-0 shadow-elegant",children:[e.jsx(K,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(bs,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(Q,{children:"Pop-up de Promociones"}),e.jsx(ve,{children:"Muestra automáticamente tus promociones especiales a los visitantes"})]})]}),e.jsxs(re,{variant:"default",className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(rs,{className:"h-3 w-3 mr-1"}),"Incluido"]})]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between p-4 border rounded-lg bg-background/50",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{id:"promotion-popup",checked:r,onCheckedChange:v,disabled:i.length===0||u}),e.jsx("label",{htmlFor:"promotion-popup",className:"font-medium",children:"Activar Pop-up de Promociones"}),u&&e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-primary ml-2"})]}),i.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:'Necesitas agregar elementos en la categoría "Promociones" para activar esta función'})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{className:"p-3 border rounded-lg bg-background/30",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Promociones dis
2ponibles"}),e.jsx("p",{className:"text-xl font-bold text-primary",children:i.length})]}),e.jsxs("div",{className:"p-3 border rounded-lg bg-background/30",children:[e.jsx("p",{className:"font-medium text-foreground",children:"Estado"}),e.jsx("p",{className:`text-xl font-bold ${r?"text-green-600":"text-gray-500"}`,children:r?"Activo":"Inactivo"})]})]}),i.length>0&&e.jsxs("div",{className:"border rounded-lg p-4 bg-background/30",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Promociones que se mostrarán:"}),e.jsx("div",{className:"space-y-2 max-h-32 overflow-y-auto",children:i.map(S=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{children:S.name}),e.jsx("span",{className:"text-primary font-medium",children:S.price})]},S.id))})]})]})]})}),e.jsx(Me,{value:"notifications",className:"space-y-4",children:e.jsx(ti,{restaurantId:s.id,restaurantName:s.name,restaurantSlug:s.slug,restaurantLogo:s.logo_url})}),e.jsx(Me,{value:"analytics",className:"space-y-4",children:e.jsxs($,{className:"border-0 shadow-elegant",children:[e.jsx(K,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ws,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(Q,{children:"Análisis de Menú"}),e.jsx(ve,{children:"Visualiza estadísticas detalladas sobre la interacción con tu menú"})]})]}),e.jsxs(re,{variant:"default",className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(rs,{className:"h-3 w-3 mr-1"}),"Incluido"]})]})}),e.jsx(q,{children:e.jsx(Yn,{restaurantId:s.id})})]})})]})]})},ni="/assets/binance-qr-COQWVKYv.jpg",yt={basic:"price_1SxSnoE4HjSSqfnSRieC1rsk",premium:"price_1SxSnoE4HjSSqfnSRieC1rsk"},ii={1:{percentage:0,label:null,badgeColor:""},3:{percentage:10,label:"10% de descuento",badgeColor:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"},6:{percentage:15,label:"15% de descuento",badgeColor:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"},12:{percentage:20,label:"20% de descuento",badgeColor:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400"}},li=({children:s,monthlyCost:t=0,preSelectedPlan:a,onOpenChange:r})=>{const{toast:n}
2=Ie(),{currentRestaurant:l}=ls(),[h,u]=f.useState(!1),[C,N]=f.useState(!1),[y,v]=f.useState(!1),[i,S]=f.useState(1),[I,d]=f.useState("stripe"),w=f.useMemo(()=>"zelle",[]),[b,c]=f.useState(w),[g,j]=f.useState("monthly"),[T,G]=f.useState(!1),[te,Y]=f.useState(49.99),[J,ge]=f.useState(!1),[oe,m]=f.useState(null),[k,E]=f.useState({amount:"",paymentReference:"",paymentDate:be(new Date,"yyyy-MM-dd"),message:"",contactPhone:"",contactEmail:""}),P="USD",O="USD";f.useEffect(()=>{c(w)},[w]),f.useEffect(()=>{h&&(async()=>{try{const{data:ae}=await L.from("promotion_settings").select("lifetime_promo_enabled, lifetime_promo_price").limit(1).single();if(G(ae?.lifetime_promo_enabled??!1),Y(ae?.lifetime_promo_price??49.99),l?.id){const{data:_e}=await L.from("lifetime_subscriptions").select("status").eq("restaurant_id",l.id).single();m(_e?.status??null)}}catch(ae){console.error("Error fetching lifetime promo:",ae)}})()},[h,l?.id]);const Z=a?.price_monthly??t,p=ii[i]||{percentage:0,label:null},M=Z*i,U=M*(p.percentage/100),W=(M-U).toFixed(2),ee=B=>{u(B),r?.(B)},ke=async()=>{if(l){v(!0);try{let B;a?.stripe_price_id_monthly?B=a.stripe_price_id_monthly:(console.warn("Using legacy fallback prices - preSelectedPlan should have stripe_price_id_monthly"),B=Z>=15?yt.premium:yt.basic);const{data:ae,error:_e}=await L.functions.invoke("create-checkout-session",{body:{restaurantId:l.id,priceId:B,months:i}});if(_e)throw _e;if(ae?.url)window.open(ae.url,"_blank"),ee(!1),n({title:"Redirigiendo a Stripe",description:`Procesando suscripción ${a?.name||"seleccionada"}.`});else throw new Error("No se recibió URL de checkout")}catch(B){console.error("Error creating Stripe checkout session:",B);const ae=B instanceof Error?B.message:"No se pudo iniciar el pago con Stripe.";n({variant:"destructive",title:"Error",description:ae})}finally{v(!1)}}},Ue=async()=>{if(l){ge(!0);try{const{data:B,error:ae}=await L.functions.invoke("create-lifetime-checkout",{body:{restaurantId:l.id}});if(ae)throw ae;if(B?.url)window.open(B.url,"_blank"),ee(!1);else throw new Error("No se recibió URL de pago")}catch(B){const ae=B instanceof Error?B.message:"Error al crear sesión de pago";n({variant:"destructive",title:"Error",description:ae})}finally{ge(!1)}}},Pe=async B=>{if(B.preventDefault(),!!l){N(!0);try{const ae=k.amount||W,{error:_e}=await L.from("payment_notifications").insert([{restaurant_id:l.id,notification_type:"payment_made",message:k.message||`Pago adelantado por ${i} mes${i>1?"es":""} - $${ae} USD`,payment_reference:k.paymentReference,amount:parseFloat(ae),currency:P,payment_method:b,payment_date:k.paymentDate?new Date(k.paymentDate).toISOString():null,contact_info:{phone:k.contactPhone,email:k.contactEmail,months_paid:i},status:"pending"}]);if(_e)throw _e;n({title:"Notificación enviada",description:`Tu notificación de pago para el plan ${a?.name||"seleccionado"} ha sido enviada al administrador.`}),ee(!1),S(1),c(w),E({amount:"",paymentReference:"",paymentDate:be(new Date,"yyyy-MM-dd"),message:"",contactPhone:"",contactEmail:""})}catch(ae){console.error("Error sending payment notification:",ae),n({variant:"destructive",title:"Error",description:"No se pudo enviar la notificación. Intenta de nuevo."})}finally{N(!1)}}},ze=(B,ae)=>{E(_e=>({..._e,[B]:ae}))};return e.jsxs(ps,{open:h,onOpenChange:ee,children:[e.jsx(Fs,{asChild:!0,children:s}),e.jsx(fs,{className:"sm:max-w-[650px] max-h-[90vh] overflow-y-auto",children:e.jsxs("div",{className:"overflow-y-auto max-h-[calc(90vh-8rem)] pr-2",children:[e.jsxs(gs,{children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-5 w-5 text-primary"}),"Pagar Suscripción"]}),e.jsx(Rs,{children:"Elige tu método de pago preferido para tu suscripción de Live Menu."})]}),T&&oe!=="active"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx(ne,{children:"Tipo de Plan"}),e.jsxs(Yr,{value:g,onValueChange:B=>j(B),className:"grid grid-cols-2 gap-3",children:[e.jsxs(ne,{htmlFor:"plan-monthly",className:`flex flex-col items-center gap-2 rounded-lg border-2 p-4 cursor-pointer transition-all ${g==="monthly"?"border-primary bg-primary/5":"border-muted hover:border-primary/40"}`,children:[e.jsx(Ha,{value:"monthly",id:"plan-monthly",className:"sr-only"}),e.jsx(De,{className:"h-6 w-6 text-primary"}),e.jsx("span",{className:"font-semibold text-sm",children:"Suscripción Mensual"}),e.jsxs("span",{className:"text-xs text-muted-foreground text-center",children:["$",Z.toFixed(2),"/mes"]})]}),e.jsxs(ne,{htmlFor:"plan-lifetime",className:`flex flex-col items-center gap-2 rounded-lg border-2 p-4 cursor-pointer transition-all relative overflow-hidden ${g==="lifetime"?"border-amber-500 bg-amber-50/50 dark:bg-amber-950/20":"border-muted hover:border-amber-400"}`,children:[e.jsx(Ha,{value:"lifetime",id:"plan-lifetime",className:"sr-only"}),e.jsx("div",{className:"absolute top-0 right-0 bg-amber-500 text-white text-[10px] px-2 py-0.5 rounded-bl-lg font-bold",children:"PROMO"}),e.jsx(rs,{className:"h-6 w-6 text-amber-500"}),e.jsx("span",{className:"font-semibold text-sm",children:"Plan Fundador"}),e.jsxs("span",{className:"text-xs text-muted-foreground text-center",children:["$",te," USD único"]})]})]})]}),g==="lifetime"&&T&&oe!=="active"?e.jsxs("div",{className:"space-y-4 mt
2-4",children:[e.jsx($,{className:"border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-950/20",children:e.jsxs(q,{className:"pt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(rs,{className:"h-5 w-5 text-amber-500"}),e.jsx("span",{className:"font-bold text-lg",children:"Plan Fundador"}),e.jsx(ka,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Pago único de ",e.jsxs("span",{className:"font-bold text-amber-600",children:["$",te," USD"]})," — acceso Premium permanente, sin mensualidades."]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsx("li",{children:"✓ Acceso Premium de por vida"}),e.jsx("li",{children:"✓ Sin pagos recurrentes"}),e.jsx("li",{children:"✓ Todas las funciones incluidas"}),e.jsx("li",{children:"✓ Para los primeros 500 restaurantes"})]}),e.jsxs("div",{className:"flex justify-between text-base font-bold border-t pt-2",children:[e.jsx("span",{children:"Total a pagar:"}),e.jsxs("span",{className:"text-amber-600",children:["$",te," USD"]})]})]})}),e.jsxs(_s,{value:I,onValueChange:B=>d(B),className:"mt-2",children:[e.jsxs(ws,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ee,{value:"stripe",className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),"Stripe (Automático)"]}),e.jsxs(Ee,{value:"manual",className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-4 w-4"}),"Pago Manual"]})]}),e.jsxs(Me,{value:"stripe",className:"space-y-4 mt-4",children:[e.jsx(D,{onClick:Ue,disabled:J,className:"w-full bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600",size:"lg",children:J?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 mr-2 animate-spin"}),"Procesando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2"}),"Pagar $",te," USD con Stripe"]})}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Serás redirigido a la página segura de Stripe"})]}),e.jsxs(Me,{value:"manual",className:"mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Realiza tu pago por Zelle o Binance y notifica al administrador para activar tu Plan Fundador."}),e.jsx(D,{variant:"outline",className:"w-full",onClick:async()=>{if(l){N(!0);try{const{data:B}=await L.from("lifetime_subscriptions").select("id, status").eq("restaurant_id",l.id).maybeSingle();if(B&&B.status==="pending_approval"){n({title:"Ya enviada",description:"Ya tienes una solicitud de Plan Fundador pendiente de aprobación."}),N(!1);return}if(!B){const{error:_e}=await L.from("lifetime_subscriptions").insert({restaurant_id:l.id,payment_method:"manual",status:"pending_approval"});if(_e)throw _e}const{error:ae}=await L.from("payment_notifications").insert({restaurant_id:l.id,notification_type:"payment_made",message:`Pago manual del Plan Fundador ($${te} USD) - Pendiente de aprobación`,amount:te,currency:"USD",payment_method:"manual",status:"pending"});if(ae)throw ae;n({title:"📩 Solicitud Enviada",description:"Tu solicitud de Plan Fundador ha sido enviada. Serás notificado cuando sea aprobada."}),ee(!1)}catch(B){const ae=B instanceof Error?B.message:"Error al enviar solicitud";n({variant:"destructive",title:"Error",description:ae})}finally{N(!1)}}},disabled:C,children:C?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 mr-2 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2"}),"Notificar Pago Manual"]})})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"months",children:"Meses a pagar"}),e.jsxs(Re,{value:i.toString(),onValueChange:B=>S(parseInt(B)),children:[e.jsx(Te,{id:"months",children:e.jsx(Le,{})}),e.jsxs(Ve,{children:[e.jsx(le,{value:"1",children:"1 mes"}),e.jsx(le,{value:"3",children:e.jsxs("span",{className:"flex items-center gap-2",children:["3 meses",e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",children:"-10%"})]})}),e.jsx(le,{value:"6",children:e.jsxs("span",{className:"flex items-center gap-2",children:["6 meses",e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",children:"-15%"})]})}),e.jsx(le,{value:"12",children:e.jsxs("span",{className:"flex items-center gap-2",children:["12 meses",e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",children:"-20%"})]})})]})]}),p.label&&e.jsxs("p",{className:"text-xs text-green-600 dark:text-green-400 font-medium",children:["🎉 ¡",p.label," aplicado!"]})]}),Z>0&&e.jsx($,{className:"border-green-200 bg-green-50/50 dark:border-green-800 dark:bg-green-950/20",children:e.jsxs(q,{className:"pt-4 space-y-2",children:[a?.name&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Plan seleccionado:"}),e.jsx("span",{className:"font-medium",children:a.name})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Costo mensual:"}),e.jsxs("span",{className:"font-medium",children:["$",Z.toFixed(2)," USD"]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Meses seleccionados:"}),e.jsx("span",{className:"font-medium",children:i})]}),p.percentage>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subtotal:"}),e.jsxs("span",{className:"font-medium line-through text-muted-foreground",children:["$",M.toFixed(2)," USD"]})]}),e.jsxs("div",{className:"flex justify-between text-sm text-green-600 dark:text-green-400",children:[e.jsxs("span",{children:["Descuento (",p.percentage,"%):"]}),e.jsxs("span",{className:"font-medium",children:["-$",U.toFixed(2)," USD"]})]})]}),e.jsxs("div",{className:"flex justify-between text-base font-bold border-t pt-2",children:[e.jsx("span",{children:"Total a pagar:"}),e.jsxs("span",{className:"text-primary",children:["$",W," USD"]})]}),p.percentage>0&&e.jsx("div",{className:"text-center pt-1",children:e.jsxs("span",{className:"text-xs text-green-600 dark:text-green-400 font-medium bg-green-100 dark:bg-green-900/30 px-2 py-1 rounded-full",children:["🎁 ¡Ahorras $",U.toFixed(2)," USD!"]})})]})})]}
2),e.jsxs(_s,{value:I,onValueChange:B=>d(B),className:"mt-6",children:[e.jsxs(ws,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ee,{value:"stripe",className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),"Stripe (Automático)"]}),e.jsxs(Ee,{value:"manual",className:"flex items-center gap-2",children:[e.jsx(es,{className:"h-4 w-4"}),"Pago Manual"]})]}),e.jsx(Me,{value:"stripe",className:"space-y-4 mt-4",children:e.jsxs($,{className:"border-primary/20 bg-primary/5",children:[e.jsx(K,{className:"pb-3",children:e.jsxs(Q,{className:"text-sm flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4 text-primary"}),"Pago con Tarjeta de Crédito/Débito"]})}),e.jsxs(q,{className:"pt-0 space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Paga de forma segura con Stripe. Aceptamos Visa, Mastercard, American Express y más."}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsx("li",{children:"✓ Pago procesado instantáneamente"}),e.jsx("li",{children:"✓ Tu suscripción se activa automáticamente"}),e.jsx("li",{children:"✓ Renovación automática cada mes"}),e.jsx("li",{children:"✓ Cancela cuando quieras desde tu portal de cliente"})]}),e.jsx(D,{onClick:ke,disabled:y||Z<=0,className:"w-full mt-4",size:"lg",children:y?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 mr-2 animate-spin"}),"Procesando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2"}),"Pagar $",W," USD con Stripe"]})}),Z<=0?e.jsx("p",{className:"text-xs text-center text-destructive",children:"Selecciona un plan válido antes de proceder con el pago"}):e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Serás redirigido a la página segura de Stripe"})]})]})}),e.jsx(Me,{value:"manual",className:"mt-4",children:e.jsxs("form",{onSubmit:Pe,className:"space-y-6",children:[e.jsxs($,{className:"border-primary/20 bg-primary/5",children:[e.jsx(K,{className:"pb-3",children:e.jsx(Q,{className:"text-sm",children:"💡 Pago Manual"})}),e.jsxs(q,{className:"pt-0 text-sm space-y-2",children:[e.jsx("p",{children:"Realiza tu pago por transferencia y notifica al administrador."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Una vez enviada la notificación, el administrador revisará tu pago. Este proceso puede tomar hasta 24 horas hábiles."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Método de pago utilizado"}),e.jsxs(Re,{value:b,onValueChange:B=>c(B),children:[e.jsx(Te,{children:e.jsx(Le,{})}),e.jsxs(Ve,{children:[e.jsx(le,{value:"zelle",children:"Zelle (USD)"}),e.jsx(le,{value:"binance",children:"Binance USDT (USD)"})]})]})]}),e.jsxs($,{className:"border-blue-200 bg-blue-50/50 dark:border-blue-800 dark:bg-blue-950/20",children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Q,{className:"text-sm flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),"Datos de Pago"]}),e.jsx(ve,{children:"Información para realizar tu pago"})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("div",{className:"p-3 rounded-lg border bg-card",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(ms,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-semibold text-sm mb-1",children:"Zelle"}),e.jsx("p",{className:"text-sm text-muted-foreground break-all",children:"[email protected]"})]})]})}),e.jsx("div",{className:"p-3 rounded-lg border bg-card",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(De,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-semibold text-sm mb-1",children:"Binance (USDT - ERC20)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Escanea el código QR para realizar el pago"})]})]}),e.jsx("div",{className:"flex justify-center p-2 bg-white rounded-lg",children:e.jsx("img",{src:ni,alt:"Binance QR Code",className:"w-48 h-48 object-contain"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Red: Ethereum (ERC20) | No envíes NFT a esta dirección"})]})})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"amount",children:["Monto pagado (",O,")"]}),e.jsx(X,{id:"amount",type:"number",step:"0.01",placeholder:W,value:k.amount,onChange:B=>ze("amount",B.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t>0?`Monto sugerido: $${W}`:"Ingresa el monto que pagaste"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"paymentDate",children:"Fecha de pago"}),e.jsx(X,{id:"paymentDate",type:"date",value:k.paymentDate,onChange:B=>ze("paymentDate",B.target.value),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"paymentReference",children:"Referencia de pago (opcional)"}),e.jsx(X,{id:"paymentReference",placeholder:"Número de transacción, referencia bancaria, etc.",value:k.paymentReference,onChange:B=>ze("paymentReference",B.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"message",children:"Mensaje adicional (opcional)"}),e.jsx(Ds,{id:"message",placeholder:"Proporciona detalles adicionales sobre el pago...",value:k.message,onChange:B=>ze("message",B.target.value),rows:3})]}),e.jsxs($,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Q,{className:"text-sm flex items-center gap-2",children:[e.jsx(Ya,{className:"h-4 w-4"}),"Información de contacto"]}),e.jsx(ve,{children:"Para que el administrador pueda contactarte si necesita verificar el pago"})]}),e.jsx(q,{className:"space-y-4",children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"contactPhone",className:"flex items-center gap-2",children:[e.jsx(Ya,{className:"h-3 w-3"}),"Teléfono"]}),e.jsx(X,{id:"contactPhone",type:"tel",placeholder:"+52 555 123 4567",value:k.contactPhone,onChange:B=>ze("contactPhone",B.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"contactEmail",className:"flex items-center gap-2",children:[e.jsx(ms,{className:"h-3 w-3"}),"Email"]}),e.jsx(X,{id:"contactEmail",type:"email",placeholder:"[email protected]",value:k.contactEmail,onChange:B=>ze("contactEmail",B.target.value)})]})]})})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(D,{type:"button",variant:"outline",onClick:()=>u(!1),className:"flex-1",children:"Cancelar"}),e.jsx(D,{type:"submit",disabled:C,className:"flex-1",children:C?"Enviando...":e.jsxs(e.Fragment,{children:[e.jsx(es,{className:"h-4 w-4 mr-2"}),"Notificar Pago"]})})]})]})})]})]})]})})]})},oi=({restaurantId:s})=>{const[t,a]=f.useState([]),[r,n]=f.useState(!0),[l,h]=f.useState(null),{toast:u}=Ie();f.useEffect(()=>{s&&C()},[s]);const C=async()=>{try{n(!0);const{data:i,error:S}=await L.from("payment_notifications").select("*").eq("restaurant_id",s).order("created_at",{ascending:!1});if(S)throw S;a(i||[])}catch(i){console.error("Error fetching payment history:",i)}finally{n(!1)}},N=i=>{switch(i){case"approved":return e.jsxs(re,{variant:"default",className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ts,{className:"h-3 w-3 mr-1"}),"Aprobado"]});case"rejected":return e.jsxs(re,{variant:"destructive",children:[e.jsx(Na,{className:"h-3 w-3 mr-1"}),"Rechazado"]});
2case"pending":return e.jsxs(re,{variant:"secondary",className:"bg-yellow-100 text-yellow-800 border-yellow-200",children:[e.jsx(We,{className:"h-3 w-3 mr-1"}),"Pendiente"]});default:return e.jsx(re,{variant:"outline",children:i})}},y=()=>t.filter(i=>i.status==="approved").reduce((i,S)=>i+S.amount,0),v=async i=>{try{h(i);const{error:S}=await L.from("payment_notifications").delete().eq("id",i);if(S)throw S;u({title:"Notificación eliminada",description:"La notificación de pago ha sido eliminada exitosamente."}),await C()}catch(S){console.error("Error deleting payment:",S),u({variant:"destructive",title:"Error",description:"No se pudo eliminar la notificación. Intenta de nuevo."})}finally{h(null)}};return r?e.jsxs($,{children:[e.jsx(K,{children:e.jsx(Ge,{className:"h-6 w-48"})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((i,S)=>e.jsx(Ge,{className:"h-20 w-full"},S))})})]}):e.jsxs($,{children:[e.jsxs(K,{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(et,{className:"h-5 w-5"}),"Historial de Pagos"]}),e.jsx(ve,{children:"Registro de todos los pagos notificados"})]}),e.jsx(q,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(et,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No hay pagos registrados"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-6 p-4 bg-primary/5 rounded-lg border border-primary/20",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Pagado"}),e.jsxs("p",{className:"text-lg font-bold text-primary",children:["$",y().toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pagos Aprobados"}),e.jsx("p",{className:"text-lg font-bold",children:t.filter(i=>i.status==="approved").length})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pendientes"}),e.jsx("p",{className:"text-lg font-bold text-yellow-600",children:t.filter(i=>i.status==="pending").length})]})]})}),e.jsx("div",{className:"space-y-3",children:t.map(i=>e.jsxs("div",{className:"border rounded-lg p-4 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Kr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-semibold",children:["$",i.amount," ",i.currency]}),i.contact_info?.months_paid&&i.contact_info.months_paid>1&&e.jsxs(re,{variant:"outline",className:"text-xs",children:[i.contact_info.months_paid," meses"]})]}),i.payment_reference&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Ref: ",i.payment_reference]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[N(i.status),i.status!=="pending"&&e.jsxs(zs,{children:[e.jsx(xa,{asChild:!0,children:e.jsx(D,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:l===i.id,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-destructive"})})}),e.jsxs($s,{children:[e.jsxs(Os,{children:[e.jsx(qs,{children:"¿Eliminar notificación?"}),e.jsx(Bs,{children:"Esta acción eliminará permanentemente esta notificación de pago del historial. Esta acción no se puede deshacer."})]}),e.jsxs(Hs,{children:[e.jsx(ha,{children:"Cancelar"}),e.jsx(Gs,{onClick:()=>v(i.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Eliminar"})]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(xs,{className:"h-3 w-3"}),i.payment_date&&be(new Date(i.payment_date),"dd/MM/yyyy",{locale:Ce})]}),e.jsxs("div",{children:["Enviado: ",be(new Date(i.created_at),"dd/MM/yyyy HH:mm",{locale:Ce})]})]}),i.reviewed_at&&e.jsx("div",{className:"mt-2 pt-2 border-t text-xs",children:e.jsxs("span",{className:"text-muted-foreground",children:["Revisado: ",be(new Date(i.reviewed_at),"dd/MM/yyyy HH:mm",{locale:Ce})]})}),i.notes&&e.jsx("div",{className:"mt-2 pt-2 border-t",children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("strong",{children:"Notas:"})," ",i.notes]})})]},i.id))})]})})]})},ci=[{value:"all",label:"Todos los eventos"},{value:"payment_succeeded",label:"Pagos exitosos"},{value:"payment_failed",label:"Pagos fallidos"},{value:"created",label:"Suscripción creada"},{value:"upgraded",label:"Plan mejorado"},{value:"downgraded",label:"Plan reducido"},{value:"canceled",label:"Cancelaciones"},{value:"suspended",label:"Suspensiones"},{value:"reactivated",label:"Reactivaciones"}],di=({restaurantId:s})=>{const[t,a]=f.useState([]),[r,n]=f.useState(!0),[l,h]=f.useState("all"),[u,C]=f.useState(void 0),[N,y]=f.useState(void 0);f.useEffect(()=>{s&&v()},[s]);const v=async()=>{try{n(!0);const{data:c,error:g}=await L.from("subscription_history").select("*").eq("restaurant_id",s).order("created_at",{ascending:!1});if(g)throw g;a(c||[])}catch(c){console.error("Error fetching subscription history:",c)}finally{n(!1)}},i=f.useMemo(()=>t.filter(c=>{if(l!=="all"&&c.action!==l)return!1;if(u){const g=new Date(c.created_at);if(Mr(g,Ut(u)))return!1}if(N){const g=new Date(c.created_at);if(Pr(g,Ct(N)))return!1}return!0}),[t,l,u,N]),S=()=>{h("all"),C(void 0),y(void 0)},I=l!=="all"||u||N,d=c=>{switch(c){case"payment_succeeded":return{label:"Pago Exitoso",icon:e.jsx(Ts,{className:"h-4 w-4"}),variant:"default",className:"bg-green-100 text-green-800 border-green-200"};case"payment_failed":return{label:"Pago Fallido",icon:e.jsx(Na,{className:"h-4 w-4"}),variant:"destructive",className:""};case"created":return{label:"Suscripción Creada",icon:e.jsx(De,{className:"h-4 w-4"}),variant:"secondary",className:"bg-blue-100 text-blue-800 border-blue-200"};case"upgraded":return{label:"Plan Mejorado",icon:e.jsx(Zs,{className:"h-4 w-4"}),variant:"default",className:"bg-purple-100 text-purple-800 border-purple-200"};case"downgraded":return{label:"Plan Reducido",icon:e.jsx(Ar,{className:"h-4 w-4"}),variant:"secondary",className:"bg-orange-100 text-orange-800 border-orange-200"};case"canceled":return{label:"Cancelada",icon:e.jsx(Na,{className:"h-4 w-4"}),variant:"destructive",className:""};case"suspended":return{label:"Suspendida",icon:e.jsx(as,{className:"h-4 w-4"}),variant:"destructive",className:"bg-red-100 text-red-800 border-red-200"};case"reactivated":return{label:"Reactivada",icon:e.jsx(Nt,{className:"h-4 w-4"}),variant:"default",className:"bg-green-100 text-green-800 border-green-200"};default:return{label:c,icon:e.jsx(We,{className:"h-4 w-4"}),variant:"outline",className:""}}},w=()=>i.filter(c=>c.action==="payment_succeeded"&&c.amount).reduce((c,g)=>c+(g.amount||0),0),b=()=>i.filter(c=>c.action==="payment_succeeded").length;return r?e.jsxs($,{children:[e.jsx(K,{children:e.jsx(Ge,{className:"h-6 w-56"})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((c,g)=>e.jsx(Ge,{className:"h-16 w-full"},g))})})]}):e.jsxs($,{children:[e.jsxs(K,{children:[e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(Us,{className:"h-5 w-5"}),"Historial de Suscripción"]}),e.jsx(ve,{children:"Registro de pagos y cambios en tu suscripción"})]}),e.jsx(q,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Us,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No hay historial de suscripción"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-6 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ma,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Filtros"}),I&&e.jsxs(D,{variant:"ghost",size:"sm",onClick:S,className:"h-6 px-2 text-xs ml-auto",children:[e.jsx(hs,{className:"h-3 w-3 mr-1"}),"Limpiar"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Tipo de evento"}),e.jsxs(Re,{value:l,onValueChange:h,children:[e.jsx(Te,{className:"h-9",children:e.jsx(Le,{placeholder:"Todos los eventos"})}),e.jsx(Ve,{children:ci.map(c=>e.jsx(le,{value:c.value,children:c.label},c.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Desde"}),e.jsxs(ja,{children:[e.jsx(va,{asChild:!0,children:e.jsxs(D,{variant:"outline",className:Oe("h-9 w-full justify-start text-left font-normal",!u&&"text-muted-foreground"),children:[e.jsx(xs,{className:"mr-2 h-4 w-4"}),u?be(u,"dd/MM/yyyy"):"Seleccionar"]})}),e.jsx(ya,{className:"w-auto p-0",align:"start",children:e.jsx(ua,{mode:"single",selected:u,onSelect:C,initialFocus:!0,locale:Ce})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Hasta"}),e.jsxs(ja,{children:[e.jsx(va,{asChild:!0,children:e.jsxs(D,{variant:"outline",className:Oe("h-9 w-full justify-start text-left font-normal",!N&&"text-muted-foreground"),children:[e.jsx(xs,{className:"mr-2 h-4 w-4"}),N?be(N,"dd/MM/yyyy"):"Seleccionar"]})}),e.jsx(ya,{className:"w-auto p-0",align:"start",children:e.jsx(ua,{mode:"single",selected:N,onSelect:y,initialFocus:!0,locale:Ce})})]})]})]})]}),e.jsx("div",{className:"mb-6 p-4 bg-primary/5 rounded-lg border border-primary/20",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Pagado"}),e.jsxs("p",{className:"text-lg font-bold text-primary",children:["$",w().toFixed(2)," USD"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pagos Realizados"}),e.jsx("p",{className:"text-lg font-bold",children:b()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Eventos Mostrados"}),e.jsxs("p",{className:"text-lg font-bold text-muted-foreground",children:[i.length," de ",t.length]})]})]})}),i.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ma,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No hay eventos que coincidan con los filtros"}),e.jsx(D,{variant:"link",onClick:S,className:"mt-2",children:"Limpiar filtros"})]}):e.jsx("div",{className:"space-y-3",children:i.map(c=>{const g=d(c.action);return e.jsxs("div",{className:"border rounded-lg p-4 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsx("div",{className:"flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsxs(re,{variant:g.variant,className:`${g.className} flex items-center gap-1`,children:[g.icon,g.label]}),c.amount&&e.jsxs("span",{className:"font-semibold text-sm",children:["$",c.amount.toFixed(2)," ",c.currency?.toUpperCase()||"USD"]})]})}),e.jsxs("div",{className:"text-xs text-muted-foreground text-right",children:[be(new Date(c.created_at),"dd MMM yyyy",{locale:Ce}),e.jsx("br",{}),be(new Date(c.created_at),"HH:mm",{locale:Ce})]})]}),c.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2 pt-2 border-t",children:c.notes}),c.stripe_event_id&&e.jsxs("p",{className:"text-xs text-muted-foreground
2/60 mt-1",children:["Stripe: ",c.stripe_event_id.substring(0,20),"..."]})]},c.id)})})]})})]})},ui=({daysRemaining:s,totalDays:t=30,onUpgradeClick:a})=>{const r=t-s,n=Math.min(100,Math.max(0,r/t*100)),h=s<=2?"critical":s<=7?"warning":s<=15?"info":"none";if(h==="none")return null;const C=(()=>{switch(h){case"critical":return{variant:"destructive",bgClass:"",textClass:"",progressClass:"bg-destructive",icon:e.jsx(as,{className:"h-5 w-5"}),title:"⚠️ Tu período de prueba está por terminar",message:s<=0?"Tu período de prueba ha expirado. Actualiza ahora para continuar usando todas las funciones.":`Solo te quedan ${s} ${s===1?"día":"días"} de prueba. ¡Actualiza ahora!`};case"warning":return{variant:"default",bgClass:"border-amber-200 bg-amber-50",textClass:"text-amber-800",progressClass:"bg-amber-500",icon:e.jsx(We,{className:"h-5 w-5 text-amber-600"}),title:"📅 Tu prueba termina pronto",message:`Te quedan ${s} días de tu período de prueba. Considera actualizar a un plan de pago para mantener todas las funciones.`};case"info":return{variant:"default",bgClass:"border-blue-200 bg-blue-50",textClass:"text-blue-800",progressClass:"bg-blue-500",icon:e.jsx(We,{className:"h-5 w-5 text-blue-600"}),title:"🎉 Período de Prueba Activo",message:`Te quedan ${s} días para explorar todas las funciones. Aprovecha para conocer los beneficios de los planes Premium.`};default:return{variant:"default",bgClass:"",textClass:"",progressClass:"bg-primary",icon:e.jsx(We,{className:"h-5 w-5"}),title:"Período de Prueba",message:`${s} días restantes`}}})(),N=["Menú hasta 50 ítems","Analíticas avanzadas","Notificaciones Push a seguidores","Detección por ubicación","Soporte prioritario"];return e.jsx(cs,{variant:C.variant,className:`mb-6 ${C.bgClass}`,children:e.jsxs("div",{className:"flex flex-col gap-4 w-full",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[C.icon,e.jsxs("div",{className:"flex-1",children:[e.jsx(ys,{className:C.textClass,children:C.title}),e.jsx(ds,{className:`mt-1 ${C.textClass}`,children:C.message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:C.textClass,children:["Día ",r," de ",t]}),e.jsxs("span",{className:C.textClass,children:[s," días restantes"]})]}),e.jsx(aa,{value:n,className:"h-2"})]}),(h==="warning"||h==="critical")&&e.jsxs("div",{className:"bg-background/80 rounded-lg p-3 mt-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(bs,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Beneficios del Plan Premium:"})]}),e.jsx("ul",{className:"grid grid-cols-1 sm:grid-cols-2 gap-1",children:N.map((y,v)=>e.jsxs("li",{className:"flex items-center gap-2 text-xs",children:[e.jsx(Ts,{className:"h-3 w-3 text-green-500 flex-shrink-0"}),e.jsx("span",{children:y})]},v))})]}),e.jsxs(D,{onClick:a,variant:h==="critical"?"default":"outline",className:"w-full sm:w-auto",children:[e.jsx(bs,{className:"h-4 w-4 mr-2"}),"Ver Planes Premium"]})]})})},mi=({restaurantId:s,restaurantName:t,hasLifetime:a,lifetimeStatus:r,onRefresh:n})=>{const[l,h]=f.useState(!1),[u,C]=f.useState(!1),[N,y]=f.useState(!1),[v,i]=f.useState("zelle"),[S,I]=f.useState(""),{toast:d}=Ie(),w=async()=>{h(!0);try{const{data:c,error:g}=await L.functions.invoke("create-lifetime-checkout",{body:{restaurantId:s}});if(g)throw g;if(c?.url)window.open(c.url,"_blank");else throw new Error("No se recibió URL de pago")}catch(c){const g=c instanceof Error?c.message:"Error al crear sesión de pago";d({variant:"destructive",title:"Error",description:g})}finally{h(!1)}},b=async()=>{if(!S.trim()){d({variant:"destructive",title:"Falta la referencia",description:"Indica la referencia o comprobante del pago."});return}C(!0);try{const c=S.trim(),{error:g}=await L.from("lifetime_subscriptions").upsert({restaurant_id:s,payment_method:v,payment_reference:c,status:"pending_approval"},{onConflict:"restaurant_id"});if(g)throw g;const{error:j}=await L.from("payment_notifications").insert({restaurant_id:s,notification_type:"payment_made",message:"Pago manual del Plan Fundador ($49.99 USD) - Pendiente de aprobación",amount:49.99,currency:"USD",payment_method:v,payment_reference:c,payment_date:new Date().toISOString(),status:"pending"});if(j)throw j;
2d({title:"📩 Solicitud Enviada",description:"Tu solicitud de pago manual ha sido enviada. Un administrador la revisará y activará tu Plan Fundador."}),y(!1),I(""),n()}catch(c){const g=c instanceof Error?c.message:"Error al enviar solicitud";d({variant:"destructive",title:"Error",description:g})}finally{C(!1)}};return a&&r==="active"?e.jsxs($,{className:"border-2 border-green-300 bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950/30 dark:to-emerald-950/30",children:[e.jsxs(K,{className:"text-center pb-2",children:[e.jsx("div",{className:"flex justify-center mb-2",children:e.jsx("div",{className:"bg-green-100 dark:bg-green-900/50 rounded-full p-3",children:e.jsx(rs,{className:"h-8 w-8 text-green-600"})})}),e.jsx(Q,{className:"text-xl flex items-center justify-center gap-2",children:"🎉 Plan Fundador Activo"}),e.jsx(ve,{children:"Tienes acceso Premium permanente. ¡Sin pagos mensuales!"})]}),e.jsx(q,{className:"text-center",children:e.jsxs(re,{className:"bg-green-600 text-white",children:[e.jsx(ka,{className:"h-3 w-3 mr-1"}),"Acceso de por vida"]})})]}):a&&r==="pending_approval"?e.jsxs($,{className:"border-2 border-yellow-300 bg-gradient-to-br from-yellow-50 to-amber-50 dark:from-yellow-950/30 dark:to-amber-950/30",children:[e.jsxs(K,{className:"text-center pb-2",children:[e.jsx("div",{className:"flex justify-center mb-2",children:e.jsx("div",{className:"bg-yellow-100 dark:bg-yellow-900/50 rounded-full p-3",children:e.jsx(rs,{className:"h-8 w-8 text-yellow-600"})})}),e.jsx(Q,{className:"text-xl",children:"Plan Fundador - Pendiente"}),e.jsx(ve,{children:"Tu pago manual está siendo revisado por un administrador."})]}),e.jsx(q,{className:"text-center",children:e.jsxs(re,{variant:"secondary",className:"bg-yellow-100 text-yellow-800 border-yellow-200",children:[e.jsx(pe,{className:"h-3 w-3 mr-1 animate-spin"}),"Pendiente de aprobación"]})})]}):e.jsxs($,{className:"border-2 border-primary/50 bg-gradient-to-br from-orange-50 via-amber-50 to-yellow-50 dark:from-orange-950/30 dark:via-amber-950/20 dark:to-yellow-950/20 shadow-lg relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 bg-primary text-primary-foreground px-4 py-1 text-xs font-bold rounded-bl-lg",children:"OFERTA ESPECIAL"}),e.jsxs(K,{className:"text-center pb-3 pt-6",children:[e.jsx("div",{className:"flex justify-center mb-3",children:e.jsx("div",{className:"bg-primary/10 rounded-full p-4",children:e.jsx(rs,{className:"h-10 w-10 text-primary"})})}),e.jsx(Q,{className:"text-2xl font-bold",children:"Plan Fundador"}),e.jsx(ve,{className:"text-base",children:"Únete sin costo inicial y disfruta de los primeros 3 meses por nuestra cuenta."}),e.jsxs("div",{className:"flex items-baseline justify-center gap-1 mt-3",children:[e.jsx("span",{className:"text-4xl font-extrabold text-primary",children:"$49.99"}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"USD / único pago"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["En vez de $49.99/mes — ",e.jsx("span",{className:"font-semibold text-green-600",children:"Ahorra desde el segundo mes"})]})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2",children:["Acceso Premium permanente","Sin pagos mensuales nunca más","Todas las funciones incluidas","Analíticas avanzadas","Geolocalización activa","Soporte prioritario"].map(c=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ts,{className:"h-4 w-4 text-green-500 shrink-0"}),e.jsx("span",{children:c})]},c))}),e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(D,{onClick:w,disabled:l,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground font-semibold",size:"lg",children:l?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 animate-spin mr-2"}),"Procesando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{className:"h-4 w-4 mr-2"}),"Pagar con Tarjeta (Stripe)"]})}),e.jsxs(D,{onClick:()=>y(!0),disabled:u,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Pago Manual (Zelle / Binance)"]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"El pago manual requiere aprobación del administrador"}),e.jsx(ps,{open:N,onOpenChange:y,children:e.jsxs(fs,{className:"sm:max-w-[420px]",children:[e.jsxs(gs,{children:[e.jsx(js,{children:"Reportar pago manual"}),e.jsx(Rs,{children:"Indica cómo pagaste los $49.99 USD y la referencia del comprobante para que el administrador pueda verificarlo."})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Método de pago"}),e.jsxs(Re,{value:v,onValueChange:c=>i(c),children:[e.jsx(Te,{children:e.jsx(Le,{})}),e.jsxs(Ve,{children:[e.jsx(le,{value:"zelle",children:"Zelle (USD)"}),e.jsx(le,{value:"binance",children:"Binance (USD)"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"lifetime-reference",children:"Referencia / comprobante"}),e.jsx(X,{id:"lifetime-reference",value:S,onChange:c=>I(c.target.value),placeholder:"Ej: 0123456789 o correo del remitente"})]})]}),e.jsxs(Et,{children:[e.jsx(D,{variant:"outline",onClick:()=>y(!1),disabled:u,children:"Cancelar"}),e.jsx(D,{onClick:b,disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 animate-spin mr-2"}),"Enviando..."]}):"Enviar solicitud"})]})]})})]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 pt-2",children:[e.jsx(Za,{className:"h-3 w-3 text-yellow-500 fill-yellow-500"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Cupos limitados para los primeros 500 restaurantes"}),e.jsx(Za,{className:"h-3 w-3 text-yellow-500 fill-yellow-500"})]})]})]})},xi=()=>{const{currentRestaurant:s,userRestaurants:t}=ls(),[a,r]=f.useState(null),[n,l]=f.useState([]),[h,u]=f.useState(!0),[C,N]=f.useState(!1),[y,v]=f.useState(null),[i,S]=f.useState(!1),[I,d]=f.useState(null),{toast:w}=Ie(),b=s||t?.[0],{permissions:c}=Rt(b?.id);f.useEffect(()=>
2{b?.id&&(j(b.id),T(b.id),oe(b.id))},[b]),f.useEffect(()=>{c?.plan_type&&g(c.plan_type)},[c?.plan_type]);const g=async E=>{try{let P="%básico%";E==="premium"?P="%premium%":E==="especial"&&(P="%especial%");const{data:O,error:Z}=await L.from("subscription_plans").select("price_monthly").ilike("name",P).eq("is_active",!0).single();if(Z){console.error("Error fetching plan price:",Z);return}v(O?.price_monthly||null)}catch(P){console.error("Error fetching current plan price:",P)}},j=async E=>{try{u(!0);const{data:P,error:O}=await L.rpc("get_restaurant_subscription_status",{p_restaurant_id:E});if(O)throw O;const{data:Z,error:p}=await L.from("subscription_status").select("last_payment_date, payment_method").eq("restaurant_id",E).single();p&&p.code!=="PGRST116"&&console.error("Error fetching payment data:",p);const{data:M}=await L.from("restaurants").select("stripe_customer_id").eq("id",E).single(),U=P?.[0]||{status:"pending",next_payment_due:null,days_until_due:null,suspension_message:"Servicio temporalmente no disponible debido a suscripción pendiente."};r({...U,last_payment_date:Z?.last_payment_date||null,payment_method:Z?.payment_method||"manual",stripe_customer_id:M?.stripe_customer_id||null})}catch(P){console.error("Error fetching subscription data:",P),r({status:"pending",next_payment_due:null,days_until_due:null,suspension_message:"Error al verificar el estado de suscripción.",last_payment_date:null})}finally{u(!1)}},T=async E=>{try{const{data:P,error:O}=await L.from("support_messages").select("*").eq("restaurant_id",E).order("created_at",{ascending:!1});if(O)throw O;l(P||[])}catch(P){console.error("Error fetching support messages:",P)}},G=async()=>{if(b?.id){N(!0);try{const{data:E,error:P}=await L.functions.invoke("customer-portal",{body:{restaurantId:b.id}});if(P)throw P;if(E?.url)window.open(E.url,"_blank");else throw new Error("No se recibió URL del portal")}catch(E){console.error("Error opening customer portal:",E);const P=E instanceof Error?E.message:"No se pudo abrir el portal de cliente.";w({variant:"destructive",title:"Error",description:P})}finally{N(!1)}}},te=a?.status==="trial",Y=a?.days_until_due,J=I!==null,ge=I==="active",oe=async E=>{try{const{data:P}=await L.from("promotion_settings").select("lifetime_promo_enabled").limit(1).single();S(P?.lifetime_promo_enabled??!1);const{data:O}=await L.from("lifetime_subscriptions").select("status").eq("restaurant_id",E).single();d(O?.status??null)}catch(P){console.error("Error fetching lifetime promo:",P)}},m=E=>{switch(E){case"active":return e.jsxs(re,{variant:"default",className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(Ts,{className:"h-3 w-3 mr-1"}),"Activa"]});case"trial":return e.jsxs(re,{variant:"default",className:"bg-purple-100 text-purple-800 border-purple-200",children:[e.jsx(Tt,{className:"h-3 w-3 mr-1"}),"Período de Prueba"]});case"pending":return e.jsxs(re,{variant:"secondary",className:"bg-yellow-100 text-yellow-800 border-yellow-200",children:[e.jsx(We,{className:"h-3 w-3 mr-1"}),"Pendiente"]});case"suspended":return e.jsxs(re,{variant:"destructive",children:[e.jsx(as,{className:"h-3 w-3 mr-1"}),"Suspendida"]});default:return e.jsxs(re,{variant:"outline",children:[e.jsx(We,{className:"h-3 w-3 mr-1"}),E]})}},k=()=>{if(!a)return null;const{status:E,days_until_due:P}=a;return E==="suspended"?e.jsxs(cs,{variant:"destructive",className:"mb-6",children:[e.jsx(as,{className:"h-4 w-4"}),e.jsx(ys,{children:"Servicio Suspendido"}),e.jsx(ds,{children:a.suspension_message})]}):E==="pending"||P!==null&&P<=7?e.jsxs(cs,{variant:"default",className:"mb-6 border-yellow-200 bg-yellow-50",children:[e.jsx(We,{className:"h-4 w-4 text-yellow-600"}),e.jsx(ys,{className:"text-yellow-800",children:"Acción Requerida"}),e.jsxs(ds,{className:"text-yellow-700",children:[P!==null&&P<0?`Su suscripción venció hace ${Math.abs(P)} días.`:P!==null&&P<=7?`Su suscripción vence en ${P} días.`:"Su suscripción está pendiente de pago."," Contacte al administrador para renovar su suscripción."]})]}):null};return h?e.jsx("div",{className:"space-y-6",children:e.jsxs("div",{className:"animate-pulse",children:[e.jsx("div",{className:"h-32 bg-muted rounded-lg mb-4"}),e.jsx("div",{className:"h-48 bg-muted rounded-lg"})]})}):a?e.jsxs("div",{className:"space-y-6",children:[b&&(i||J)&&e.jsx(mi,{restaurantId:b.id,restaurantName:b.name,hasLifetime:J,lifetimeStatus:I??void 0,onRefresh:()=>
2{b?.id&&(oe(b.id),j(b.id))}}),te&&Y!==null&&e.jsx(ui,{daysRemaining:Y,totalDays:30,onUpgradeClick:()=>window.open("https://wa.me/584121353788","_blank")}),k(),e.jsxs($,{children:[e.jsx(K,{children:e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(De,{className:"h-5 w-5"}),"Estado de Suscripción"]})}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Estado Actual:"}),m(a.status)]}),a?.stripe_customer_id&&e.jsxs("div",{className:"pt-2",children:[e.jsx(D,{variant:"outline",className:"w-full",onClick:G,disabled:C,children:C?e.jsxs(e.Fragment,{children:[e.jsx(pe,{className:"h-4 w-4 animate-spin mr-2"}),"Abriendo portal..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Gestionar Suscripción"]})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 text-center",children:"Administra tu tarjeta, cancela o modifica tu plan desde el portal de Stripe"})]}),a.last_payment_date&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Último Pago:"}),e.jsx("span",{className:"font-medium",children:be(new Date(a.last_payment_date),"dd 'de' MMMM 'de' yyyy",{locale:Ce})})]}),a.next_payment_due?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Próximo Vencimiento:"}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-medium",children:be(new Date(a.next_payment_due),"dd 'de' MMMM 'de' yyyy",{locale:Ce})}),a.days_until_due!==null&&e.jsx("div",{className:`text-sm ${a.days_until_due<0?"text-red-600":a.days_until_due<=7?"text-yellow-600":"text-muted-foreground"}`,children:a.days_until_due<0?`Vencida hace ${Math.abs(a.days_until_due)} días`:`${a.days_until_due} días restantes`})]})]}):ge?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Vencimiento:"}),e.jsxs(re,{className:"bg-green-100 text-green-800 border-green-200",children:[e.jsx(ka,{className:"h-3 w-3 mr-1"}),"Sin vencimiento - Plan Fundador"]})]}):null]})]}),!ge&&a.status!=="active"&&e.jsxs(cs,{className:"border-blue-200 bg-blue-50",children:[e.jsx(wa,{className:"h-4 w-4 text-blue-600"}),e.jsx(ys,{className:"text-blue-800",children:"Activación de Plan"}),e.jsxs(ds,{className:"text-blue-700",children:["Para activar o cambiar tu plan, contacta a tu operador local o L.U.C. Ellos gestionarán la activación de tu suscripción.",e.jsx("div",{className:"mt-2",children:e.jsx(D,{variant:"outline",size:"sm",onClick:()=>window.open("https://wa.me/584121353788","_blank"),className:"text-blue-700 border-blue-300 hover:bg-blue-100",children:"📱 Contactar por WhatsApp"})})]})]}),e.jsxs($,{children:[e.jsx(K,{children:e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"h-5 w-5"}),"Detalles de la Cuenta"]})}),e.jsx(q,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm text-muted-foreground",children:"Restaurante"}),e.jsx("p",{className:"font-medium",children:b?.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm text-muted-foreground",children:"Plan Actual"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium",children:c?.plan_type==="premium"?"Plan Premium":c?.plan_type==="especial"?"Plan Especial":"Plan Básico"}),y!==null&&e.jsxs("span",{className:"text-primary font-semibold",children:["$",y.toFixed(2),"/mes"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm text-muted-foreground",children:"Método de Pago"}),e.jsx("div",{className:"flex items-center gap-2",children:a?.payment_method==="str
2ipe"?e.jsxs(e.Fragment,{children:[e.jsxs(re,{variant:"default",className:"bg-purple-100 text-purple-800 border-purple-200",children:[e.jsx(De,{className:"h-3 w-3 mr-1"}),"Stripe"]}),a?.stripe_customer_id&&e.jsx(D,{variant:"outline",size:"sm",onClick:G,disabled:C,children:C?e.jsx(pe,{className:"h-3 w-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ks,{className:"h-3 w-3 mr-1"}),"Gestionar"]})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Pago Manual"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium text-sm text-muted-foreground",children:"Ciclo de Facturación"}),e.jsx("p",{className:"text-muted-foreground",children:"Mensual"})]})]})})]}),e.jsxs($,{children:[e.jsx(K,{children:e.jsx(Q,{children:"Módulo de Pagos y Soporte"})}),e.jsxs(q,{className:"space-y-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground mb-4",children:"¿Necesitas ayuda con tu suscripción? Nuestro equipo está aquí para asistirte."}),e.jsx("div",{className:"mb-6 p-4 bg-gradient-to-r from-primary/10 to-primary/5 rounded-lg border border-primary/20",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-sm",children:a.status==="active"?"💳 Pagar por Adelantado":"💳 ¿Ya realizaste el pago?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a.status==="active"?"Paga 3, 6 o 12 meses por adelantado y evita interrupciones":"Notifica al administrador para activar tu suscripción más rápido"})]}),e.jsx(li,{children:e.jsxs(D,{variant:a.status==="active"?"default":"outline",className:"w-full sm:w-auto",children:[e.jsx(es,{className:"h-4 w-4 mr-2"}),"Notificar Pago"]})})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(ar,{subscriptionStatus:a.status,nextPaymentDue:a.next_payment_due?be(new Date(a.next_payment_due),"dd 'de' MMMM 'de' yyyy",{locale:Ce}):"No disponible",children:e.jsxs(D,{variant:"default",className:"flex items-center gap-2 w-full sm:w-auto",children:[e.jsx(ms,{className:"h-4 w-4"}),"Notificar a Soporte"]})}),e.jsx(D,{variant:"outline",onClick:()=>window.open("https://wa.me/584121353788","_blank"),className:"flex items-center gap-2",children:"📱 WhatsApp"})]}),a.status!=="active"&&e.jsxs(cs,{className:"mt-4",children:[e.jsx(as,{className:"h-4 w-4"}),e.jsxs(ds,{children:[e.jsx("strong",{children:"Importante:"})," Para reactivar su servicio o actualizar su suscripción, contacte a nuestro equipo de soporte. Procesaremos su solicitud en horario comercial."]})]})]})]}),n.length>0&&e.jsxs($,{children:[e.jsx(K,{children:e.jsxs(Q,{className:"flex items-center gap-2",children:[e.jsx(Ga,{className:"h-5 w-5"}),"Mensajes de Soporte"]})}),e.jsx(q,{children:e.jsx("div",{className:"space-y-4",children:n.map(E=>e.jsxs("div",{className:"border rounded-lg p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium text-sm",children:E.subject}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:be(new Date(E.created_at),"dd 'de' MMMM 'de' yyyy, HH:mm",{locale:Ce})})]}),e.jsx(re,{variant:E.status==="resolved"?"default":E.status==="in_progress"?"secondary":"outline",className:E.status==="resolved"?"bg-green-100 text-green-800 border-green-200":E.status==="in_progress"?"bg-blue-100 text-blue-800 border-blue-200":"",children:E.status==="resolved"?"Resuelto":E.status==="in_progress"?"En Proceso":E.status==="closed"?"Cerrado":"Pendiente"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"Tu mensaje:"}),e.jsx("p",{className:"mt-1",children:E.message})]}),E.admin_response&&e.jsxs("div",{className:"bg-primary/5 border-l-4 border-primary rounded p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ga,{className:"h-4 w-4 text-primary"}),e.jsx("strong",{className:"text-sm text-primary",children:"Respuesta del Administrador:"})]}),e.jsx("p",{className:"text-sm",children:E.admin_response}),E.resolved_at&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Respondido el ",be(new Date(E.resolved_at),"dd 'de' MMMM 'de' yyyy, HH:mm",{locale:Ce})]})]})]},E.id))})})]}),b?.id&&e.jsx(di,{restaurantId:b.id}),b?.id&&e.jsx(oi,{restaurantId:b.id})]}):e.jsxs(cs,{variant:"destructive",children:[e.jsx(as,{className:"h-4 w-4"}),e.jsx(ys,{children:"Error"}
2),e.jsx(ds,{children:"No se pudo cargar la información de suscripción."})]})},bt=({restaurantId:s})=>{const[t,a]=f.useState(0),[r,n]=f.useState([]),[l,h]=f.useState(!1),{toast:u}=Ie(),C=async()=>{try{const{data:v,error:i}=await L.from("restaurant_notifications").select("*").eq("restaurant_id",s).eq("status","unread").order("created_at",{ascending:!1});if(i)throw i;n(v||[]),a((v||[]).length)}catch(v){console.error("Error fetching notifications:",v)}};f.useEffect(()=>{if(s){C();const v=L.channel("restaurant-notifications").on("postgres_changes",{event:"*",schema:"public",table:"restaurant_notifications",filter:`restaurant_id=eq.${s}`},i=>{console.log("Notification change:",i),C(),i.eventType==="INSERT"&&u({title:"Nueva notificación",description:"Tienes un nuevo mensaje de la plataforma"})}).subscribe();return()=>{L.removeChannel(v)}}},[s,u]);const N=async v=>{try{const{error:i}=await L.from("restaurant_notifications").update({status:"read",read_at:new Date().toISOString()}).eq("id",v);if(i)throw i;C()}catch(i){console.error("Error marking notification as read:",i),u({variant:"destructive",title:"Error",description:"No se pudo marcar la notificación como leída"})}},y=async()=>{try{const{error:v}=await L.from("restaurant_notifications").update({status:"read",read_at:new Date().toISOString()}).eq("restaurant_id",s).eq("status","unread");if(v)throw v;u({title:"Notificaciones marcadas",description:"Todas las notificaciones han sido marcadas como leídas"}),C()}catch(v){console.error("Error marking all as read:",v),u({variant:"destructive",title:"Error",description:"No se pudieron marcar las notificaciones"})}};return e.jsxs(ps,{open:l,onOpenChange:h,children:[e.jsx(Fs,{asChild:!0,children:e.jsxs(D,{variant:"outline",className:"relative",children:[e.jsx(ms,{className:"h-4 w-4"}),t>0&&e.jsx(re,{variant:"destructive",className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:t>9?"9+":t})]})}),e.jsxs(fs,{className:"max-w-2xl",children:[e.jsxs(gs,{children:[e.jsxs(js,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Notificaciones de la Plataforma"}),t>0&&e.jsx(D,{variant:"ghost",size:"sm",onClick:y,children:"Marcar todas como leídas"})]}),e.jsx(Rs,{children:"Mensajes y actualizaciones importantes de Live-Menu"})]}),e.jsx(kt,{className:"h-[500px] pr-4",children:r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ms,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No tienes notificaciones"})]}):e.jsx("div",{className:"space-y-4",children:r.map(v=>e.jsxs($,{className:v.status==="unread"?"border-primary":"",children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs(Q,{className:"text-base flex items-center gap-2",children:[v.subject,v.status==="unread"&&e.jsx(re,{variant:"default",className:"ml-2",children:"Nueva"})]}),v.status==="unread"&&e.jsx(D,{variant:"ghost",size:"sm",onClick:()=>N(v.id),children:"Marcar leída"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(v.created_at).toLocaleString("es-MX",{day:"2-digit",month:"long",year:"numeric",hour:"2-digit",minute:"2-digit"})})]}),e.jsx(q,{children:e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.message})})]},v.id))})})]})]})};function hi({restaurantId:s}){const[t,a]=f.useState(null);if(f.useEffect(()=>{if(!s)return;let n=!1;return L.from("restaurants").select("billing_model").eq("id",s).maybeSingle().then(({data:l})=>{!n&&l&&a(l.billing_model)}),()=>{n=!0}},[s]),!t)return null;const r=t==="revenue_share"?"Modelo: Revenue Share":"Modelo: Suscripción";return e.jsx(re,{variant:t==="revenue_share"?"default":"secondary",className:"text-[10px] sm:text-xs",children:r})}const al=()=>{const{user:s,signOut:t}=xr(),{currentRestaurant:a,userRestaurants:r,userRole:n,loading:l,setCurrentRestaurant:h}=ls(),{toast:u}=Ie(),C=hr(),[N,y]=f.useState(!1),[v,i]=f.useState(!1),S=wt(),{showRoleSelector:I,setShowRoleSelector:d,availableRoles:w,userEmail:b}=Rr({expectedRole:"restaurant_owner"}),c=async()=>{try{await t(),C("/")}catch(j){console.error("Error signing out:",j)}},g=j=>{const T=r.find(G=>
2G.id===j);T&&h(T)};return f.useEffect(()=>{(async()=>{if(s&&!l&&r.length===0){let T=localStorage.getItem("pendingRestaurant");if(!T&&s.email)try{const{data:G}=await L.from("pending_restaurants").select("restaurant_data").eq("user_email",s.email.toLowerCase()).eq("status","pending_email_confirmation").order("created_at",{ascending:!1}).limit(1).maybeSingle();G?.restaurant_data&&(T=JSON.stringify(G.restaurant_data))}catch(G){console.warn("Could not check pending_restaurants backup:",G)}if(T)try{const G=JSON.parse(T);y(!0);const{data:te,error:Y}=await L.rpc("complete_restaurant_registration",{p_user_id:s.id,p_restaurant_name:G.name,p_restaurant_slug:G.slug,p_description:G.description||"",p_address:G.address||"",p_phone:G.phone||"",p_website:G.website||"",p_country:G.country||G.territory||"Mexico",p_user_email:s.email||null,p_referral_code:G.referralCode||null});if(localStorage.removeItem("referralCode"),Y)throw Y;const ge=te?.restaurant_id,oe=G.name;if(!ge)throw new Error("No se pudo obtener el ID del restaurante");try{const m=`¡Hola, ${oe}! 👋
3
4¡Bienvenidos a Live-Menu! Estamos muy contentos de tenerte con nosotros. 🎉
5
6Ya tienes acceso a todas las herramientas para impulsar tu negocio: análisis de menú, promociones, detección por ubicación y mucho más.
7
8Si necesitas ayuda, no dudes en escribirnos. ¡Éxito!
9
10— El Equipo de Live-Menu`,{error:k}=await L.from("restaurant_notifications").insert([{restaurant_id:ge,subject:"¡Bienvenido a Live-Menu! 🎉",message:m,status:"unread"}]);k&&console.error("Error sending welcome notification:",k)}catch(m){console.error("Error creating welcome notification:",m)}localStorage.removeItem("pendingRestaurant"),s.email&&L.from("pending_restaurants").update({status:"completed"}).eq("user_email",s.email.toLowerCase()).eq("status","pending_email_confirmation").then(()=>{}),u({title:"¡Restaurante creado!",description:"Tu restaurante ha sido registrado exitosamente."}),window.location.reload()}catch(G){console.error("Error creating restaurant:",G),u({variant:"destructive",title:"Error",description:G.message||"No se pudo crear el restaurante. Intenta de nuevo."})}finally{y(!1)}}})()},[s,l,r,u]),N||l?e.jsx("div",{className:"min-h-screen bg-gradient-subtle flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Cargando panel de administración..."})]})}):r.length===0?e.jsx("div",{className:"min-h-screen bg-gradient-subtle flex items-center justify-center",children:e.jsxs($,{className:"w-full max-w-md border-0 shadow-elegant",children:[e.jsxs(K,{className:"text-center",children:[e.jsx(oa,{className:"h-12 w-12 text-primary mx-auto mb-4"}),e.jsx(Q,{children:"No tienes restaurantes registrados"}),e.jsx(ve,{children:"Para acceder al panel de administración, necesitas tener al menos un restaurante registrado."})]}),e.jsxs(q,{className:"space-y-4",children:[e.jsxs(D,{onClick:()=>C("/register-restaurant"),className:"w-full",children:[e.jsx(Ka,{className:"h-4 w-4 mr-2"}),"Registrar Restaurante"]}),e.jsx(D,{onClick:()=>C("/"),variant:"outline",className:"w-full",children:"Volver al inicio"})]})]})}):e.jsx(pr,{children:e.jsxs("div",{className:"min-h-screen bg-gradient-subtle safe-area-top safe-area-bottom",children:[e.jsx("header",{className:"bg-card/80 backdrop-blur-sm border-b border-border/50 sticky top-0 z-40",children:e.jsx("div",{className:"container mx-auto px-3 sm:px-4 py-3 sm:py-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-1 min-w-0",children:[S&&e.jsxs(Lr,{open:v,onOpenChange:i,children:[e.jsx(Vr,{asChild:!0,children:e.jsx(D,{variant:"ghost",size:"icon",className:"shrink-0",children:e.jsx(tn,{className:"h-5 w-5"})})}),e.jsxs(Ir,{side:"left",className:"w-[280px] sm:w-[350px] bg-background/95 backdrop-blur-sm",children:[e.jsx(Ur,{className:"text-left mb-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(oa,{className:"h-8 w-8 text-primary"}),e.jsx(zr,{children:"Menú"})]})}),e.jsxs("div",{className:"flex flex-col gap-3",children:[r.length>1&&e.jsxs("div",{className:"pb-3 border-b border-border/50",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground mb-2 block",children:"Restaurante"}),e.jsxs(Re,{value:a?.id||"",onValueChange:g,children:[e.jsxs(Te,{className:"w-full bg-background/80",children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),e.jsx(Le,{placeholder:"Seleccionar"})]}),e.jsx(Ve,{className:"bg-background/95 backdrop-blur-sm",children:r.map(j=>e.jsx(le,{value:j.id,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:j.name}),j.description&&e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1",children:j.description})]})},j.id))})]})]}),a&&e.jsx(bt,{restaurantId:a.id}),e.jsxs(D,{onClick:()=>{window.open("https://github.com/Jcdelpino/dish-spotlight-pwa/blob/03448adaf9229a6386f51d9accfe9b9ed29537e8/MANUAL_CONFIGURACION_RESTAURANTE.md","_blank"),i(!1)},variant:"outline",className:"w-full justify-start",children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"}),"Guía de Uso"]}),e.jsxs(D,{onClick:()=>{C(`/restaurant/${a?.slug}`),i(!1)},variant:"outline",disabled:!a,className:"w-full justify-start",children:[e.jsx(Ks,{className:"h-4 w-4 mr-2"}),"Ver Sitio Público"]}),e.jsxs(D,{onClick:()=>{c(),i(!1)},variant:"ghost",className:"w-full justify-start text-destructive hover:text-destructive mt-6 border-t border-border/50 pt-6",children:[e.jsx(Oa,{className:"h-4 w-4 mr-2"}),"Cerrar Sesión"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0",children:[!S&&e.jsx(oa,{className:"h-6 w-6 sm:h-8 sm:w-8 text-primary shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-base sm:text-xl md:text-2xl font-bold text-foreground truncate",children:S?"Admin":"Panel de Administración"}),e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",children:a?.name||"Selecciona un restaurante"}),a&&e.jsx("div",{className:"mt-1",children:e.jsx(hi,{restaurantId:a.id})})]})]}),!S&&r.length>1&&e.jsx("div",{className:"ml-4",children:e.jsxs(Re,{value:a?.id||"",onValueChange:g,children:[e.jsxs(Te,{className:"w-[200px] lg:w-[280px] bg-background/80 backdrop-blur-sm",children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),e.jsx(Le,{placeholder:"Seleccionar restaurante"})]}),e.jsx(Ve,{className:"bg-background/95 backdrop-blur-sm border-border/50",children:r.map(j=>e.jsx(le,{value:j.id,children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:j.name}),j.description&&e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1",children:j.description})]})},j.id))})]})})]}),!S&&e.jsxs("div",{className:"flex items-center gap-2 lg:gap-3 shrink-0",children:[a&&e.jsx(bt,{restaurantId:a.id}),e.jsxs(D,{onClick:()=>window.open("https://github.com/Jcdelpino/dish-spotlight-pwa/blob/03448adaf9229a6386f51d9accfe9b9ed29537e8/MANUAL_CONFIGURACION_RESTAURANTE.md","_blank"),variant:"outline",size:"sm",className:"hidden lg:flex",children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"}),"Guía"]}),e.jsxs(D,{onClick:()=>C(`/restaurant/${a?.slug}`),variant:"outline",size:"sm",disabled:!a,children:[e.jsx(Ks,{className:"h-4 w-4 lg:mr-2"}),e.jsx("span",{className:"hidden lg:inline",children:"Ver Sitio"})]}),e.jsxs(D,{onClick:c,variant:"ghost",size:"sm",children:[e.jsx(Oa,{className:"h-4 w-4 lg:mr-2"}),e.jsx("span",{className:"hidden xl:inline",children:"Cerrar Sesión"})]})]})]})})}),e.jsx("main",{className:"container mx-auto px-3 sm:px-4 py-4 sm:py-8",children:a?(()=>{const T=!(a?.billing_model==="subscription");return e.jsxs(_s,{defaultValue:"menu",className:"w-full",children:[e.jsxs(ws,{className:`${S?"grid w-full grid-cols-2 h-auto":T?"grid w-full grid-cols-5":"grid w-full grid-cols-4"}`,children:[e.jsxs(Ee,{value:"menu",className:"flex items-center gap-1 sm:gap-2 text-xs sm:text-sm py-2",children:[e.jsx(Sa,{className:"h-3 w-3 sm:h-4 sm:w-4"}),e.jsx("span",{className:S?"text-xs":"",children:S?"Menú":"Gestión de Menú"})]}),e.jsxs(Ee,{value:"extras",className:"flex items-center gap-1 sm:gap-2 text-xs sm:text-sm py-2",children:[e.jsx(bs,{className:"h-3 w-3 sm:h-4 sm:w-4"}),"Herramientas"]}),e.jsxs(Ee,{value:"orders",className:"flex items-center gap-1 sm:gap-2 text-xs sm:text-sm py-2",children:[e.jsx(Us,{className:"h-3 w-3 sm:h-4 sm:w-4"}),e.jsx("span",{className:S?"text-xs":"",children:"Pedidos"})]}),T&&e.jsxs(Ee,{value:"invoices",className:"flex items-center gap-1 sm:gap-2 text-xs sm:text-sm py-2",children:[e.jsx(Us,{className:"h-3 w-3 sm:h-4 sm:w-4"}),e.jsx("span",{className:S?"text-xs":"",children:"Facturas"})]}),e.jsxs(Ee,{value:"settings",className:"flex items-center gap-1 sm:gap-2 text-xs sm:text-sm py-2",children:[e.jsx(Zr,{className:"h-3 w-3 sm:h-4 sm:w-4"}),e.jsx("span",{className:S?"text-xs":"",children:S?"Config":"Configuración"})]})]}),e.jsx(Me,{value:"menu",className:"mt-4 sm:mt-6",children:e.jsx(Rn,{})}),e.jsx(Me,{value:"extras",className:"mt-4 sm:mt-6",children:e.jsx(ri,{})}),e.jsx(Me,{value:"orders",className:"mt-4 sm:mt-6",children:a&&e.jsx(On,{restaurantId:a.id,billingModel:a.billing_model})}),T&&e.jsx(Me,{value:"invoices",className:"mt-4 sm:mt-6",children:a&&e.jsx(Hn,{restaurantId:a.id})}),e.jsx(Me,{value:"settings",className:"mt-4 sm:mt-6",children:e.jsxs(_s,{defaultValue:"restaurant",className:"w-full",children:[e.jsxs(ws,{className:"grid w-full grid-cols-2",children:[e.jsxs(Ee,{value:"restaurant",className:"flex items-center gap-2 text-xs sm:text-sm py-2",children:[e.jsx(Ka,{className:"h-3 w-3 sm:h-4 sm:w-4"}),"Restaurante"]}),e.jsxs(Ee,{value:"subscription",className:"flex items-center gap-2 text-xs sm:text-sm py-2",children:[e.jsx(De,{className:"h-3 w-3 sm:h-4 sm:w-4"}),"Suscripción"]})]}),e.jsx(Me,{value:"restaurant",className:"mt-4 sm:mt-6",children:e.jsx(Un,{})}),e.jsx(Me,{value:"subscription",className:"mt-4 sm:mt-6",children:e.jsx(xi,{})})]})})]})})():e.jsxs($,{className:"border-0 shadow-elegant",children:[e.jsxs(K,{className:"text-center",children:[e.jsx(Q,{className:"text-lg sm:text-xl",children:"Selecciona un restaurante"}),e.jsx(ve,{className:"text-sm",children:"Elige el restaurante que deseas administrar"})]}),e.jsx(q,{children:e.jsx("div",{className:"grid gap-3 sm:gap-4",children:r.map(j=>e.jsx(D,{onClick:()=>C(`/admin?restaurant=${j.slug}`),variant:"outline",className:"p-3 sm:p-4 h-auto text-left justify-start",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm sm:text-base truncate",children:j.name}),j.description&&e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground line-clamp-2",children:j.description})]})},j.id))})})]})}),e.jsx(sn,{open:I,onOpenChange:d,roles:w,userEmail:b})]})})};export{al 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.