forlogic-core 1.11.7 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import*as r from"react";import s,{createContext as n,useContext as i,useMemo as o,useRef as l,useCallback as d,useState as c,useEffect as u,createElement as m,memo as h,Component as p}from"react";import{Slot as f}from"@radix-ui/react-slot";import{cva as g}from"class-variance-authority";import{clsx as b}from"clsx";import{twMerge as v}from"tailwind-merge";import{parseISO as y,isValid as x,format as N}from"date-fns";import{toast as w,Toaster as k}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as C,X as S,ChevronDown as _,ChevronUp as P,Check as E,Loader2 as I,Loader2Icon as T,OctagonXIcon as A,TriangleAlertIcon as R,InfoIcon as O,CircleCheckIcon as L,AlertCircle as F,AlertTriangle as j,Search as M,FileX as z,ChevronRight as D,Circle as $,Edit as U,PowerOff as V,Power as q,Trash2 as B,Plus as W,ArrowUpDown as H,ArrowUp as K,ArrowDown as G,Target as Q,Trophy as J,Award as X,Sparkles as Y,Flame as Z,Zap as ee,Key as te,Shield as ae,EyeOff as re,Eye as se,Unlock as ne,Lock as ie,Archive as oe,FolderOpen as le,Folder as de,FileText as ce,Save as ue,Copy as me,Share as he,Upload as pe,Download as fe,HelpCircle as ge,Info as be,Bell as ve,Clock as ye,ArrowRight as xe,ArrowLeft as Ne,ChevronLeft as we,Minus as ke,Filter as Ce,Bookmark as Se,Book as _e,Video as Pe,Music as Ee,Image as Ie,Camera as Te,MapPin as Ae,Calendar as Re,Phone as Oe,Mail as Le,Settings as Fe,User as je,Home as Me,Heart as ze,Star as De,ChevronsLeft as $e,ChevronsRight as Ue,RefreshCw as Ve,MoreHorizontal as qe,PanelLeft as Be,ExternalLink as We,Globe as He,Building2 as Ke,LogOut as Ge,MessageCircle as Qe,Send as Je,Users as Xe,Crown as Ye,UserPlus as Ze}from"lucide-react";import*as et from"@radix-ui/react-label";import*as tt from"@radix-ui/react-dialog";import*as at from"@radix-ui/react-separator";import{useFormContext as rt,FormProvider as st,Controller as nt,appendErrors as it,useForm as ot}from"react-hook-form";import*as lt from"@radix-ui/react-select";import*as dt from"@radix-ui/react-checkbox";import*as ct from"@radix-ui/react-popover";import{createClient as ut}from"@supabase/supabase-js";import{useQueryClient as mt,useQuery as ht,useMutation as pt,QueryClient as ft,QueryClientProvider as gt}from"@tanstack/react-query";import{useSearchParams as bt,useLocation as vt,useNavigate as yt,Link as xt}from"react-router-dom";import*as Nt from"@radix-ui/react-alert-dialog";import*as wt from"@radix-ui/react-dropdown-menu";import*as kt from"@radix-ui/react-context-menu";import*as Ct from"@radix-ui/react-scroll-area";import*as St from"@radix-ui/react-switch";import*as _t from"@radix-ui/react-progress";import*as Pt from"@radix-ui/react-collapsible";import*as Et from"@radix-ui/react-accordion";import*as It from"@radix-ui/react-aspect-ratio";import*as Tt from"@radix-ui/react-avatar";import{DayPicker as At}from"react-day-picker";import{Drawer as Rt}from"vaul";import*as Ot from"@radix-ui/react-radio-group";import*as Lt from"@radix-ui/react-tooltip";import*as Ft from"@radix-ui/react-slider";import*as jt from"@radix-ui/react-tabs";import*as Mt from"@radix-ui/react-toggle";import*as zt from"@radix-ui/react-toggle-group";import Dt from"react-markdown";import $t from"remark-gfm";import{z as Ut}from"zod";import{validateFieldsNatively as Vt,toNestErrors as qt}from"@hookform/resolvers";const Bt=e=>"string"==typeof e,Wt=()=>{let e,t;const a=new Promise((a,r)=>{e=a,t=r});return a.resolve=e,a.reject=t,a},Ht=e=>null==e?"":""+e,Kt=/###/g,Gt=e=>e&&e.indexOf("###")>-1?e.replace(Kt,"."):e,Qt=e=>!e||Bt(e),Jt=(e,t,a)=>{const r=Bt(t)?t.split("."):t;let s=0;for(;s<r.length-1;){if(Qt(e))return{};const t=Gt(r[s]);!e[t]&&a&&(e[t]=new a),e=Object.prototype.hasOwnProperty.call(e,t)?e[t]:{},++s}return Qt(e)?{}:{obj:e,k:Gt(r[s])}},Xt=(e,t,a)=>{const{obj:r,k:s}=Jt(e,t,Object);if(void 0!==r||1===t.length)return void(r[s]=a);let n=t[t.length-1],i=t.slice(0,t.length-1),o=Jt(e,i,Object);for(;void 0===o.obj&&i.length;)n=`${i[i.length-1]}.${n}`,i=i.slice(0,i.length-1),o=Jt(e,i,Object),o?.obj&&void 0!==o.obj[`${o.k}.${n}`]&&(o.obj=void 0);o.obj[`${o.k}.${n}`]=a},Yt=(e,t)=>{const{obj:a,k:r}=Jt(e,t);if(a&&Object.prototype.hasOwnProperty.call(a,r))return a[r]},Zt=(e,t,a)=>{for(const r in t)"__proto__"!==r&&"constructor"!==r&&(r in e?Bt(e[r])||e[r]instanceof String||Bt(t[r])||t[r]instanceof String?a&&(e[r]=t[r]):Zt(e[r],t[r],a):e[r]=t[r]);return e},ea=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var ta={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const aa=e=>Bt(e)?e.replace(/[&<>"'\/]/g,e=>ta[e]):e;const ra=[" ",",","?","!",";"],sa=new class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(void 0!==t)return t;const a=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,a),this.regExpQueue.push(e),a}}(20),na=(e,t,a=".")=>{if(!e)return;if(e[t]){if(!Object.prototype.hasOwnProperty.call(e,t))return;return e[t]}const r=t.split(a);let s=e;for(let n=0;n<r.length;){if(!s||"object"!=typeof s)return;let e,t="";for(let i=n;i<r.length;++i)if(i!==n&&(t+=a),t+=r[i],e=s[t],void 0!==e){if(["string","number","boolean"].indexOf(typeof e)>-1&&i<r.length-1)continue;n+=i-n+1;break}s=e}return s},ia=e=>e?.replace("_","-"),oa={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){}};class la{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||oa,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,a,r){return r&&!this.debug?null:(Bt(e[0])&&(e[0]=`${a}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new la(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return(e=e||this.options).prefix=e.prefix||this.prefix,new la(this.logger,e)}}var da=new la;class ca{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(e=>{this.observers[e]||(this.observers[e]=new Map);const a=this.observers[e].get(t)||0;this.observers[e].set(t,a+1)}),this}off(e,t){this.observers[e]&&(t?this.observers[e].delete(t):delete this.observers[e])}emit(e,...t){if(this.observers[e]){Array.from(this.observers[e].entries()).forEach(([e,a])=>{for(let r=0;r<a;r++)e(...t)})}if(this.observers["*"]){Array.from(this.observers["*"].entries()).forEach(([a,r])=>{for(let s=0;s<r;s++)a.apply(a,[e,...t])})}}}class ua extends ca{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,void 0===this.options.keySeparator&&(this.options.keySeparator="."),void 0===this.options.ignoreJSONStructure&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,a,r={}){const s=void 0!==r.keySeparator?r.keySeparator:this.options.keySeparator,n=void 0!==r.ignoreJSONStructure?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let i;e.indexOf(".")>-1?i=e.split("."):(i=[e,t],a&&(Array.isArray(a)?i.push(...a):Bt(a)&&s?i.push(...a.split(s)):i.push(a)));const o=Yt(this.data,i);return!o&&!t&&!a&&e.indexOf(".")>-1&&(e=i[0],t=i[1],a=i.slice(2).join(".")),!o&&n&&Bt(a)?na(this.data?.[e]?.[t],a,s):o}addResource(e,t,a,r,s={silent:!1}){const n=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator;let i=[e,t];a&&(i=i.concat(n?a.split(n):a)),e.indexOf(".")>-1&&(i=e.split("."),r=t,t=i[1]),this.addNamespaces(t),Xt(this.data,i,r),s.silent||this.emit("added",e,t,a,r)}addResources(e,t,a,r={silent:!1}){for(const s in a)(Bt(a[s])||Array.isArray(a[s]))&&this.addResource(e,t,s,a[s],{silent:!0});r.silent||this.emit("added",e,t,a)}addResourceBundle(e,t,a,r,s,n={silent:!1,skipCopy:!1}){let i=[e,t];e.indexOf(".")>-1&&(i=e.split("."),r=a,a=t,t=i[1]),this.addNamespaces(t);let o=Yt(this.data,i)||{};n.skipCopy||(a=JSON.parse(JSON.stringify(a))),r?Zt(o,a,s):o={...o,...a},Xt(this.data,i,o),n.silent||this.emit("added",e,t,a)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return void 0!==this.getResource(e,t)}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(e=>t[e]&&Object.keys(t[e]).length>0)}toJSON(){return this.data}}var ma={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,a,r,s){return e.forEach(e=>{t=this.processors[e]?.process(t,a,r,s)??t}),t}};const ha=Symbol("i18next/PATH_KEY");function pa(e,t){const{[ha]:a}=e(function(){const e=[],t=Object.create(null);let a;return t.get=(r,s)=>(a?.revoke?.(),s===ha?e:(e.push(s),a=Proxy.revocable(r,t),a.proxy)),Proxy.revocable(Object.create(null),t).proxy}());return a.join(t?.keySeparator??".")}const fa={},ga=e=>!Bt(e)&&"boolean"!=typeof e&&"number"!=typeof e;class ba extends ca{constructor(e,t={}){super(),((e,t,a)=>{e.forEach(e=>{t[e]&&(a[e]=t[e])})})(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,void 0===this.options.keySeparator&&(this.options.keySeparator="."),this.logger=da.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const a={...t};if(null==e)return!1;const r=this.resolve(e,a);if(void 0===r?.res)return!1;const s=ga(r.res);return!1!==a.returnObjects||!s}extractFromKey(e,t){let a=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===a&&(a=":");const r=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator;let s=t.ns||this.options.defaultNS||[];const n=a&&e.indexOf(a)>-1,i=!(this.options.userDefinedKeySeparator||t.keySeparator||this.options.userDefinedNsSeparator||t.nsSeparator||((e,t,a)=>{t=t||"",a=a||"";const r=ra.filter(e=>t.indexOf(e)<0&&a.indexOf(e)<0);if(0===r.length)return!0;const s=sa.getRegExp(`(${r.map(e=>"?"===e?"\\?":e).join("|")})`);let n=!s.test(e);if(!n){const t=e.indexOf(a);t>0&&!s.test(e.substring(0,t))&&(n=!0)}return n})(e,a,r));if(n&&!i){const t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:Bt(s)?[s]:s};const n=e.split(a);(a!==r||a===r&&this.options.ns.indexOf(n[0])>-1)&&(s=n.shift()),e=n.join(r)}return{key:e,namespaces:Bt(s)?[s]:s}}translate(e,t,a){let r="object"==typeof t?{...t}:t;if("object"!=typeof r&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof r&&(r={...r}),r||(r={}),null==e)return"";"function"==typeof e&&(e=pa(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]);const s=void 0!==r.returnDetails?r.returnDetails:this.options.returnDetails,n=void 0!==r.keySeparator?r.keySeparator:this.options.keySeparator,{key:i,namespaces:o}=this.extractFromKey(e[e.length-1],r),l=o[o.length-1];let d=void 0!==r.nsSeparator?r.nsSeparator:this.options.nsSeparator;void 0===d&&(d=":");const c=r.lng||this.language,u=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if("cimode"===c?.toLowerCase())return u?s?{res:`${l}${d}${i}`,usedKey:i,exactUsedKey:i,usedLng:c,usedNS:l,usedParams:this.getUsedParamsDetails(r)}:`${l}${d}${i}`:s?{res:i,usedKey:i,exactUsedKey:i,usedLng:c,usedNS:l,usedParams:this.getUsedParamsDetails(r)}:i;const m=this.resolve(e,r);let h=m?.res;const p=m?.usedKey||i,f=m?.exactUsedKey||i,g=void 0!==r.joinArrays?r.joinArrays:this.options.joinArrays,b=!this.i18nFormat||this.i18nFormat.handleAsObject,v=void 0!==r.count&&!Bt(r.count),y=ba.hasDefaultValue(r),x=v?this.pluralResolver.getSuffix(c,r.count,r):"",N=r.ordinal&&v?this.pluralResolver.getSuffix(c,r.count,{ordinal:!1}):"",w=v&&!r.ordinal&&0===r.count,k=w&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${x}`]||r[`defaultValue${N}`]||r.defaultValue;let C=h;b&&!h&&y&&(C=k);const S=ga(C),_=Object.prototype.toString.apply(C);if(!(b&&C&&S&&["[object Number]","[object Function]","[object RegExp]"].indexOf(_)<0)||Bt(g)&&Array.isArray(C))if(b&&Bt(g)&&Array.isArray(h))h=h.join(g),h&&(h=this.extendTranslation(h,e,r,a));else{let t=!1,s=!1;!this.isValidLookup(h)&&y&&(t=!0,h=k),this.isValidLookup(h)||(s=!0,h=i);const o=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&s?void 0:h,u=y&&k!==h&&this.options.updateMissing;if(s||t||u){if(this.logger.log(u?"updateKey":"missingKey",c,l,i,u?k:h),n){const e=this.resolve(i,{...r,keySeparator:!1});e&&e.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let e=[];const t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if("fallback"===this.options.saveMissingTo&&t&&t[0])for(let r=0;r<t.length;r++)e.push(t[r]);else"all"===this.options.saveMissingTo?e=this.languageUtils.toResolveHierarchy(r.lng||this.language):e.push(r.lng||this.language);const a=(e,t,a)=>{const s=y&&a!==h?a:o;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,s,u,r):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,s,u,r),this.emit("missingKey",e,l,t,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&v?e.forEach(e=>{const t=this.pluralResolver.getSuffixes(e,r);w&&r[`defaultValue${this.options.pluralSeparator}zero`]&&t.indexOf(`${this.options.pluralSeparator}zero`)<0&&t.push(`${this.options.pluralSeparator}zero`),t.forEach(t=>{a([e],i+t,r[`defaultValue${t}`]||k)})}):a(e,i,k))}h=this.extendTranslation(h,e,r,m,a),s&&h===i&&this.options.appendNamespaceToMissingKey&&(h=`${l}${d}${i}`),(s||t)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${d}${i}`:i,t?h:void 0,r))}else{if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(p,C,{...r,ns:o}):`key '${i} (${this.language})' returned an object instead of string.`;return s?(m.res=e,m.usedParams=this.getUsedParamsDetails(r),m):e}if(n){const e=Array.isArray(C),t=e?[]:{},a=e?f:p;for(const s in C)if(Object.prototype.hasOwnProperty.call(C,s)){const e=`${a}${n}${s}`;t[s]=y&&!h?this.translate(e,{...r,defaultValue:ga(k)?k[s]:void 0,joinArrays:!1,ns:o}):this.translate(e,{...r,joinArrays:!1,ns:o}),t[s]===e&&(t[s]=C[s])}h=t}}return s?(m.res=h,m.usedParams=this.getUsedParamsDetails(r),m):h}extendTranslation(e,t,a,r,s){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...a},a.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init({...a,interpolation:{...this.options.interpolation,...a.interpolation}});const n=Bt(e)&&(void 0!==a?.interpolation?.skipOnVariables?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let i;if(n){const t=e.match(this.interpolator.nestingRegexp);i=t&&t.length}let o=a.replace&&!Bt(a.replace)?a.replace:a;if(this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),e=this.interpolator.interpolate(e,o,a.lng||this.language||r.usedLng,a),n){const t=e.match(this.interpolator.nestingRegexp);i<(t&&t.length)&&(a.nest=!1)}!a.lng&&r&&r.res&&(a.lng=this.language||r.usedLng),!1!==a.nest&&(e=this.interpolator.nest(e,(...e)=>s?.[0]!==e[0]||a.context?this.translate(...e,t):(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null),a)),a.interpolation&&this.interpolator.reset()}const n=a.postProcess||this.options.postProcess,i=Bt(n)?[n]:n;return null!=e&&i?.length&&!1!==a.applyPostProcessor&&(e=ma.handle(i,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(a)},...a}:a,this)),e}resolve(e,t={}){let a,r,s,n,i;return Bt(e)&&(e=[e]),e.forEach(e=>{if(this.isValidLookup(a))return;const o=this.extractFromKey(e,t),l=o.key;r=l;let d=o.namespaces;this.options.fallbackNS&&(d=d.concat(this.options.fallbackNS));const c=void 0!==t.count&&!Bt(t.count),u=c&&!t.ordinal&&0===t.count,m=void 0!==t.context&&(Bt(t.context)||"number"==typeof t.context)&&""!==t.context,h=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);d.forEach(e=>{this.isValidLookup(a)||(i=e,fa[`${h[0]}-${e}`]||!this.utils?.hasLoadedNamespace||this.utils?.hasLoadedNamespace(i)||(fa[`${h[0]}-${e}`]=!0,this.logger.warn(`key "${r}" for languages "${h.join(", ")}" won't get resolved as namespace "${i}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),h.forEach(r=>{if(this.isValidLookup(a))return;n=r;const i=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(i,l,r,e,t);else{let e;c&&(e=this.pluralResolver.getSuffix(r,t.count,t));const a=`${this.options.pluralSeparator}zero`,s=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(c&&(t.ordinal&&0===e.indexOf(s)&&i.push(l+e.replace(s,this.options.pluralSeparator)),i.push(l+e),u&&i.push(l+a)),m){const r=`${l}${this.options.contextSeparator||"_"}${t.context}`;i.push(r),c&&(t.ordinal&&0===e.indexOf(s)&&i.push(r+e.replace(s,this.options.pluralSeparator)),i.push(r+e),u&&i.push(r+a))}}let o;for(;o=i.pop();)this.isValidLookup(a)||(s=o,a=this.getResource(r,e,o,t))}))})}),{res:a,usedKey:r,exactUsedKey:s,usedLng:n,usedNS:i}}isValidLookup(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}getResource(e,t,a,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,a,r):this.resourceStore.getResource(e,t,a,r)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],a=e.replace&&!Bt(e.replace);let r=a?e.replace:e;if(a&&void 0!==e.count&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!a){r={...r};for(const e of t)delete r[e]}return r}static hasDefaultValue(e){const t="defaultValue";for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t===a.substring(0,12)&&void 0!==e[a])return!0;return!1}}class va{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=da.create("languageUtils")}getScriptPartFromCode(e){if(!(e=ia(e))||e.indexOf("-")<0)return null;const t=e.split("-");return 2===t.length?null:(t.pop(),"x"===t[t.length-1].toLowerCase()?null:this.formatLanguageCode(t.join("-")))}getLanguagePartFromCode(e){if(!(e=ia(e))||e.indexOf("-")<0)return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(Bt(e)&&e.indexOf("-")>-1){let a;try{a=Intl.getCanonicalLocales(e)[0]}catch(t){}return a&&this.options.lowerCaseLng&&(a=a.toLowerCase()),a||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(e=>{if(t)return;const a=this.formatLanguageCode(e);this.options.supportedLngs&&!this.isSupportedCode(a)||(t=a)}),!t&&this.options.supportedLngs&&e.forEach(e=>{if(t)return;const a=this.getScriptPartFromCode(e);if(this.isSupportedCode(a))return t=a;const r=this.getLanguagePartFromCode(e);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(e=>e===r?e:e.indexOf("-")<0&&r.indexOf("-")<0?void 0:e.indexOf("-")>0&&r.indexOf("-")<0&&e.substring(0,e.indexOf("-"))===r||0===e.indexOf(r)&&r.length>1?e:void 0)}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),Bt(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let a=e[t];return a||(a=e[this.getScriptPartFromCode(t)]),a||(a=e[this.formatLanguageCode(t)]),a||(a=e[this.getLanguagePartFromCode(t)]),a||(a=e.default),a||[]}toResolveHierarchy(e,t){const a=this.getFallbackCodes((!1===t?[]:t)||this.options.fallbackLng||[],e),r=[],s=e=>{e&&(this.isSupportedCode(e)?r.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return Bt(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?("languageOnly"!==this.options.load&&s(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&s(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&s(this.getLanguagePartFromCode(e))):Bt(e)&&s(this.formatLanguageCode(e)),a.forEach(e=>{r.indexOf(e)<0&&s(this.formatLanguageCode(e))}),r}}const ya={zero:0,one:1,two:2,few:3,many:4,other:5},xa={select:e=>1===e?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Na{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=da.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,t){this.rules[e]=t}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const a=ia("dev"===e?"en":e),r=t.ordinal?"ordinal":"cardinal",s=JSON.stringify({cleanedCode:a,type:r});if(s in this.pluralRulesCache)return this.pluralRulesCache[s];let n;try{n=new Intl.PluralRules(a,{type:r})}catch(i){if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),xa;if(!e.match(/-|_/))return xa;const a=this.languageUtils.getLanguagePartFromCode(e);n=this.getRule(a,t)}return this.pluralRulesCache[s]=n,n}needsPlural(e,t={}){let a=this.getRule(e,t);return a||(a=this.getRule("dev",t)),a?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,a={}){return this.getSuffixes(e,a).map(e=>`${t}${e}`)}getSuffixes(e,t={}){let a=this.getRule(e,t);return a||(a=this.getRule("dev",t)),a?a.resolvedOptions().pluralCategories.sort((e,t)=>ya[e]-ya[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${e}`):[]}getSuffix(e,t,a={}){const r=this.getRule(e,a);return r?`${this.options.prepend}${a.ordinal?`ordinal${this.options.prepend}`:""}${r.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,a))}}const wa=(e,t,a,r=".",s=!0)=>{let n=((e,t,a)=>{const r=Yt(e,a);return void 0!==r?r:Yt(t,a)})(e,t,a);return!n&&s&&Bt(a)&&(n=na(e,a,r),void 0===n&&(n=na(t,a,r))),n},ka=e=>e.replace(/\$/g,"$$$$");class Ca{constructor(e={}){this.logger=da.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:a,useRawValueToEscape:r,prefix:s,prefixEscaped:n,suffix:i,suffixEscaped:o,formatSeparator:l,unescapeSuffix:d,unescapePrefix:c,nestingPrefix:u,nestingPrefixEscaped:m,nestingSuffix:h,nestingSuffixEscaped:p,nestingOptionsSeparator:f,maxReplaces:g,alwaysFormat:b}=e.interpolation;this.escape=void 0!==t?t:aa,this.escapeValue=void 0===a||a,this.useRawValueToEscape=void 0!==r&&r,this.prefix=s?ea(s):n||"{{",this.suffix=i?ea(i):o||"}}",this.formatSeparator=l||",",this.unescapePrefix=d?"":c||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=u?ea(u):m||ea("$t("),this.nestingSuffix=h?ea(h):p||ea(")"),this.nestingOptionsSeparator=f||",",this.maxReplaces=g||1e3,this.alwaysFormat=void 0!==b&&b,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(e,t)=>e?.source===t?(e.lastIndex=0,e):new RegExp(t,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,a,r){let s,n,i;const o=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=e=>{if(e.indexOf(this.formatSeparator)<0){const s=wa(t,o,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(s,void 0,a,{...r,...t,interpolationkey:e}):s}const s=e.split(this.formatSeparator),n=s.shift().trim(),i=s.join(this.formatSeparator).trim();return this.format(wa(t,o,n,this.options.keySeparator,this.options.ignoreJSONStructure),i,a,{...r,...t,interpolationkey:n})};this.resetRegExp();const d=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,c=void 0!==r?.interpolation?.skipOnVariables?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>ka(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?ka(this.escape(e)):ka(e)}].forEach(t=>{for(i=0;s=t.regex.exec(e);){const a=s[1].trim();if(n=l(a),void 0===n)if("function"==typeof d){const t=d(e,s,r);n=Bt(t)?t:""}else if(r&&Object.prototype.hasOwnProperty.call(r,a))n="";else{if(c){n=s[0];continue}this.logger.warn(`missed to pass in variable ${a} for interpolating ${e}`),n=""}else Bt(n)||this.useRawValueToEscape||(n=Ht(n));const o=t.safeValue(n);if(e=e.replace(s[0],o),c?(t.regex.lastIndex+=n.length,t.regex.lastIndex-=s[0].length):t.regex.lastIndex=0,i++,i>=this.maxReplaces)break}}),e}nest(e,t,a={}){let r,s,n;const i=(e,t)=>{const a=this.nestingOptionsSeparator;if(e.indexOf(a)<0)return e;const r=e.split(new RegExp(`${a}[ ]*{`));let s=`{${r[1]}`;e=r[0],s=this.interpolate(s,n);const i=s.match(/'/g),o=s.match(/"/g);((i?.length??0)%2==0&&!o||o.length%2!=0)&&(s=s.replace(/'/g,'"'));try{n=JSON.parse(s),t&&(n={...t,...n})}catch(l){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,l),`${e}${a}${s}`}return n.defaultValue&&n.defaultValue.indexOf(this.prefix)>-1&&delete n.defaultValue,e};for(;r=this.nestingRegexp.exec(e);){let o=[];n={...a},n=n.replace&&!Bt(n.replace)?n.replace:n,n.applyPostProcessor=!1,delete n.defaultValue;const l=/{.*}/.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(-1!==l&&(o=r[1].slice(l).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),r[1]=r[1].slice(0,l)),s=t(i.call(this,r[1].trim(),n),n),s&&r[0]===e&&!Bt(s))return s;Bt(s)||(s=Ht(s)),s||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),s=""),o.length&&(s=o.reduce((e,t)=>this.format(e,t,a.lng,{...a,interpolationkey:r[1].trim()}),s.trim())),e=e.replace(r[0],s),this.regexp.lastIndex=0}return e}}const Sa=e=>{const t={};return(a,r,s)=>{let n=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(n={...n,[s.interpolationkey]:void 0});const i=r+JSON.stringify(n);let o=t[i];return o||(o=e(ia(r),s),t[i]=o),o(a)}},_a=e=>(t,a,r)=>e(ia(a),r)(t);class Pa{constructor(e={}){this.logger=da.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const a=t.cacheInBuiltFormats?Sa:_a;this.formats={number:a((e,t)=>{const a=new Intl.NumberFormat(e,{...t});return e=>a.format(e)}),currency:a((e,t)=>{const a=new Intl.NumberFormat(e,{...t,style:"currency"});return e=>a.format(e)}),datetime:a((e,t)=>{const a=new Intl.DateTimeFormat(e,{...t});return e=>a.format(e)}),relativetime:a((e,t)=>{const a=new Intl.RelativeTimeFormat(e,{...t});return e=>a.format(e,t.range||"day")}),list:a((e,t)=>{const a=new Intl.ListFormat(e,{...t});return e=>a.format(e)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Sa(t)}format(e,t,a,r={}){const s=t.split(this.formatSeparator);if(s.length>1&&s[0].indexOf("(")>1&&s[0].indexOf(")")<0&&s.find(e=>e.indexOf(")")>-1)){const e=s.findIndex(e=>e.indexOf(")")>-1);s[0]=[s[0],...s.splice(1,e)].join(this.formatSeparator)}return s.reduce((e,t)=>{const{formatName:s,formatOptions:n}=(e=>{let t=e.toLowerCase().trim();const a={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);"currency"===t&&s.indexOf(":")<0?a.currency||(a.currency=s.trim()):"relativetime"===t&&s.indexOf(":")<0?a.range||(a.range=s.trim()):s.split(";").forEach(e=>{if(e){const[t,...r]=e.split(":"),s=r.join(":").trim().replace(/^'+|'+$/g,""),n=t.trim();a[n]||(a[n]=s),"false"===s&&(a[n]=!1),"true"===s&&(a[n]=!0),isNaN(s)||(a[n]=parseInt(s,10))}})}return{formatName:t,formatOptions:a}})(t);if(this.formats[s]){let t=e;try{const i=r?.formatParams?.[r.interpolationkey]||{},o=i.locale||i.lng||r.locale||r.lng||a;t=this.formats[s](e,o,{...n,...r,...i})}catch(i){this.logger.warn(i)}return t}return this.logger.warn(`there was no format function for ${s}`),e},e)}}class Ea extends ca{constructor(e,t,a,r={}){super(),this.backend=e,this.store=t,this.services=a,this.languageUtils=a.languageUtils,this.options=r,this.logger=da.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(a,r.backend,r)}queueLoad(e,t,a,r){const s={},n={},i={},o={};return e.forEach(e=>{let r=!0;t.forEach(t=>{const i=`${e}|${t}`;!a.reload&&this.store.hasResourceBundle(e,t)?this.state[i]=2:this.state[i]<0||(1===this.state[i]?void 0===n[i]&&(n[i]=!0):(this.state[i]=1,r=!1,void 0===n[i]&&(n[i]=!0),void 0===s[i]&&(s[i]=!0),void 0===o[t]&&(o[t]=!0)))}),r||(i[e]=!0)}),(Object.keys(s).length||Object.keys(n).length)&&this.queue.push({pending:n,pendingCount:Object.keys(n).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(s),pending:Object.keys(n),toLoadLanguages:Object.keys(i),toLoadNamespaces:Object.keys(o)}}loaded(e,t,a){const r=e.split("|"),s=r[0],n=r[1];t&&this.emit("failedLoading",s,n,t),!t&&a&&this.store.addResourceBundle(s,n,a,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&a&&(this.state[e]=0);const i={};this.queue.forEach(a=>{((e,t,a)=>{const{obj:r,k:s}=Jt(e,t,Object);r[s]=r[s]||[],r[s].push(a)})(a.loaded,[s],n),((e,t)=>{void 0!==e.pending[t]&&(delete e.pending[t],e.pendingCount--)})(a,e),t&&a.errors.push(t),0!==a.pendingCount||a.done||(Object.keys(a.loaded).forEach(e=>{i[e]||(i[e]={});const t=a.loaded[e];t.length&&t.forEach(t=>{void 0===i[e][t]&&(i[e][t]=!0)})}),a.done=!0,a.errors.length?a.callback(a.errors):a.callback())}),this.emit("loaded",i),this.queue=this.queue.filter(e=>!e.done)}read(e,t,a,r=0,s=this.retryTimeout,n){if(!e.length)return n(null,{});if(this.readingCalls>=this.maxParallelReads)return void this.waitingReads.push({lng:e,ns:t,fcName:a,tried:r,wait:s,callback:n});this.readingCalls++;const i=(i,o)=>{if(this.readingCalls--,this.waitingReads.length>0){const e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}i&&o&&r<this.maxRetries?setTimeout(()=>{this.read.call(this,e,t,a,r+1,2*s,n)},s):n(i,o)},o=this.backend[a].bind(this.backend);if(2!==o.length)return o(e,t,i);try{const a=o(e,t);a&&"function"==typeof a.then?a.then(e=>i(null,e)).catch(i):i(null,a)}catch(l){i(l)}}prepareLoading(e,t,a={},r){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();Bt(e)&&(e=this.languageUtils.toResolveHierarchy(e)),Bt(t)&&(t=[t]);const s=this.queueLoad(e,t,a,r);if(!s.toLoad.length)return s.pending.length||r(),null;s.toLoad.forEach(e=>{this.loadOne(e)})}load(e,t,a){this.prepareLoading(e,t,{},a)}reload(e,t,a){this.prepareLoading(e,t,{reload:!0},a)}loadOne(e,t=""){const a=e.split("|"),r=a[0],s=a[1];this.read(r,s,"read",void 0,void 0,(a,n)=>{a&&this.logger.warn(`${t}loading namespace ${s} for language ${r} failed`,a),!a&&n&&this.logger.log(`${t}loaded namespace ${s} for language ${r}`,n),this.loaded(e,a,n)})}saveMissing(e,t,a,r,s,n={},i=()=>{}){if(!this.services?.utils?.hasLoadedNamespace||this.services?.utils?.hasLoadedNamespace(t)){if(null!=a&&""!==a){if(this.backend?.create){const l={...n,isUpdate:s},d=this.backend.create.bind(this.backend);if(d.length<6)try{let s;s=5===d.length?d(e,t,a,r,l):d(e,t,a,r),s&&"function"==typeof s.then?s.then(e=>i(null,e)).catch(i):i(null,s)}catch(o){i(o)}else d(e,t,a,r,i,l)}e&&e[0]&&this.store.addResource(e[0],t,a,r)}}else this.logger.warn(`did not save key "${a}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")}}const Ia=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if("object"==typeof e[1]&&(t=e[1]),Bt(e[1])&&(t.defaultValue=e[1]),Bt(e[2])&&(t.tDescription=e[2]),"object"==typeof e[2]||"object"==typeof e[3]){const a=e[3]||e[2];Object.keys(a).forEach(e=>{t[e]=a[e]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Ta=e=>(Bt(e.ns)&&(e.ns=[e.ns]),Bt(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),Bt(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),"boolean"==typeof e.initImmediate&&(e.initAsync=e.initImmediate),e),Aa=()=>{};class Ra extends ca{constructor(e={},t){var a;if(super(),this.options=Ta(e),this.services={},this.logger=da,this.modules={external:[]},a=this,Object.getOwnPropertyNames(Object.getPrototypeOf(a)).forEach(e=>{"function"==typeof a[e]&&(a[e]=a[e].bind(a))}),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,"function"==typeof e&&(t=e,e={}),null==e.defaultNS&&e.ns&&(Bt(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const a=Ia();this.options={...a,...this.options,...Ta(e)},this.options.interpolation={...a.interpolation,...this.options.interpolation},void 0!==e.keySeparator&&(this.options.userDefinedKeySeparator=e.keySeparator),void 0!==e.nsSeparator&&(this.options.userDefinedNsSeparator=e.nsSeparator);const r=e=>e?"function"==typeof e?new e:e:null;if(!this.options.isClone){let e;this.modules.logger?da.init(r(this.modules.logger),this.options):da.init(null,this.options),e=this.modules.formatter?this.modules.formatter:Pa;const t=new va(this.options);this.store=new ua(this.options.resources,this.options);const s=this.services;s.logger=da,s.resourceStore=this.store,s.languageUtils=t,s.pluralResolver=new Na(t,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix});this.options.interpolation.format&&this.options.interpolation.format!==a.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),!e||this.options.interpolation.format&&this.options.interpolation.format!==a.interpolation.format||(s.formatter=r(e),s.formatter.init&&s.formatter.init(s,this.options),this.options.interpolation.format=s.formatter.format.bind(s.formatter)),s.interpolator=new Ca(this.options),s.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},s.backendConnector=new Ea(r(this.modules.backend),s.resourceStore,s,this.options),s.backendConnector.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(s.languageDetector=r(this.modules.languageDetector),s.languageDetector.init&&s.languageDetector.init(s,this.options.detection,this.options)),this.modules.i18nFormat&&(s.i18nFormat=r(this.modules.i18nFormat),s.i18nFormat.init&&s.i18nFormat.init(this)),this.translator=new ba(this.services,this.options),this.translator.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.external.forEach(e=>{e.init&&e.init(this)})}if(this.format=this.options.interpolation.format,t||(t=Aa),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&"dev"!==e[0]&&(this.options.lng=e[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(e=>{this[e]=(...t)=>this.store[e](...t)});["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(e=>{this[e]=(...t)=>(this.store[e](...t),this)});const s=Wt(),n=()=>{const e=(e,a)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),s.resolve(a),t(e,a)};if(this.languages&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?n():setTimeout(n,0),s}loadResources(e,t=Aa){let a=t;const r=Bt(e)?e:this.language;if("function"==typeof e&&(a=e),!this.options.resources||this.options.partialBundledLanguages){if("cimode"===r?.toLowerCase()&&(!this.options.preload||0===this.options.preload.length))return a();const e=[],t=t=>{if(!t)return;if("cimode"===t)return;this.services.languageUtils.toResolveHierarchy(t).forEach(t=>{"cimode"!==t&&e.indexOf(t)<0&&e.push(t)})};if(r)t(r);else{this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(e=>t(e))}this.options.preload?.forEach?.(e=>t(e)),this.services.backendConnector.load(e,this.options.ns,e=>{e||this.resolvedLanguage||!this.language||this.setResolvedLanguage(this.language),a(e)})}else a(null)}reloadResources(e,t,a){const r=Wt();return"function"==typeof e&&(a=e,e=void 0),"function"==typeof t&&(a=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),a||(a=Aa),this.services.backendConnector.reload(e,t,e=>{r.resolve(),a(e)}),r}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&ma.addPostProcessor(e),"formatter"===e.type&&(this.modules.formatter=e),"3rdParty"===e.type&&this.modules.external.push(e),this}setResolvedLanguage(e){if(e&&this.languages&&!(["cimode","dev"].indexOf(e)>-1)){for(let e=0;e<this.languages.length;e++){const t=this.languages[e];if(!(["cimode","dev"].indexOf(t)>-1)&&this.store.hasLanguageSomeTranslations(t)){this.resolvedLanguage=t;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;const a=Wt();this.emit("languageChanging",e);const r=e=>{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},s=(s,n)=>{n?this.isLanguageChangingTo===e&&(r(n),this.translator.changeLanguage(n),this.isLanguageChangingTo=void 0,this.emit("languageChanged",n),this.logger.log("languageChanged",n)):this.isLanguageChangingTo=void 0,a.resolve((...e)=>this.t(...e)),t&&t(s,(...e)=>this.t(...e))},n=t=>{e||t||!this.services.languageDetector||(t=[]);const a=Bt(t)?t:t&&t[0],n=this.store.hasLanguageSomeTranslations(a)?a:this.services.languageUtils.getBestMatchFromCodes(Bt(t)?[t]:t);n&&(this.language||r(n),this.translator.language||this.translator.changeLanguage(n),this.services.languageDetector?.cacheUserLanguage?.(n)),this.loadResources(n,e=>{s(e,n)})};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(n):this.services.languageDetector.detect(n):n(e):n(this.services.languageDetector.detect()),a}getFixedT(e,t,a){const r=(e,t,...s)=>{let n;n="object"!=typeof t?this.options.overloadTranslationOptionHandler([e,t].concat(s)):{...t},n.lng=n.lng||r.lng,n.lngs=n.lngs||r.lngs,n.ns=n.ns||r.ns,""!==n.keyPrefix&&(n.keyPrefix=n.keyPrefix||a||r.keyPrefix);const i=this.options.keySeparator||".";let o;return n.keyPrefix&&Array.isArray(e)?o=e.map(e=>("function"==typeof e&&(e=pa(e,{...this.options,...t})),`${n.keyPrefix}${i}${e}`)):("function"==typeof e&&(e=pa(e,{...this.options,...t})),o=n.keyPrefix?`${n.keyPrefix}${i}${e}`:e),this.t(o,n)};return Bt(e)?r.lng=e:r.lngs=e,r.ns=t,r.keyPrefix=a,r}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const a=t.lng||this.resolvedLanguage||this.languages[0],r=!!this.options&&this.options.fallbackLng,s=this.languages[this.languages.length-1];if("cimode"===a.toLowerCase())return!0;const n=(e,t)=>{const a=this.services.backendConnector.state[`${e}|${t}`];return-1===a||0===a||2===a};if(t.precheck){const e=t.precheck(this,n);if(void 0!==e)return e}return!!this.hasResourceBundle(a,e)||(!(this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages))||!(!n(a,e)||r&&!n(s,e)))}loadNamespaces(e,t){const a=Wt();return this.options.ns?(Bt(e)&&(e=[e]),e.forEach(e=>{this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}),this.loadResources(e=>{a.resolve(),t&&t(e)}),a):(t&&t(),Promise.resolve())}loadLanguages(e,t){const a=Wt();Bt(e)&&(e=[e]);const r=this.options.preload||[],s=e.filter(e=>r.indexOf(e)<0&&this.services.languageUtils.isSupportedCode(e));return s.length?(this.options.preload=r.concat(s),this.loadResources(e=>{a.resolve(),t&&t(e)}),a):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const t=new Intl.Locale(e);if(t&&t.getTextInfo){const e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch(a){}const t=this.services?.languageUtils||new va(Ia());return e.toLowerCase().indexOf("-latn")>1?"ltr":["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(t.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){const a=new Ra(e,t);return a.createInstance=Ra.createInstance,a}cloneInstance(e={},t=Aa){const a=e.forkResourceStore;a&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},s=new Ra(r);void 0===e.debug&&void 0===e.prefix||(s.logger=s.logger.clone(e));if(["store","services","language"].forEach(e=>{s[e]=this[e]}),s.services={...this.services},s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},a){const e=Object.keys(this.store.data).reduce((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce((a,r)=>(a[r]={...e[t][r]},a),e[t]),e),{});s.store=new ua(e,r),s.services.resourceStore=s.store}return s.translator=new ba(s.services,r),s.translator.on("*",(e,...t)=>{s.emit(e,...t)}),s.init(r,t),s.translator.options=r,s.translator.backendConnector.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Oa=Ra.createInstance();function La(e,t){t?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{w.info(Oa.t("link_copied"))})}function Fa(...e){return v(b(e))}Oa.createInstance,Oa.dir,Oa.init,Oa.loadResources,Oa.reloadResources,Oa.use,Oa.changeLanguage,Oa.getFixedT,Oa.t,Oa.exists,Oa.setDefaultNamespace,Oa.hasLoadedNamespace,Oa.loadNamespaces,Oa.loadLanguages;const ja=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(ja);if("object"==typeof e&&e.constructor===Object){const t={};for(const[a,r]of Object.entries(e))t[a]=ja(r);return t}return e},Ma=e=>{if(!e)return"";const t=y(e);if(!x(t))return"Data inválida";return`${t.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",timeZone:"America/Sao_Paulo"})} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"})}`},za=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),Da=(e,t)=>{let a;return(...r)=>{clearTimeout(a),a=setTimeout(()=>e(...r),t)}},$a=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Ua=g("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),Va=r.forwardRef(({className:t,variant:a,size:r,asChild:s=!1,...n},i)=>e(s?f:"button",{className:Fa(Ua({variant:a,size:r,className:t})),ref:i,...n}));Va.displayName="Button";const qa=s.forwardRef(({variant:t="default",className:a,children:r,...s},n)=>e(Va,{ref:n,variant:"action",size:"sm",className:Fa("h-7 px-2 text-xs",a),...s,children:r||e(C,{size:12})}));qa.displayName="ActionButton";const Ba=r.forwardRef(({className:t,type:a,...r},s)=>e("input",{type:a,className:Fa("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:s,...r}));Ba.displayName="Input";const Wa=g("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ha=r.forwardRef(({className:t,...a},r)=>e(et.Root,{ref:r,className:Fa(Wa(),t),...a}));Ha.displayName=et.Root.displayName;const Ka=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));Ka.displayName="Card";const Ga=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("flex flex-col space-y-1.5 p-6",t),...a}));Ga.displayName="CardHeader";const Qa=r.forwardRef(({className:t,...a},r)=>e("h3",{ref:r,className:Fa("text-2xl font-semibold leading-none tracking-tight",t),...a}));Qa.displayName="CardTitle";const Ja=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:Fa("text-sm text-muted-foreground",t),...a}));Ja.displayName="CardDescription";const Xa=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("p-6 pt-0",t),...a}));Xa.displayName="CardContent";const Ya=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("flex items-center p-6 pt-0",t),...a}));Ya.displayName="CardFooter";const Za=r.forwardRef(({className:t,orientation:a="horizontal",decorative:r=!0,...s},n)=>e(at.Root,{ref:n,decorative:r,orientation:a,className:Fa("shrink-0 bg-border","horizontal"===a?"h-[1px] w-full":"h-full w-[1px]",t),...s}));Za.displayName=at.Root.displayName;const er=tt.Root,tr=tt.Trigger,ar=tt.Portal,rr=tt.Close,sr=r.forwardRef(({className:t,...a},r)=>e(tt.Overlay,{ref:r,className:Fa("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a}));sr.displayName=tt.Overlay.displayName;const nr=r.forwardRef(({className:a,children:r,...s},n)=>t(ar,{children:[e(sr,{}),t(tt.Content,{ref:n,className:Fa("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-[85vw] max-h-[85vh] translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...s,children:[r,t(tt.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));nr.displayName=tt.Content.displayName;const ir=({className:a,showSeparator:r=!1,children:s,...n})=>t("div",{className:Fa("flex flex-col flex-shrink-0",a),...n,children:[e("div",{className:"flex flex-col text-left",children:s}),r&&e(Za,{className:"mt-2"})]});ir.displayName="DialogHeader";const or=({className:t,...a})=>e("div",{className:Fa("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});or.displayName="DialogBody";const lr=({className:a,children:r,...s})=>t("div",{className:"flex-shrink-0 pt-4",children:[e(Za,{className:"mb-4"}),e("div",{className:Fa("flex flex-row justify-end gap-2",a),...s,children:r})]});lr.displayName="DialogFooter";const dr=r.forwardRef(({className:t,...a},r)=>e(tt.Title,{ref:r,className:Fa("text-lg font-semibold leading-none tracking-tight",t),...a}));dr.displayName=tt.Title.displayName;const cr=r.forwardRef(({className:t,...a},r)=>e(tt.Description,{ref:r,className:Fa("text-sm text-muted-foreground",t),...a}));cr.displayName=tt.Description.displayName;const ur=st,mr=r.createContext({}),hr=({...t})=>e(mr.Provider,{value:{name:t.name},children:e(nt,{...t})}),pr=()=>{const e=r.useContext(mr),t=r.useContext(fr),{getFieldState:a,formState:s}=rt(),n=a(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...n}},fr=r.createContext({}),gr=r.forwardRef(({className:t,...a},s)=>{const n=r.useId();return e(fr.Provider,{value:{id:n},children:e("div",{ref:s,className:Fa("space-y-2",t),...a})})});gr.displayName="FormItem";const br=r.forwardRef(({className:t,...a},r)=>{const{error:s,formItemId:n}=pr();return e(Ha,{ref:r,className:Fa(s&&"text-destructive",t),htmlFor:n,...a})});br.displayName="FormLabel";const vr=r.forwardRef(({...t},a)=>{const{error:r,formItemId:s,formDescriptionId:n,formMessageId:i}=pr();return e(f,{ref:a,id:s,"aria-describedby":r?`${n} ${i}`:`${n}`,"aria-invalid":!!r,...t})});vr.displayName="FormControl";const yr=r.forwardRef(({className:t,...a},r)=>{const{formDescriptionId:s}=pr();return e("p",{ref:r,id:s,className:Fa("text-sm text-muted-foreground",t),...a})});yr.displayName="FormDescription";const xr=r.forwardRef(({className:t,children:a,...r},s)=>{const{error:n,formMessageId:i}=pr(),o=n?String(n?.message):a;return o?e("p",{ref:s,id:i,className:Fa("text-sm font-medium text-destructive",t),...r,children:o}):null});xr.displayName="FormMessage";const Nr=lt.Root,wr=lt.Group,kr=lt.Value,Cr=r.forwardRef(({className:a,children:r,...s},n)=>t(lt.Trigger,{ref:n,className:Fa("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",a),...s,children:[r,e(lt.Icon,{asChild:!0,children:e(_,{className:"h-4 w-4 opacity-50"})})]}));Cr.displayName=lt.Trigger.displayName;const Sr=r.forwardRef(({className:t,...a},r)=>e(lt.ScrollUpButton,{ref:r,className:Fa("flex cursor-default items-center justify-center py-1",t),...a,children:e(P,{className:"h-4 w-4"})}));Sr.displayName=lt.ScrollUpButton.displayName;const _r=r.forwardRef(({className:t,...a},r)=>e(lt.ScrollDownButton,{ref:r,className:Fa("flex cursor-default items-center justify-center py-1",t),...a,children:e(_,{className:"h-4 w-4"})}));_r.displayName=lt.ScrollDownButton.displayName;const Pr=r.forwardRef(({className:a,children:r,position:s="popper",container:n,collisionBoundary:i,...o},l)=>e(lt.Portal,{container:n,children:t(lt.Content,{ref:l,className:Fa("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:s,collisionBoundary:i,...o,children:[e(Sr,{}),e(lt.Viewport,{className:Fa("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(_r,{})]})}));Pr.displayName=lt.Content.displayName;const Er=r.forwardRef(({className:t,...a},r)=>e(lt.Label,{ref:r,className:Fa("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a}));Er.displayName=lt.Label.displayName;const Ir=r.forwardRef(({className:a,children:r,...s},n)=>t(lt.Item,{ref:n,className:Fa("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(lt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),e(lt.ItemText,{children:r})]}));Ir.displayName=lt.Item.displayName;const Tr=r.forwardRef(({className:t,...a},r)=>e(lt.Separator,{ref:r,className:Fa("-mx-1 my-1 h-px bg-muted",t),...a}));Tr.displayName=lt.Separator.displayName;const Ar=r.forwardRef(({className:t,...a},r)=>e(dt.Root,{ref:r,className:Fa("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",t),...a,children:e(dt.Indicator,{className:Fa("flex items-center justify-center text-current"),children:e(E,{className:"h-4 w-4"})})}));Ar.displayName=dt.Root.displayName;const Rr=r.forwardRef(({className:t,...a},r)=>e("textarea",{className:Fa("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:r,...a}));Rr.displayName="Textarea";const Or=g("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-green-500 text-white hover:bg-green-600",warning:"border-transparent bg-yellow-500 text-white hover:bg-yellow-600",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-white hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Lr=r.forwardRef(({className:t,variant:a,...r},s)=>e("div",{ref:s,className:Fa(Or({variant:a}),t),...r}));Lr.displayName="Badge";const Fr={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function jr({size:t="md",className:a}){return e(I,{className:Fa("animate-spin text-muted-foreground",Fr[t],a)})}function Mr({isLoading:r,children:s,className:n,type:i="spinner",size:o="md"}){return r?"overlay"===i?t("div",{className:Fa("relative",n),children:[s,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(jr,{size:o})})]}):e("div","skeleton"===i?{className:Fa("animate-pulse",n),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Fa("flex items-center justify-center py-8",n),children:e(jr,{size:o})}):e(a,{children:s})}const zr=({...t})=>e(k,{className:"toaster group",position:"top-center",expand:!1,closeButton:!0,icons:{success:e(L,{className:"h-4 w-4"}),info:e(O,{className:"h-4 w-4"}),warning:e(R,{className:"h-4 w-4"}),error:e(A,{className:"h-4 w-4"}),loading:e(T,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-[#E0FBE8] !border-[#E0FBE8]",error:"!bg-[#FEE1E1] !border-[#FEE1E1]",warning:"!bg-[#FEF3C8] !border-[#FEF3C8]",info:"!bg-[#FFFFFF] !border-border"}},...t}),Dr=ct.Root,$r=ct.Trigger,Ur=r.forwardRef(({className:t,align:a="center",sideOffset:r=4,container:s,...n},i)=>e(ct.Portal,{container:s,children:e(ct.Content,{ref:i,align:a,sideOffset:r,className:Fa("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n})}));Ur.displayName=ct.Content.displayName;const Vr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...a}));Vr.displayName="Command";const qr=({children:t,...a})=>e("div",{...a,children:e(Vr,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:t})}),Br=r.forwardRef(({className:t,...a},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:Fa("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",t),...a})}));Br.displayName="CommandInput";const Wr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...a}));Wr.displayName="CommandList";const Hr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("py-6 text-center text-sm text-muted-foreground",t),...a}));Hr.displayName="CommandEmpty";const Kr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...a}));Kr.displayName="CommandGroup";const Gr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("-mx-1 h-px bg-border",t),...a}));Gr.displayName="CommandSeparator";const Qr=r.forwardRef(({className:t,disabled:a,onSelect:r,value:s,...n},i)=>e("div",{ref:i,className:Fa("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",t),"data-disabled":a,onClick:()=>!a&&r?.(s||""),...n}));Qr.displayName="CommandItem";const Jr=({className:t,...a})=>e("span",{className:Fa("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});function Xr({className:t,...a}){return e("div",{className:Fa("animate-pulse rounded-md bg-muted",t),...a})}Jr.displayName="CommandShortcut";const Yr={},Zr=(e,t,a,r)=>{rs(a)&&Yr[a]||(rs(a)&&(Yr[a]=new Date),((e,t,a,r)=>{const s=[a,{code:t,...r||{}}];if(e?.services?.logger?.forward)return e.services.logger.forward(s,"warn","react-i18next::",!0);rs(s[0])&&(s[0]=`react-i18next:: ${s[0]}`),e?.services?.logger?.warn?e.services.logger.warn(...s):console})(e,t,a,r))},es=(e,t)=>()=>{if(e.isInitialized)t();else{const a=()=>{setTimeout(()=>{e.off("initialized",a)},0),t()};e.on("initialized",a)}},ts=(e,t,a)=>{e.loadNamespaces(t,es(e,a))},as=(e,t,a,r)=>{if(rs(a)&&(a=[a]),e.options.preload&&e.options.preload.indexOf(t)>-1)return ts(e,a,r);a.forEach(t=>{e.options.ns.indexOf(t)<0&&e.options.ns.push(t)}),e.loadLanguages(t,es(e,r))},rs=e=>"string"==typeof e,ss=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,ns={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},is=e=>ns[e];let os={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:e=>e.replace(ss,is)};let ls;const ds={type:"3rdParty",init(e){((e={})=>{os={...os,...e}})(e.options.react),(e=>{ls=e})(e)}},cs=n();class us{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(e=>{this.usedNamespaces[e]||(this.usedNamespaces[e]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var ms,hs={exports:{}},ps={};var fs,gs,bs={};
1
+ import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import*as r from"react";import n,{createContext as s,useContext as i,useMemo as o,useRef as l,useCallback as c,useState as d,useEffect as u,createElement as m,memo as h,Component as p,useLayoutEffect as f}from"react";import{Slot as g,createSlot as v}from"@radix-ui/react-slot";import{cva as b}from"class-variance-authority";import{clsx as y}from"clsx";import{twMerge as w}from"tailwind-merge";import{parseISO as x,isValid as N,format as k}from"date-fns";import{toast as C,Toaster as S}from"sonner";export{toast as sonnerToast,toast}from"sonner";import{EllipsisVertical as E,X as _,ChevronDown as P,ChevronUp as R,Check as T,Loader2 as A,Loader2Icon as I,OctagonXIcon as M,TriangleAlertIcon as O,InfoIcon as L,CircleCheckIcon as D,AlertCircle as F,Search as j,FileX as z,ChevronRight as $,Circle as U,Edit as V,PowerOff as W,Power as B,Trash2 as H,Plus as q,ArrowUpDown as K,ArrowUp as G,ArrowDown as X,Target as J,Trophy as Q,Award as Y,Sparkles as Z,Flame as ee,Zap as te,Key as ae,Shield as re,EyeOff as ne,Eye as se,Unlock as ie,Lock as oe,Archive as le,FolderOpen as ce,Folder as de,FileText as ue,Save as me,Copy as he,Share as pe,Upload as fe,Download as ge,HelpCircle as ve,Info as be,Bell as ye,Clock as we,ArrowRight as xe,ArrowLeft as Ne,ChevronLeft as ke,Minus as Ce,Filter as Se,Bookmark as Ee,Book as _e,Video as Pe,Music as Re,Image as Te,Camera as Ae,MapPin as Ie,Calendar as Me,Phone as Oe,Mail as Le,Settings as De,User as Fe,Home as je,Heart as ze,Star as $e,ChevronsLeft as Ue,ChevronsRight as Ve,RefreshCw as We,AlertTriangle as Be,MoreHorizontal as He,PanelLeft as qe,Edit3 as Ke,Code as Ge,Heading1 as Xe,Heading2 as Je,Heading3 as Qe,Bold as Ye,Italic as Ze,Underline as et,Strikethrough as tt,List as at,ListOrdered as rt,Highlighter as nt,Link as st,RemoveFormatting as it,Undo as ot,Redo as lt,ExternalLink as ct,Globe as dt,Building2 as ut,LogOut as mt,Users as ht,Crown as pt,UserPlus as ft}from"lucide-react";import*as gt from"@radix-ui/react-label";import*as vt from"@radix-ui/react-dialog";import*as bt from"@radix-ui/react-separator";import{useFormContext as yt,FormProvider as wt,Controller as xt,appendErrors as Nt,useForm as kt}from"react-hook-form";import*as Ct from"@radix-ui/react-select";import*as St from"@radix-ui/react-checkbox";import*as Et from"@radix-ui/react-popover";import{createClient as _t}from"@supabase/supabase-js";import{useQueryClient as Pt,useQuery as Rt,useMutation as Tt,QueryClient as At,QueryClientProvider as It}from"@tanstack/react-query";import{useSearchParams as Mt,useLocation as Ot,useNavigate as Lt,Link as Dt}from"react-router-dom";import*as Ft from"@radix-ui/react-tooltip";import*as jt from"@radix-ui/react-dropdown-menu";import*as zt from"@radix-ui/react-context-menu";import*as $t from"@radix-ui/react-scroll-area";import*as Ut from"@radix-ui/react-switch";import*as Vt from"@radix-ui/react-progress";import*as Wt from"@radix-ui/react-collapsible";import*as Bt from"@radix-ui/react-accordion";import*as Ht from"@radix-ui/react-alert-dialog";import*as qt from"@radix-ui/react-avatar";import{DayPicker as Kt}from"react-day-picker";import{Drawer as Gt}from"vaul";import*as Xt from"@radix-ui/react-radio-group";import*as Jt from"@radix-ui/react-slider";import*as Qt from"@radix-ui/react-tabs";import*as Yt from"@radix-ui/react-toggle";import*as Zt from"@radix-ui/react-toggle-group";import*as ea from"react-dom";import ta from"react-dom";import*as aa from"recharts";import{useEditor as ra,EditorContent as na}from"@tiptap/react";import sa from"@tiptap/starter-kit";import ia from"@tiptap/extension-underline";import oa from"@tiptap/extension-link";import{TextStyle as la}from"@tiptap/extension-text-style";import{Color as ca}from"@tiptap/extension-color";import da from"@tiptap/extension-highlight";import{z as ua}from"zod";import{validateFieldsNatively as ma,toNestErrors as ha}from"@hookform/resolvers";const pa=e=>"string"==typeof e,fa=()=>{let e,t;const a=new Promise((a,r)=>{e=a,t=r});return a.resolve=e,a.reject=t,a},ga=e=>null==e?"":""+e,va=/###/g,ba=e=>e&&e.indexOf("###")>-1?e.replace(va,"."):e,ya=e=>!e||pa(e),wa=(e,t,a)=>{const r=pa(t)?t.split("."):t;let n=0;for(;n<r.length-1;){if(ya(e))return{};const t=ba(r[n]);!e[t]&&a&&(e[t]=new a),e=Object.prototype.hasOwnProperty.call(e,t)?e[t]:{},++n}return ya(e)?{}:{obj:e,k:ba(r[n])}},xa=(e,t,a)=>{const{obj:r,k:n}=wa(e,t,Object);if(void 0!==r||1===t.length)return void(r[n]=a);let s=t[t.length-1],i=t.slice(0,t.length-1),o=wa(e,i,Object);for(;void 0===o.obj&&i.length;)s=`${i[i.length-1]}.${s}`,i=i.slice(0,i.length-1),o=wa(e,i,Object),o?.obj&&void 0!==o.obj[`${o.k}.${s}`]&&(o.obj=void 0);o.obj[`${o.k}.${s}`]=a},Na=(e,t)=>{const{obj:a,k:r}=wa(e,t);if(a&&Object.prototype.hasOwnProperty.call(a,r))return a[r]},ka=(e,t,a)=>{for(const r in t)"__proto__"!==r&&"constructor"!==r&&(r in e?pa(e[r])||e[r]instanceof String||pa(t[r])||t[r]instanceof String?a&&(e[r]=t[r]):ka(e[r],t[r],a):e[r]=t[r]);return e},Ca=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Sa={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Ea=e=>pa(e)?e.replace(/[&<>"'\/]/g,e=>Sa[e]):e;const _a=[" ",",","?","!",";"],Pa=new class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(void 0!==t)return t;const a=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,a),this.regExpQueue.push(e),a}}(20),Ra=(e,t,a=".")=>{if(!e)return;if(e[t]){if(!Object.prototype.hasOwnProperty.call(e,t))return;return e[t]}const r=t.split(a);let n=e;for(let s=0;s<r.length;){if(!n||"object"!=typeof n)return;let e,t="";for(let i=s;i<r.length;++i)if(i!==s&&(t+=a),t+=r[i],e=n[t],void 0!==e){if(["string","number","boolean"].indexOf(typeof e)>-1&&i<r.length-1)continue;s+=i-s+1;break}n=e}return n},Ta=e=>e?.replace("_","-"),Aa={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){}};class Ia{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||Aa,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,a,r){return r&&!this.debug?null:(pa(e[0])&&(e[0]=`${a}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new Ia(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return(e=e||this.options).prefix=e.prefix||this.prefix,new Ia(this.logger,e)}}var Ma=new Ia;class Oa{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(e=>{this.observers[e]||(this.observers[e]=new Map);const a=this.observers[e].get(t)||0;this.observers[e].set(t,a+1)}),this}off(e,t){this.observers[e]&&(t?this.observers[e].delete(t):delete this.observers[e])}emit(e,...t){if(this.observers[e]){Array.from(this.observers[e].entries()).forEach(([e,a])=>{for(let r=0;r<a;r++)e(...t)})}if(this.observers["*"]){Array.from(this.observers["*"].entries()).forEach(([a,r])=>{for(let n=0;n<r;n++)a.apply(a,[e,...t])})}}}class La extends Oa{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,void 0===this.options.keySeparator&&(this.options.keySeparator="."),void 0===this.options.ignoreJSONStructure&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}removeNamespaces(e){const t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,a,r={}){const n=void 0!==r.keySeparator?r.keySeparator:this.options.keySeparator,s=void 0!==r.ignoreJSONStructure?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let i;e.indexOf(".")>-1?i=e.split("."):(i=[e,t],a&&(Array.isArray(a)?i.push(...a):pa(a)&&n?i.push(...a.split(n)):i.push(a)));const o=Na(this.data,i);return!o&&!t&&!a&&e.indexOf(".")>-1&&(e=i[0],t=i[1],a=i.slice(2).join(".")),!o&&s&&pa(a)?Ra(this.data?.[e]?.[t],a,n):o}addResource(e,t,a,r,n={silent:!1}){const s=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator;let i=[e,t];a&&(i=i.concat(s?a.split(s):a)),e.indexOf(".")>-1&&(i=e.split("."),r=t,t=i[1]),this.addNamespaces(t),xa(this.data,i,r),n.silent||this.emit("added",e,t,a,r)}addResources(e,t,a,r={silent:!1}){for(const n in a)(pa(a[n])||Array.isArray(a[n]))&&this.addResource(e,t,n,a[n],{silent:!0});r.silent||this.emit("added",e,t,a)}addResourceBundle(e,t,a,r,n,s={silent:!1,skipCopy:!1}){let i=[e,t];e.indexOf(".")>-1&&(i=e.split("."),r=a,a=t,t=i[1]),this.addNamespaces(t);let o=Na(this.data,i)||{};s.skipCopy||(a=JSON.parse(JSON.stringify(a))),r?ka(o,a,n):o={...o,...a},xa(this.data,i,o),s.silent||this.emit("added",e,t,a)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return void 0!==this.getResource(e,t)}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(e=>t[e]&&Object.keys(t[e]).length>0)}toJSON(){return this.data}}var Da={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,a,r,n){return e.forEach(e=>{t=this.processors[e]?.process(t,a,r,n)??t}),t}};const Fa=Symbol("i18next/PATH_KEY");function ja(e,t){const{[Fa]:a}=e(function(){const e=[],t=Object.create(null);let a;return t.get=(r,n)=>(a?.revoke?.(),n===Fa?e:(e.push(n),a=Proxy.revocable(r,t),a.proxy)),Proxy.revocable(Object.create(null),t).proxy}());return a.join(t?.keySeparator??".")}const za={},$a=e=>!pa(e)&&"boolean"!=typeof e&&"number"!=typeof e;class Ua extends Oa{constructor(e,t={}){super(),((e,t,a)=>{e.forEach(e=>{t[e]&&(a[e]=t[e])})})(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,void 0===this.options.keySeparator&&(this.options.keySeparator="."),this.logger=Ma.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const a={...t};if(null==e)return!1;const r=this.resolve(e,a);if(void 0===r?.res)return!1;const n=$a(r.res);return!1!==a.returnObjects||!n}extractFromKey(e,t){let a=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===a&&(a=":");const r=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator;let n=t.ns||this.options.defaultNS||[];const s=a&&e.indexOf(a)>-1,i=!(this.options.userDefinedKeySeparator||t.keySeparator||this.options.userDefinedNsSeparator||t.nsSeparator||((e,t,a)=>{t=t||"",a=a||"";const r=_a.filter(e=>t.indexOf(e)<0&&a.indexOf(e)<0);if(0===r.length)return!0;const n=Pa.getRegExp(`(${r.map(e=>"?"===e?"\\?":e).join("|")})`);let s=!n.test(e);if(!s){const t=e.indexOf(a);t>0&&!n.test(e.substring(0,t))&&(s=!0)}return s})(e,a,r));if(s&&!i){const t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:pa(n)?[n]:n};const s=e.split(a);(a!==r||a===r&&this.options.ns.indexOf(s[0])>-1)&&(n=s.shift()),e=s.join(r)}return{key:e,namespaces:pa(n)?[n]:n}}translate(e,t,a){let r="object"==typeof t?{...t}:t;if("object"!=typeof r&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof r&&(r={...r}),r||(r={}),null==e)return"";"function"==typeof e&&(e=ja(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]);const n=void 0!==r.returnDetails?r.returnDetails:this.options.returnDetails,s=void 0!==r.keySeparator?r.keySeparator:this.options.keySeparator,{key:i,namespaces:o}=this.extractFromKey(e[e.length-1],r),l=o[o.length-1];let c=void 0!==r.nsSeparator?r.nsSeparator:this.options.nsSeparator;void 0===c&&(c=":");const d=r.lng||this.language,u=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if("cimode"===d?.toLowerCase())return u?n?{res:`${l}${c}${i}`,usedKey:i,exactUsedKey:i,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(r)}:`${l}${c}${i}`:n?{res:i,usedKey:i,exactUsedKey:i,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(r)}:i;const m=this.resolve(e,r);let h=m?.res;const p=m?.usedKey||i,f=m?.exactUsedKey||i,g=void 0!==r.joinArrays?r.joinArrays:this.options.joinArrays,v=!this.i18nFormat||this.i18nFormat.handleAsObject,b=void 0!==r.count&&!pa(r.count),y=Ua.hasDefaultValue(r),w=b?this.pluralResolver.getSuffix(d,r.count,r):"",x=r.ordinal&&b?this.pluralResolver.getSuffix(d,r.count,{ordinal:!1}):"",N=b&&!r.ordinal&&0===r.count,k=N&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${w}`]||r[`defaultValue${x}`]||r.defaultValue;let C=h;v&&!h&&y&&(C=k);const S=$a(C),E=Object.prototype.toString.apply(C);if(!(v&&C&&S&&["[object Number]","[object Function]","[object RegExp]"].indexOf(E)<0)||pa(g)&&Array.isArray(C))if(v&&pa(g)&&Array.isArray(h))h=h.join(g),h&&(h=this.extendTranslation(h,e,r,a));else{let t=!1,n=!1;!this.isValidLookup(h)&&y&&(t=!0,h=k),this.isValidLookup(h)||(n=!0,h=i);const o=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&n?void 0:h,u=y&&k!==h&&this.options.updateMissing;if(n||t||u){if(this.logger.log(u?"updateKey":"missingKey",d,l,i,u?k:h),s){const e=this.resolve(i,{...r,keySeparator:!1});e&&e.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let e=[];const t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if("fallback"===this.options.saveMissingTo&&t&&t[0])for(let r=0;r<t.length;r++)e.push(t[r]);else"all"===this.options.saveMissingTo?e=this.languageUtils.toResolveHierarchy(r.lng||this.language):e.push(r.lng||this.language);const a=(e,t,a)=>{const n=y&&a!==h?a:o;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,n,u,r):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,n,u,r),this.emit("missingKey",e,l,t,h)};this.options.saveMissing&&(this.options.saveMissingPlurals&&b?e.forEach(e=>{const t=this.pluralResolver.getSuffixes(e,r);N&&r[`defaultValue${this.options.pluralSeparator}zero`]&&t.indexOf(`${this.options.pluralSeparator}zero`)<0&&t.push(`${this.options.pluralSeparator}zero`),t.forEach(t=>{a([e],i+t,r[`defaultValue${t}`]||k)})}):a(e,i,k))}h=this.extendTranslation(h,e,r,m,a),n&&h===i&&this.options.appendNamespaceToMissingKey&&(h=`${l}${c}${i}`),(n||t)&&this.options.parseMissingKeyHandler&&(h=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${c}${i}`:i,t?h:void 0,r))}else{if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(p,C,{...r,ns:o}):`key '${i} (${this.language})' returned an object instead of string.`;return n?(m.res=e,m.usedParams=this.getUsedParamsDetails(r),m):e}if(s){const e=Array.isArray(C),t=e?[]:{},a=e?f:p;for(const n in C)if(Object.prototype.hasOwnProperty.call(C,n)){const e=`${a}${s}${n}`;t[n]=y&&!h?this.translate(e,{...r,defaultValue:$a(k)?k[n]:void 0,joinArrays:!1,ns:o}):this.translate(e,{...r,joinArrays:!1,ns:o}),t[n]===e&&(t[n]=C[n])}h=t}}return n?(m.res=h,m.usedParams=this.getUsedParamsDetails(r),m):h}extendTranslation(e,t,a,r,n){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...a},a.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init({...a,interpolation:{...this.options.interpolation,...a.interpolation}});const s=pa(e)&&(void 0!==a?.interpolation?.skipOnVariables?a.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let i;if(s){const t=e.match(this.interpolator.nestingRegexp);i=t&&t.length}let o=a.replace&&!pa(a.replace)?a.replace:a;if(this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),e=this.interpolator.interpolate(e,o,a.lng||this.language||r.usedLng,a),s){const t=e.match(this.interpolator.nestingRegexp);i<(t&&t.length)&&(a.nest=!1)}!a.lng&&r&&r.res&&(a.lng=this.language||r.usedLng),!1!==a.nest&&(e=this.interpolator.nest(e,(...e)=>n?.[0]!==e[0]||a.context?this.translate(...e,t):(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null),a)),a.interpolation&&this.interpolator.reset()}const s=a.postProcess||this.options.postProcess,i=pa(s)?[s]:s;return null!=e&&i?.length&&!1!==a.applyPostProcessor&&(e=Da.handle(i,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(a)},...a}:a,this)),e}resolve(e,t={}){let a,r,n,s,i;return pa(e)&&(e=[e]),e.forEach(e=>{if(this.isValidLookup(a))return;const o=this.extractFromKey(e,t),l=o.key;r=l;let c=o.namespaces;this.options.fallbackNS&&(c=c.concat(this.options.fallbackNS));const d=void 0!==t.count&&!pa(t.count),u=d&&!t.ordinal&&0===t.count,m=void 0!==t.context&&(pa(t.context)||"number"==typeof t.context)&&""!==t.context,h=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);c.forEach(e=>{this.isValidLookup(a)||(i=e,za[`${h[0]}-${e}`]||!this.utils?.hasLoadedNamespace||this.utils?.hasLoadedNamespace(i)||(za[`${h[0]}-${e}`]=!0,this.logger.warn(`key "${r}" for languages "${h.join(", ")}" won't get resolved as namespace "${i}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),h.forEach(r=>{if(this.isValidLookup(a))return;s=r;const i=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(i,l,r,e,t);else{let e;d&&(e=this.pluralResolver.getSuffix(r,t.count,t));const a=`${this.options.pluralSeparator}zero`,n=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(t.ordinal&&0===e.indexOf(n)&&i.push(l+e.replace(n,this.options.pluralSeparator)),i.push(l+e),u&&i.push(l+a)),m){const r=`${l}${this.options.contextSeparator||"_"}${t.context}`;i.push(r),d&&(t.ordinal&&0===e.indexOf(n)&&i.push(r+e.replace(n,this.options.pluralSeparator)),i.push(r+e),u&&i.push(r+a))}}let o;for(;o=i.pop();)this.isValidLookup(a)||(n=o,a=this.getResource(r,e,o,t))}))})}),{res:a,usedKey:r,exactUsedKey:n,usedLng:s,usedNS:i}}isValidLookup(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}getResource(e,t,a,r={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,a,r):this.resourceStore.getResource(e,t,a,r)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],a=e.replace&&!pa(e.replace);let r=a?e.replace:e;if(a&&void 0!==e.count&&(r.count=e.count),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!a){r={...r};for(const e of t)delete r[e]}return r}static hasDefaultValue(e){const t="defaultValue";for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t===a.substring(0,12)&&void 0!==e[a])return!0;return!1}}class Va{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ma.create("languageUtils")}getScriptPartFromCode(e){if(!(e=Ta(e))||e.indexOf("-")<0)return null;const t=e.split("-");return 2===t.length?null:(t.pop(),"x"===t[t.length-1].toLowerCase()?null:this.formatLanguageCode(t.join("-")))}getLanguagePartFromCode(e){if(!(e=Ta(e))||e.indexOf("-")<0)return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(pa(e)&&e.indexOf("-")>-1){let a;try{a=Intl.getCanonicalLocales(e)[0]}catch(t){}return a&&this.options.lowerCaseLng&&(a=a.toLowerCase()),a||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(e=>{if(t)return;const a=this.formatLanguageCode(e);this.options.supportedLngs&&!this.isSupportedCode(a)||(t=a)}),!t&&this.options.supportedLngs&&e.forEach(e=>{if(t)return;const a=this.getScriptPartFromCode(e);if(this.isSupportedCode(a))return t=a;const r=this.getLanguagePartFromCode(e);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(e=>e===r?e:e.indexOf("-")<0&&r.indexOf("-")<0?void 0:e.indexOf("-")>0&&r.indexOf("-")<0&&e.substring(0,e.indexOf("-"))===r||0===e.indexOf(r)&&r.length>1?e:void 0)}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),pa(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let a=e[t];return a||(a=e[this.getScriptPartFromCode(t)]),a||(a=e[this.formatLanguageCode(t)]),a||(a=e[this.getLanguagePartFromCode(t)]),a||(a=e.default),a||[]}toResolveHierarchy(e,t){const a=this.getFallbackCodes((!1===t?[]:t)||this.options.fallbackLng||[],e),r=[],n=e=>{e&&(this.isSupportedCode(e)?r.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return pa(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?("languageOnly"!==this.options.load&&n(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&n(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&n(this.getLanguagePartFromCode(e))):pa(e)&&n(this.formatLanguageCode(e)),a.forEach(e=>{r.indexOf(e)<0&&n(this.formatLanguageCode(e))}),r}}const Wa={zero:0,one:1,two:2,few:3,many:4,other:5},Ba={select:e=>1===e?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Ha{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=Ma.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,t){this.rules[e]=t}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const a=Ta("dev"===e?"en":e),r=t.ordinal?"ordinal":"cardinal",n=JSON.stringify({cleanedCode:a,type:r});if(n in this.pluralRulesCache)return this.pluralRulesCache[n];let s;try{s=new Intl.PluralRules(a,{type:r})}catch(i){if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),Ba;if(!e.match(/-|_/))return Ba;const a=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(a,t)}return this.pluralRulesCache[n]=s,s}needsPlural(e,t={}){let a=this.getRule(e,t);return a||(a=this.getRule("dev",t)),a?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,a={}){return this.getSuffixes(e,a).map(e=>`${t}${e}`)}getSuffixes(e,t={}){let a=this.getRule(e,t);return a||(a=this.getRule("dev",t)),a?a.resolvedOptions().pluralCategories.sort((e,t)=>Wa[e]-Wa[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${e}`):[]}getSuffix(e,t,a={}){const r=this.getRule(e,a);return r?`${this.options.prepend}${a.ordinal?`ordinal${this.options.prepend}`:""}${r.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,a))}}const qa=(e,t,a,r=".",n=!0)=>{let s=((e,t,a)=>{const r=Na(e,a);return void 0!==r?r:Na(t,a)})(e,t,a);return!s&&n&&pa(a)&&(s=Ra(e,a,r),void 0===s&&(s=Ra(t,a,r))),s},Ka=e=>e.replace(/\$/g,"$$$$");class Ga{constructor(e={}){this.logger=Ma.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:a,useRawValueToEscape:r,prefix:n,prefixEscaped:s,suffix:i,suffixEscaped:o,formatSeparator:l,unescapeSuffix:c,unescapePrefix:d,nestingPrefix:u,nestingPrefixEscaped:m,nestingSuffix:h,nestingSuffixEscaped:p,nestingOptionsSeparator:f,maxReplaces:g,alwaysFormat:v}=e.interpolation;this.escape=void 0!==t?t:Ea,this.escapeValue=void 0===a||a,this.useRawValueToEscape=void 0!==r&&r,this.prefix=n?Ca(n):s||"{{",this.suffix=i?Ca(i):o||"}}",this.formatSeparator=l||",",this.unescapePrefix=c?"":d||"-",this.unescapeSuffix=this.unescapePrefix?"":c||"",this.nestingPrefix=u?Ca(u):m||Ca("$t("),this.nestingSuffix=h?Ca(h):p||Ca(")"),this.nestingOptionsSeparator=f||",",this.maxReplaces=g||1e3,this.alwaysFormat=void 0!==v&&v,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(e,t)=>e?.source===t?(e.lastIndex=0,e):new RegExp(t,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,a,r){let n,s,i;const o=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=e=>{if(e.indexOf(this.formatSeparator)<0){const n=qa(t,o,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(n,void 0,a,{...r,...t,interpolationkey:e}):n}const n=e.split(this.formatSeparator),s=n.shift().trim(),i=n.join(this.formatSeparator).trim();return this.format(qa(t,o,s,this.options.keySeparator,this.options.ignoreJSONStructure),i,a,{...r,...t,interpolationkey:s})};this.resetRegExp();const c=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,d=void 0!==r?.interpolation?.skipOnVariables?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>Ka(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?Ka(this.escape(e)):Ka(e)}].forEach(t=>{for(i=0;n=t.regex.exec(e);){const a=n[1].trim();if(s=l(a),void 0===s)if("function"==typeof c){const t=c(e,n,r);s=pa(t)?t:""}else if(r&&Object.prototype.hasOwnProperty.call(r,a))s="";else{if(d){s=n[0];continue}this.logger.warn(`missed to pass in variable ${a} for interpolating ${e}`),s=""}else pa(s)||this.useRawValueToEscape||(s=ga(s));const o=t.safeValue(s);if(e=e.replace(n[0],o),d?(t.regex.lastIndex+=s.length,t.regex.lastIndex-=n[0].length):t.regex.lastIndex=0,i++,i>=this.maxReplaces)break}}),e}nest(e,t,a={}){let r,n,s;const i=(e,t)=>{const a=this.nestingOptionsSeparator;if(e.indexOf(a)<0)return e;const r=e.split(new RegExp(`${a}[ ]*{`));let n=`{${r[1]}`;e=r[0],n=this.interpolate(n,s);const i=n.match(/'/g),o=n.match(/"/g);((i?.length??0)%2==0&&!o||o.length%2!=0)&&(n=n.replace(/'/g,'"'));try{s=JSON.parse(n),t&&(s={...t,...s})}catch(l){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,l),`${e}${a}${n}`}return s.defaultValue&&s.defaultValue.indexOf(this.prefix)>-1&&delete s.defaultValue,e};for(;r=this.nestingRegexp.exec(e);){let o=[];s={...a},s=s.replace&&!pa(s.replace)?s.replace:s,s.applyPostProcessor=!1,delete s.defaultValue;const l=/{.*}/.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(-1!==l&&(o=r[1].slice(l).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),r[1]=r[1].slice(0,l)),n=t(i.call(this,r[1].trim(),s),s),n&&r[0]===e&&!pa(n))return n;pa(n)||(n=ga(n)),n||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),n=""),o.length&&(n=o.reduce((e,t)=>this.format(e,t,a.lng,{...a,interpolationkey:r[1].trim()}),n.trim())),e=e.replace(r[0],n),this.regexp.lastIndex=0}return e}}const Xa=e=>{const t={};return(a,r,n)=>{let s=n;n&&n.interpolationkey&&n.formatParams&&n.formatParams[n.interpolationkey]&&n[n.interpolationkey]&&(s={...s,[n.interpolationkey]:void 0});const i=r+JSON.stringify(s);let o=t[i];return o||(o=e(Ta(r),n),t[i]=o),o(a)}},Ja=e=>(t,a,r)=>e(Ta(a),r)(t);class Qa{constructor(e={}){this.logger=Ma.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const a=t.cacheInBuiltFormats?Xa:Ja;this.formats={number:a((e,t)=>{const a=new Intl.NumberFormat(e,{...t});return e=>a.format(e)}),currency:a((e,t)=>{const a=new Intl.NumberFormat(e,{...t,style:"currency"});return e=>a.format(e)}),datetime:a((e,t)=>{const a=new Intl.DateTimeFormat(e,{...t});return e=>a.format(e)}),relativetime:a((e,t)=>{const a=new Intl.RelativeTimeFormat(e,{...t});return e=>a.format(e,t.range||"day")}),list:a((e,t)=>{const a=new Intl.ListFormat(e,{...t});return e=>a.format(e)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Xa(t)}format(e,t,a,r={}){const n=t.split(this.formatSeparator);if(n.length>1&&n[0].indexOf("(")>1&&n[0].indexOf(")")<0&&n.find(e=>e.indexOf(")")>-1)){const e=n.findIndex(e=>e.indexOf(")")>-1);n[0]=[n[0],...n.splice(1,e)].join(this.formatSeparator)}return n.reduce((e,t)=>{const{formatName:n,formatOptions:s}=(e=>{let t=e.toLowerCase().trim();const a={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const n=r[1].substring(0,r[1].length-1);"currency"===t&&n.indexOf(":")<0?a.currency||(a.currency=n.trim()):"relativetime"===t&&n.indexOf(":")<0?a.range||(a.range=n.trim()):n.split(";").forEach(e=>{if(e){const[t,...r]=e.split(":"),n=r.join(":").trim().replace(/^'+|'+$/g,""),s=t.trim();a[s]||(a[s]=n),"false"===n&&(a[s]=!1),"true"===n&&(a[s]=!0),isNaN(n)||(a[s]=parseInt(n,10))}})}return{formatName:t,formatOptions:a}})(t);if(this.formats[n]){let t=e;try{const i=r?.formatParams?.[r.interpolationkey]||{},o=i.locale||i.lng||r.locale||r.lng||a;t=this.formats[n](e,o,{...s,...r,...i})}catch(i){this.logger.warn(i)}return t}return this.logger.warn(`there was no format function for ${n}`),e},e)}}class Ya extends Oa{constructor(e,t,a,r={}){super(),this.backend=e,this.store=t,this.services=a,this.languageUtils=a.languageUtils,this.options=r,this.logger=Ma.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(a,r.backend,r)}queueLoad(e,t,a,r){const n={},s={},i={},o={};return e.forEach(e=>{let r=!0;t.forEach(t=>{const i=`${e}|${t}`;!a.reload&&this.store.hasResourceBundle(e,t)?this.state[i]=2:this.state[i]<0||(1===this.state[i]?void 0===s[i]&&(s[i]=!0):(this.state[i]=1,r=!1,void 0===s[i]&&(s[i]=!0),void 0===n[i]&&(n[i]=!0),void 0===o[t]&&(o[t]=!0)))}),r||(i[e]=!0)}),(Object.keys(n).length||Object.keys(s).length)&&this.queue.push({pending:s,pendingCount:Object.keys(s).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(n),pending:Object.keys(s),toLoadLanguages:Object.keys(i),toLoadNamespaces:Object.keys(o)}}loaded(e,t,a){const r=e.split("|"),n=r[0],s=r[1];t&&this.emit("failedLoading",n,s,t),!t&&a&&this.store.addResourceBundle(n,s,a,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&a&&(this.state[e]=0);const i={};this.queue.forEach(a=>{((e,t,a)=>{const{obj:r,k:n}=wa(e,t,Object);r[n]=r[n]||[],r[n].push(a)})(a.loaded,[n],s),((e,t)=>{void 0!==e.pending[t]&&(delete e.pending[t],e.pendingCount--)})(a,e),t&&a.errors.push(t),0!==a.pendingCount||a.done||(Object.keys(a.loaded).forEach(e=>{i[e]||(i[e]={});const t=a.loaded[e];t.length&&t.forEach(t=>{void 0===i[e][t]&&(i[e][t]=!0)})}),a.done=!0,a.errors.length?a.callback(a.errors):a.callback())}),this.emit("loaded",i),this.queue=this.queue.filter(e=>!e.done)}read(e,t,a,r=0,n=this.retryTimeout,s){if(!e.length)return s(null,{});if(this.readingCalls>=this.maxParallelReads)return void this.waitingReads.push({lng:e,ns:t,fcName:a,tried:r,wait:n,callback:s});this.readingCalls++;const i=(i,o)=>{if(this.readingCalls--,this.waitingReads.length>0){const e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}i&&o&&r<this.maxRetries?setTimeout(()=>{this.read.call(this,e,t,a,r+1,2*n,s)},n):s(i,o)},o=this.backend[a].bind(this.backend);if(2!==o.length)return o(e,t,i);try{const a=o(e,t);a&&"function"==typeof a.then?a.then(e=>i(null,e)).catch(i):i(null,a)}catch(l){i(l)}}prepareLoading(e,t,a={},r){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();pa(e)&&(e=this.languageUtils.toResolveHierarchy(e)),pa(t)&&(t=[t]);const n=this.queueLoad(e,t,a,r);if(!n.toLoad.length)return n.pending.length||r(),null;n.toLoad.forEach(e=>{this.loadOne(e)})}load(e,t,a){this.prepareLoading(e,t,{},a)}reload(e,t,a){this.prepareLoading(e,t,{reload:!0},a)}loadOne(e,t=""){const a=e.split("|"),r=a[0],n=a[1];this.read(r,n,"read",void 0,void 0,(a,s)=>{a&&this.logger.warn(`${t}loading namespace ${n} for language ${r} failed`,a),!a&&s&&this.logger.log(`${t}loaded namespace ${n} for language ${r}`,s),this.loaded(e,a,s)})}saveMissing(e,t,a,r,n,s={},i=()=>{}){if(!this.services?.utils?.hasLoadedNamespace||this.services?.utils?.hasLoadedNamespace(t)){if(null!=a&&""!==a){if(this.backend?.create){const l={...s,isUpdate:n},c=this.backend.create.bind(this.backend);if(c.length<6)try{let n;n=5===c.length?c(e,t,a,r,l):c(e,t,a,r),n&&"function"==typeof n.then?n.then(e=>i(null,e)).catch(i):i(null,n)}catch(o){i(o)}else c(e,t,a,r,i,l)}e&&e[0]&&this.store.addResource(e[0],t,a,r)}}else this.logger.warn(`did not save key "${a}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")}}const Za=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if("object"==typeof e[1]&&(t=e[1]),pa(e[1])&&(t.defaultValue=e[1]),pa(e[2])&&(t.tDescription=e[2]),"object"==typeof e[2]||"object"==typeof e[3]){const a=e[3]||e[2];Object.keys(a).forEach(e=>{t[e]=a[e]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),er=e=>(pa(e.ns)&&(e.ns=[e.ns]),pa(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),pa(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),"boolean"==typeof e.initImmediate&&(e.initAsync=e.initImmediate),e),tr=()=>{};class ar extends Oa{constructor(e={},t){var a;if(super(),this.options=er(e),this.services={},this.logger=Ma,this.modules={external:[]},a=this,Object.getOwnPropertyNames(Object.getPrototypeOf(a)).forEach(e=>{"function"==typeof a[e]&&(a[e]=a[e].bind(a))}),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,"function"==typeof e&&(t=e,e={}),null==e.defaultNS&&e.ns&&(pa(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const a=Za();this.options={...a,...this.options,...er(e)},this.options.interpolation={...a.interpolation,...this.options.interpolation},void 0!==e.keySeparator&&(this.options.userDefinedKeySeparator=e.keySeparator),void 0!==e.nsSeparator&&(this.options.userDefinedNsSeparator=e.nsSeparator),"function"!=typeof this.options.overloadTranslationOptionHandler&&(this.options.overloadTranslationOptionHandler=a.overloadTranslationOptionHandler);const r=e=>e?"function"==typeof e?new e:e:null;if(!this.options.isClone){let e;this.modules.logger?Ma.init(r(this.modules.logger),this.options):Ma.init(null,this.options),e=this.modules.formatter?this.modules.formatter:Qa;const t=new Va(this.options);this.store=new La(this.options.resources,this.options);const n=this.services;n.logger=Ma,n.resourceStore=this.store,n.languageUtils=t,n.pluralResolver=new Ha(t,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix});this.options.interpolation.format&&this.options.interpolation.format!==a.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),!e||this.options.interpolation.format&&this.options.interpolation.format!==a.interpolation.format||(n.formatter=r(e),n.formatter.init&&n.formatter.init(n,this.options),this.options.interpolation.format=n.formatter.format.bind(n.formatter)),n.interpolator=new Ga(this.options),n.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},n.backendConnector=new Ya(r(this.modules.backend),n.resourceStore,n,this.options),n.backendConnector.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(n.languageDetector=r(this.modules.languageDetector),n.languageDetector.init&&n.languageDetector.init(n,this.options.detection,this.options)),this.modules.i18nFormat&&(n.i18nFormat=r(this.modules.i18nFormat),n.i18nFormat.init&&n.i18nFormat.init(this)),this.translator=new Ua(this.services,this.options),this.translator.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.external.forEach(e=>{e.init&&e.init(this)})}if(this.format=this.options.interpolation.format,t||(t=tr),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&"dev"!==e[0]&&(this.options.lng=e[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(e=>{this[e]=(...t)=>this.store[e](...t)});["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(e=>{this[e]=(...t)=>(this.store[e](...t),this)});const n=fa(),s=()=>{const e=(e,a)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),n.resolve(a),t(e,a)};if(this.languages&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?s():setTimeout(s,0),n}loadResources(e,t=tr){let a=t;const r=pa(e)?e:this.language;if("function"==typeof e&&(a=e),!this.options.resources||this.options.partialBundledLanguages){if("cimode"===r?.toLowerCase()&&(!this.options.preload||0===this.options.preload.length))return a();const e=[],t=t=>{if(!t)return;if("cimode"===t)return;this.services.languageUtils.toResolveHierarchy(t).forEach(t=>{"cimode"!==t&&e.indexOf(t)<0&&e.push(t)})};if(r)t(r);else{this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(e=>t(e))}this.options.preload?.forEach?.(e=>t(e)),this.services.backendConnector.load(e,this.options.ns,e=>{e||this.resolvedLanguage||!this.language||this.setResolvedLanguage(this.language),a(e)})}else a(null)}reloadResources(e,t,a){const r=fa();return"function"==typeof e&&(a=e,e=void 0),"function"==typeof t&&(a=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),a||(a=tr),this.services.backendConnector.reload(e,t,e=>{r.resolve(),a(e)}),r}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&Da.addPostProcessor(e),"formatter"===e.type&&(this.modules.formatter=e),"3rdParty"===e.type&&this.modules.external.push(e),this}setResolvedLanguage(e){if(e&&this.languages&&!(["cimode","dev"].indexOf(e)>-1)){for(let e=0;e<this.languages.length;e++){const t=this.languages[e];if(!(["cimode","dev"].indexOf(t)>-1)&&this.store.hasLanguageSomeTranslations(t)){this.resolvedLanguage=t;break}}!this.resolvedLanguage&&this.languages.indexOf(e)<0&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;const a=fa();this.emit("languageChanging",e);const r=e=>{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},n=(n,s)=>{s?this.isLanguageChangingTo===e&&(r(s),this.translator.changeLanguage(s),this.isLanguageChangingTo=void 0,this.emit("languageChanged",s),this.logger.log("languageChanged",s)):this.isLanguageChangingTo=void 0,a.resolve((...e)=>this.t(...e)),t&&t(n,(...e)=>this.t(...e))},s=t=>{e||t||!this.services.languageDetector||(t=[]);const a=pa(t)?t:t&&t[0],s=this.store.hasLanguageSomeTranslations(a)?a:this.services.languageUtils.getBestMatchFromCodes(pa(t)?[t]:t);s&&(this.language||r(s),this.translator.language||this.translator.changeLanguage(s),this.services.languageDetector?.cacheUserLanguage?.(s)),this.loadResources(s,e=>{n(e,s)})};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(s):this.services.languageDetector.detect(s):s(e):s(this.services.languageDetector.detect()),a}getFixedT(e,t,a){const r=(e,t,...n)=>{let s;s="object"!=typeof t?this.options.overloadTranslationOptionHandler([e,t].concat(n)):{...t},s.lng=s.lng||r.lng,s.lngs=s.lngs||r.lngs,s.ns=s.ns||r.ns,""!==s.keyPrefix&&(s.keyPrefix=s.keyPrefix||a||r.keyPrefix);const i=this.options.keySeparator||".";let o;return s.keyPrefix&&Array.isArray(e)?o=e.map(e=>("function"==typeof e&&(e=ja(e,{...this.options,...t})),`${s.keyPrefix}${i}${e}`)):("function"==typeof e&&(e=ja(e,{...this.options,...t})),o=s.keyPrefix?`${s.keyPrefix}${i}${e}`:e),this.t(o,s)};return pa(e)?r.lng=e:r.lngs=e,r.ns=t,r.keyPrefix=a,r}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const a=t.lng||this.resolvedLanguage||this.languages[0],r=!!this.options&&this.options.fallbackLng,n=this.languages[this.languages.length-1];if("cimode"===a.toLowerCase())return!0;const s=(e,t)=>{const a=this.services.backendConnector.state[`${e}|${t}`];return-1===a||0===a||2===a};if(t.precheck){const e=t.precheck(this,s);if(void 0!==e)return e}return!!this.hasResourceBundle(a,e)||(!(this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages))||!(!s(a,e)||r&&!s(n,e)))}loadNamespaces(e,t){const a=fa();return this.options.ns?(pa(e)&&(e=[e]),e.forEach(e=>{this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}),this.loadResources(e=>{a.resolve(),t&&t(e)}),a):(t&&t(),Promise.resolve())}loadLanguages(e,t){const a=fa();pa(e)&&(e=[e]);const r=this.options.preload||[],n=e.filter(e=>r.indexOf(e)<0&&this.services.languageUtils.isSupportedCode(e));return n.length?(this.options.preload=r.concat(n),this.loadResources(e=>{a.resolve(),t&&t(e)}),a):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{const t=new Intl.Locale(e);if(t&&t.getTextInfo){const e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch(a){}const t=this.services?.languageUtils||new Va(Za());return e.toLowerCase().indexOf("-latn")>1?"ltr":["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(t.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){const a=new ar(e,t);return a.createInstance=ar.createInstance,a}cloneInstance(e={},t=tr){const a=e.forkResourceStore;a&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},n=new ar(r);void 0===e.debug&&void 0===e.prefix||(n.logger=n.logger.clone(e));if(["store","services","language"].forEach(e=>{n[e]=this[e]}),n.services={...this.services},n.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},a){const e=Object.keys(this.store.data).reduce((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce((a,r)=>(a[r]={...e[t][r]},a),e[t]),e),{});n.store=new La(e,r),n.services.resourceStore=n.store}return e.interpolation&&(n.services.interpolator=new Ga(r)),n.translator=new Ua(n.services,r),n.translator.on("*",(e,...t)=>{n.emit(e,...t)}),n.init(r,t),n.translator.options=r,n.translator.backendConnector.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},n}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const rr=ar.createInstance();function nr(e,t){t?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{C.info(rr.t("link_copied"))})}function sr(...e){return w(y(e))}rr.createInstance,rr.dir,rr.init,rr.loadResources,rr.reloadResources,rr.use,rr.changeLanguage,rr.getFixedT,rr.t,rr.exists,rr.setDefaultNamespace,rr.hasLoadedNamespace,rr.loadNamespaces,rr.loadLanguages;const ir=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(ir);if("object"==typeof e&&e.constructor===Object){const t={};for(const[a,r]of Object.entries(e))t[a]=ir(r);return t}return e},or=e=>{if(!e)return"";const t=x(e);if(!N(t))return"Data inválida";return`${t.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",timeZone:"America/Sao_Paulo"})} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"})}`},lr=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),cr=(e,t)=>{let a;return(...r)=>{clearTimeout(a),a=setTimeout(()=>e(...r),t)}},dr=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),ur=b("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),mr=r.forwardRef(({className:t,variant:a,size:r,asChild:n=!1,...s},i)=>e(n?g:"button",{className:sr(ur({variant:a,size:r,className:t})),ref:i,...s}));mr.displayName="Button";const hr=n.forwardRef(({className:t,children:a,...r},n)=>e(mr,{ref:n,variant:"action",size:"sm",className:sr("h-7 px-2 text-xs",t),...r,children:a||e(E,{size:12})}));hr.displayName="ActionButton";const pr=r.forwardRef(({className:t,type:a,...r},n)=>e("input",{type:a,className:sr("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:n,...r}));pr.displayName="Input";const fr=b("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),gr=r.forwardRef(({className:t,...a},r)=>e(gt.Root,{ref:r,className:sr(fr(),t),...a}));gr.displayName=gt.Root.displayName;const vr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));vr.displayName="Card";const br=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("flex flex-col space-y-1.5 p-6",t),...a}));br.displayName="CardHeader";const yr=r.forwardRef(({className:t,...a},r)=>e("h3",{ref:r,className:sr("text-2xl font-semibold leading-none tracking-tight",t),...a}));yr.displayName="CardTitle";const wr=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:sr("text-sm text-muted-foreground",t),...a}));wr.displayName="CardDescription";const xr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("p-6 pt-0",t),...a}));xr.displayName="CardContent";const Nr=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("flex items-center p-6 pt-0",t),...a}));Nr.displayName="CardFooter";const kr=r.forwardRef(({className:t,orientation:a="horizontal",decorative:r=!0,...n},s)=>e(bt.Root,{ref:s,decorative:r,orientation:a,className:sr("shrink-0 bg-border","horizontal"===a?"h-[1px] w-full":"h-full w-[1px]",t),...n}));kr.displayName=bt.Root.displayName;const Cr=vt.Root,Sr=vt.Trigger,Er=vt.Portal,_r=vt.Close,Pr=r.forwardRef(({className:t,...a},r)=>e(vt.Overlay,{ref:r,className:sr("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a}));Pr.displayName=vt.Overlay.displayName;const Rr={sm:"sm:max-w-[420px]",md:"sm:max-w-lg",lg:"sm:max-w-2xl",xl:"sm:max-w-4xl",full:"max-w-[85vw]"},Tr=r.forwardRef(({className:a,children:r,size:n="md",...s},i)=>t(Er,{children:[e(Pr,{}),t(vt.Content,{ref:i,className:sr("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-[85vw] max-h-[85vh] translate-x-[-50%] translate-y-[-50%] border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",Rr[n],a),...s,children:[r,t(vt.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e(_,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));Tr.displayName=vt.Content.displayName;const Ar=({className:a,showSeparator:r=!1,children:n,...s})=>t("div",{className:sr("flex flex-col flex-shrink-0",a),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(kr,{className:"mt-2"})]});Ar.displayName="DialogHeader";const Ir=({className:t,...a})=>e("div",{className:sr("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});Ir.displayName="DialogBody";const Mr=({className:a,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[e(kr,{className:"mb-4"}),e("div",{className:sr("flex flex-row justify-end gap-2",a),...n,children:r})]});Mr.displayName="DialogFooter";const Or=r.forwardRef(({className:t,...a},r)=>e(vt.Title,{ref:r,className:sr("text-lg font-semibold leading-none tracking-tight",t),...a}));Or.displayName=vt.Title.displayName;const Lr=r.forwardRef(({className:t,...a},r)=>e(vt.Description,{ref:r,className:sr("text-sm text-muted-foreground",t),...a}));Lr.displayName=vt.Description.displayName;const Dr=wt,Fr=r.createContext({}),jr=({...t})=>e(Fr.Provider,{value:{name:t.name},children:e(xt,{...t})}),zr=()=>{const e=r.useContext(Fr),t=r.useContext($r),{getFieldState:a,formState:n}=yt(),s=a(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...s}},$r=r.createContext({}),Ur=r.forwardRef(({className:t,...a},n)=>{const s=r.useId();return e($r.Provider,{value:{id:s},children:e("div",{ref:n,className:sr("space-y-2",t),...a})})});Ur.displayName="FormItem";const Vr=r.forwardRef(({className:t,...a},r)=>{const{error:n,formItemId:s}=zr();return e(gr,{ref:r,className:sr(n&&"text-destructive",t),htmlFor:s,...a})});Vr.displayName="FormLabel";const Wr=r.forwardRef(({...t},a)=>{const{error:r,formItemId:n,formDescriptionId:s,formMessageId:i}=zr();return e(g,{ref:a,id:n,"aria-describedby":r?`${s} ${i}`:`${s}`,"aria-invalid":!!r,...t})});Wr.displayName="FormControl";const Br=r.forwardRef(({className:t,...a},r)=>{const{formDescriptionId:n}=zr();return e("p",{ref:r,id:n,className:sr("text-sm text-muted-foreground",t),...a})});Br.displayName="FormDescription";const Hr=r.forwardRef(({className:t,children:a,...r},n)=>{const{error:s,formMessageId:i}=zr(),o=s?String(s?.message):a;return o?e("p",{ref:n,id:i,className:sr("text-sm font-medium text-destructive",t),...r,children:o}):null});Hr.displayName="FormMessage";const qr=Ct.Root,Kr=Ct.Group,Gr=Ct.Value,Xr=r.forwardRef(({className:a,children:r,...n},s)=>t(Ct.Trigger,{ref:s,className:sr("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",a),...n,children:[r,e(Ct.Icon,{asChild:!0,children:e(P,{className:"h-4 w-4 opacity-50"})})]}));Xr.displayName=Ct.Trigger.displayName;const Jr=r.forwardRef(({className:t,...a},r)=>e(Ct.ScrollUpButton,{ref:r,className:sr("flex cursor-default items-center justify-center py-1",t),...a,children:e(R,{className:"h-4 w-4"})}));Jr.displayName=Ct.ScrollUpButton.displayName;const Qr=r.forwardRef(({className:t,...a},r)=>e(Ct.ScrollDownButton,{ref:r,className:sr("flex cursor-default items-center justify-center py-1",t),...a,children:e(P,{className:"h-4 w-4"})}));Qr.displayName=Ct.ScrollDownButton.displayName;const Yr=r.forwardRef(({className:a,children:r,position:n="popper",container:s,collisionBoundary:i,...o},l)=>e(Ct.Portal,{container:s,children:t(Ct.Content,{ref:l,className:sr("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:n,collisionBoundary:i,...o,children:[e(Jr,{}),e(Ct.Viewport,{className:sr("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),e(Qr,{})]})}));Yr.displayName=Ct.Content.displayName;const Zr=r.forwardRef(({className:t,...a},r)=>e(Ct.Label,{ref:r,className:sr("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a}));Zr.displayName=Ct.Label.displayName;const en=r.forwardRef(({className:a,children:r,...n},s)=>t(Ct.Item,{ref:s,className:sr("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Ct.ItemIndicator,{children:e(T,{className:"h-4 w-4"})})}),e(Ct.ItemText,{children:r})]}));en.displayName=Ct.Item.displayName;const tn=r.forwardRef(({className:t,...a},r)=>e(Ct.Separator,{ref:r,className:sr("-mx-1 my-1 h-px bg-muted",t),...a}));tn.displayName=Ct.Separator.displayName;const an=r.forwardRef(({className:t,...a},r)=>e(St.Root,{ref:r,className:sr("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",t),...a,children:e(St.Indicator,{className:sr("flex items-center justify-center text-current"),children:e(T,{className:"h-4 w-4"})})}));an.displayName=St.Root.displayName;const rn=r.forwardRef(({className:t,...a},r)=>e("textarea",{className:sr("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:r,...a}));rn.displayName="Textarea";const nn=b("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),sn=r.forwardRef(({className:t,variant:a,...r},n)=>e("div",{ref:n,className:sr(nn({variant:a}),t),...r}));sn.displayName="Badge";const on={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ln({size:t="md",className:a}){return e(A,{className:sr("animate-spin text-muted-foreground",on[t],a)})}function cn({isLoading:r,children:n,className:s,type:i="spinner",size:o="md"}){return r?"overlay"===i?t("div",{className:sr("relative",s),children:[n,e("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e(ln,{size:o})})]}):e("div","skeleton"===i?{className:sr("animate-pulse",s),children:e("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:sr("flex items-center justify-center py-8",s),children:e(ln,{size:o})}):e(a,{children:n})}const dn=({...t})=>e(S,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:e(D,{className:"h-4 w-4"}),info:e(L,{className:"h-4 w-4"}),warning:e(O,{className:"h-4 w-4"}),error:e(M,{className:"h-4 w-4"}),loading:e(I,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...t}),un=Et.Root,mn=Et.Trigger,hn=r.forwardRef(({className:t,align:a="center",sideOffset:r=4,container:n,...s},i)=>e(Et.Portal,{container:n,children:e(Et.Content,{ref:i,align:a,sideOffset:r,className:sr("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...s})}));hn.displayName=Et.Content.displayName;const pn=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...a}));pn.displayName="Command";const fn=({children:t,...a})=>e("div",{...a,children:e(pn,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:t})}),gn=r.forwardRef(({className:t,...a},r)=>e("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e("input",{ref:r,className:sr("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",t),...a})}));gn.displayName="CommandInput";const vn=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...a}));vn.displayName="CommandList";const bn=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("py-6 text-center text-sm text-muted-foreground",t),...a}));bn.displayName="CommandEmpty";const yn=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...a}));yn.displayName="CommandGroup";const wn=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("-mx-1 h-px bg-border",t),...a}));wn.displayName="CommandSeparator";const xn=r.forwardRef(({className:t,disabled:a,onSelect:r,value:n,...s},i)=>e("div",{ref:i,className:sr("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",t),"data-disabled":a,onClick:()=>!a&&r?.(n||""),...s}));xn.displayName="CommandItem";const Nn=({className:t,...a})=>e("span",{className:sr("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});function kn({className:t,...a}){return e("div",{className:sr("animate-pulse rounded-md bg-muted",t),...a})}Nn.displayName="CommandShortcut";const Cn={},Sn=(e,t,a,r)=>{Rn(a)&&Cn[a]||(Rn(a)&&(Cn[a]=new Date),((e,t,a,r)=>{const n=[a,{code:t,...r||{}}];if(e?.services?.logger?.forward)return e.services.logger.forward(n,"warn","react-i18next::",!0);Rn(n[0])&&(n[0]=`react-i18next:: ${n[0]}`),e?.services?.logger?.warn?e.services.logger.warn(...n):console})(e,t,a,r))},En=(e,t)=>()=>{if(e.isInitialized)t();else{const a=()=>{setTimeout(()=>{e.off("initialized",a)},0),t()};e.on("initialized",a)}},_n=(e,t,a)=>{e.loadNamespaces(t,En(e,a))},Pn=(e,t,a,r)=>{if(Rn(a)&&(a=[a]),e.options.preload&&e.options.preload.indexOf(t)>-1)return _n(e,a,r);a.forEach(t=>{e.options.ns.indexOf(t)<0&&e.options.ns.push(t)}),e.loadLanguages(t,En(e,r))},Rn=e=>"string"==typeof e,Tn=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,An={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},In=e=>An[e];let Mn={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:e=>e.replace(Tn,In),transDefaultProps:void 0};let On;const Ln={type:"3rdParty",init(e){((e={})=>{Mn={...Mn,...e}})(e.options.react),(e=>{On=e})(e)}},Dn=s();class Fn{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(e=>{this.usedNamespaces[e]||(this.usedNamespaces[e]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var jn,zn={exports:{}},$n={};var Un,Vn,Wn={};
2
2
  /**
3
3
  * @license React
4
4
  * use-sync-external-store-shim.development.js
@@ -7,4 +7,4 @@ import{jsx as e,jsxs as t,Fragment as a}from"react/jsx-runtime";import*as r from
7
7
  *
8
8
  * This source code is licensed under the MIT license found in the
9
9
  * LICENSE file in the root directory of this source tree.
10
- */var vs=(gs||(gs=1,"production"===process.env.NODE_ENV?hs.exports=function(){if(ms)return ps;ms=1;var e=s,t="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},a=e.useState,r=e.useEffect,n=e.useLayoutEffect,i=e.useDebugValue;function o(e){var a=e.getSnapshot;e=e.value;try{var r=a();return!t(e,r)}catch(s){return!0}}var l="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var s=t(),l=a({inst:{value:s,getSnapshot:t}}),d=l[0].inst,c=l[1];return n(function(){d.value=s,d.getSnapshot=t,o(d)&&c({inst:d})},[e,s,t]),r(function(){return o(d)&&c({inst:d}),e(function(){o(d)&&c({inst:d})})},[e]),i(s),s};return ps.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:l,ps}():hs.exports=(fs||(fs=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!a(e,r)}catch(s){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var t=s,a="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useState,n=t.useEffect,i=t.useLayoutEffect,o=t.useDebugValue,l=!1,d=!1,c="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(s,c){l||void 0===t.startTransition||(l=!0);var u=c();if(!d){var m=c();a(u,m)||(d=!0)}var h=(m=r({inst:{value:u,getSnapshot:c}}))[0].inst,p=m[1];return i(function(){h.value=u,h.getSnapshot=c,e(h)&&p({inst:h})},[s,u,c]),n(function(){return e(h)&&p({inst:h}),s(function(){e(h)&&p({inst:h})})},[s]),o(u),u};bs.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:c,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),bs)),hs.exports);const ys={t:(e,t)=>{return rs(t)?t:"object"==typeof(a=t)&&null!==a&&rs(t.defaultValue)?t.defaultValue:Array.isArray(e)?e[e.length-1]:e;var a},ready:!1},xs=()=>()=>{},Ns=(e,t={})=>{const{i18n:a}=t,{i18n:r,defaultNS:s}=i(cs)||{},n=a||r||ls;n&&!n.reportNamespaces&&(n.reportNamespaces=new us),n||Zr(n,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const m=o(()=>({...os,...n?.options?.react,...t}),[n,t]),{useSuspense:h,keyPrefix:p}=m,f=e||s||n?.options?.defaultNS,g=rs(f)?[f]:f||["translation"],b=o(()=>g,g);n?.reportNamespaces?.addUsedNamespaces?.(b);const v=l(0),y=d(e=>{if(!n)return xs;const{bindI18n:t,bindI18nStore:a}=m,r=()=>{v.current+=1,e()};return t&&n.on(t,r),a&&n.store.on(a,r),()=>{t&&t.split(" ").forEach(e=>n.off(e,r)),a&&a.split(" ").forEach(e=>n.store.off(e,r))}},[n,m]),x=l(),N=d(()=>{if(!n)return ys;const e=!(!n.isInitialized&&!n.initializedStoreOnce)&&b.every(e=>((e,t,a={})=>t.languages&&t.languages.length?t.hasLoadedNamespace(e,{lng:a.lng,precheck:(t,r)=>{if(a.bindI18n&&a.bindI18n.indexOf("languageChanging")>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!r(t.isLanguageChangingTo,e))return!1}}):(Zr(t,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:t.languages}),!0))(e,n,m)),a=t.lng||n.language,r=v.current,s=x.current;if(s&&s.ready===e&&s.lng===a&&s.keyPrefix===p&&s.revision===r)return s;const i={t:n.getFixedT(a,"fallback"===m.nsMode?b:b[0],p),ready:e,lng:a,keyPrefix:p,revision:r};return x.current=i,i},[n,b,p,m,t.lng]),[w,k]=c(0),{t:C,ready:S}=vs.useSyncExternalStore(y,N,N);u(()=>{if(n&&!S&&!h){const e=()=>k(e=>e+1);t.lng?as(n,t.lng,b,e):ts(n,b,e)}},[n,t.lng,b,S,h,w]);const _=n||{},P=l(null),E=l(),I=e=>{const t=Object.getOwnPropertyDescriptors(e);t.__original&&delete t.__original;const a=Object.create(Object.getPrototypeOf(e),t);if(!Object.prototype.hasOwnProperty.call(a,"__original"))try{Object.defineProperty(a,"__original",{value:e,writable:!1,enumerable:!1,configurable:!1})}catch(r){}return a},T=o(()=>{const e=_,t=e?.language;let a=e;e&&(P.current&&P.current.__original===e?E.current!==t?(a=I(e),P.current=a,E.current=t):a=P.current:(a=I(e),P.current=a,E.current=t));const r=[C,a,S];return r.t=C,r.i18n=a,r.ready=S,r},[C,_,S,_.resolvedLanguage,_.language,_.languages]);if(n&&h&&!S)throw new Promise(e=>{const a=()=>e();t.lng?as(n,t.lng,b,a):ts(n,b,a)});return T};function ws({i18n:e,defaultNS:t,children:a}){const r=o(()=>({i18n:e,defaultNS:t}),[e,t]);return m(cs.Provider,{value:r},a)}const ks=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Cs({multiple:a,options:r,value:s,onChange:n,getOptionValue:i,getOptionLabel:l,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:b,sortOptions:v,maxDisplayedBadges:y,popoverContainer:x,onOpen:N,onClose:w}){const{t:k}=Ns(),[C,P]=c(!1),[I,T]=c(""),A=o(()=>s?Array.isArray(s)?s:[s]:[],[s]),R=o(()=>{if(!x)return;let e=x,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),r=a.overflowY||a.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,t++}}catch{}return e??void 0},[x]),O=o(()=>{const e=r.map(e=>({original:e,value:i(e),label:l(e)}));return v?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[r,i,l,v]),L=o(()=>{if(!I)return O;const e=ks(I);return O.filter(t=>ks(t.label).includes(e))},[O,I]),F=o(()=>O.filter(e=>A.includes(e.value)),[O,A]),j=(e,t)=>{t.preventDefault(),t.stopPropagation(),n&&n(a?A.filter(t=>t!==e):"")},M=y?F.slice(0,y):F,z=y&&F.length>y?F.length-y:0;return t("div",{className:Fa("space-y-2",b),children:[u&&t(Ha,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t(Dr,{open:C,onOpenChange:e=>{P(e),e?N?.():(T(""),w?.())},modal:!1,children:[e($r,{asChild:!0,children:t(Va,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:Fa("w-full justify-between min-h-10 h-auto",0===F.length&&"text-muted-foreground"),children:[0===F.length?t("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),d]}):a?t("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[M.map(a=>t(Lr,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&j(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>j(a.value,e),children:e(S,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),z>0&&t(Lr,{variant:"outline",className:"gap-1",children:["+",z]})]}):t("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),F[0]?.label]}),e(_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(Ur,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:R,collisionBoundary:R,children:t(Vr,{children:[e(Br,{placeholder:p,value:I,onChange:e=>T(e.target.value)}),e(Wr,{children:0===r.length?e(Hr,{children:h}):0===L.length?e(Hr,{children:k("no_results")}):e(Kr,{children:L.map(r=>t(Qr,{value:r.value,onSelect:()=>(e=>{if(n)if(a){const t=A.includes(e)?A.filter(t=>t!==e):[...A,e];n(t)}else n(e),P(!1)})(r.value),className:"cursor-pointer",children:[e(E,{className:Fa("mr-2 h-4 w-4",A.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Ss({multiple:a=!1,options:r,items:s,value:n,onChange:i,onValueChange:o,getOptionValue:l=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:b=!1,error:v,className:y,sortOptions:x=!0,maxDisplayedBadges:N,popoverContainer:w,onOpen:k,onClose:C}){const{t:S}=Ns(),_=s||r||[],P=o||i,E=c||S("select_placeholder"),I=h||S("no_results"),T=p||S("search_placeholder");if(b)return t("div",{className:Fa("space-y-2",y),children:[u&&t(Ha,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Xr,{className:"h-10 w-full"})]});const A="string"==typeof v?v:v instanceof Error?v.message:v?"Erro ao carregar dados":void 0;return A?t("div",{className:Fa("space-y-2",y),children:[u&&t(Ha,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:A})]})]}):e(Cs,{multiple:a,options:_,value:n||(a?[]:""),onChange:P,getOptionValue:l,getOptionLabel:d,placeholder:E,label:u,icon:m,emptyMessage:I,searchPlaceholder:T,disabled:f,required:g,className:y,sortOptions:x,maxDisplayedBadges:N,popoverContainer:w,onOpen:k,onClose:C})}var _s=Object.defineProperty;class Ps{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}static parseJwtPayload(e){try{const s=e.split(".");if(3!==s.length)return null;const n=s[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),t=atob(e),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);const r=new TextDecoder("utf-8").decode(a);return JSON.parse(r)}catch(t){try{const e=this.normalizeBase64Url(n),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(n),t=atob(e);return JSON.parse(t)}catch(r){throw r}}}}catch(s){return null}}static validateTokens(e,t){const a=[],r=[];try{t.split(".")[1],e.split(".")[1];const s=this.parseJwtPayload(t),n=this.parseJwtPayload(e);if(!s){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:r}}let i=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.push(e),i=!1}const o=Math.floor(Date.now()/1e3);if(n?.exp&&n.exp<o){const e="Access token expirado - pode precisar de refresh";a.push(e),i=!1}if(s.exp&&s.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:a,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:a,errors:r}}catch(s){const e=`Erro na validação de tokens: ${s}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:r}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}((e,t,a)=>{t in e?_s(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a})(Ps,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const Es="qualiex_access_token",Is="qualiex_id_token",Ts="supabase_token",As="oauth_state",Rs="oauth_nonce",Os="selected_alias",Ls="manual_logout",Fs={setAccessToken:e=>localStorage.setItem(Es,e),getAccessToken:()=>localStorage.getItem(Es),setIdToken:e=>localStorage.setItem(Is,e),getIdToken:()=>localStorage.getItem(Is),getSupabaseToken:()=>localStorage.getItem(Ts),setOAuthState:e=>sessionStorage.setItem(As,e),getOAuthState:()=>sessionStorage.getItem(As),clearOAuthState:()=>sessionStorage.removeItem(As),setOAuthNonce:e=>sessionStorage.setItem(Rs,e),getOAuthNonce:()=>sessionStorage.getItem(Rs),clearOAuthNonce:()=>sessionStorage.removeItem(Rs),setSelectedAlias:e=>localStorage.setItem(Os,e),getSelectedAlias:()=>localStorage.getItem(Os),clearSelectedAlias:()=>localStorage.removeItem(Os),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Fs.getAccessToken()||!Fs.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(Ts,e),Fs._clearValidationCache()},areAllTokensValid:()=>{const e=Fs.getAccessToken(),t=Fs.getIdToken();if(!e||!t)return!1;try{const a=Ps.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=Fs.getAccessToken(),a=Fs.getIdToken(),r=Fs.getSupabaseToken();return t&&Fs.isTokenExpired(t)&&(localStorage.removeItem(Es),e=!0),a&&Fs.isTokenExpired(a)&&(localStorage.removeItem(Is),e=!0),r&&Fs.isTokenExpired(r)&&(localStorage.removeItem(Ts),e=!0),e},clearAll:()=>{localStorage.removeItem(Es),localStorage.removeItem(Is),localStorage.removeItem(Ts),localStorage.removeItem(Os),localStorage.removeItem(Ls),sessionStorage.removeItem(As),sessionStorage.removeItem(Rs)},setManualLogout:()=>localStorage.setItem(Ls,"true"),isManualLogout:()=>"true"===localStorage.getItem(Ls),clearManualLogout:()=>localStorage.removeItem(Ls),isTokenExpired:e=>{try{return Ps.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Fs._validationCache.isValid=!1,Fs._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Fs.getSupabaseToken();if(!e)return!1;if(Fs.isTokenExpired(e))return Fs._clearValidationCache(),Fs._handleExpiredToken(),!1;const t=Date.now();return t-Fs._validationCache.timestamp<Fs._validationCache.cacheValidityMs?Fs._validationCache.isValid:(Fs._validationCache.isValid=!0,Fs._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>Fs.isSupabaseTokenValid()?Fs.getSupabaseToken():null,_handleExpiredToken:()=>{Fs.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Fs.isSupabaseTokenValid())return null;const e=Fs.getSupabaseToken();if(!e)return null;try{const t=Ps.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,r=t.place_id||null,s=t.place_name||null;let n=t.company_id;if(!n&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=t[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===a){n=e[7];break}}}return{alias:a,companyId:n,placeId:r,placeName:s,payload:t}}catch(t){return Fs._handleExpiredToken(),null}},getCompanyId:e=>{const t=Fs.getAccessToken();if(t)try{const a=Ps.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const t=r.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(s){}const a=Fs.extractTokenData();if(a?.companyId)return a.companyId;const r=Fs.getIdToken();if(r)try{const t=Ps.parseJwtPayload(r);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const t=r.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(s){}return null},getCurrentCompanyId:()=>{const e=Fs.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Fs.getIdToken();if(!e)return[];try{const t=Ps.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=t[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}};var js=Object.defineProperty,Ms=(e,t,a)=>((e,t,a)=>t in e?js(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const zs=new class{constructor(){Ms(this,"errors",[]),Ms(this,"toastCount",0),Ms(this,"lastToastTime",0)}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);w.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?"Sessão Expirada":t.includes("token")||t.includes("autenticação")?"Erro de Autenticação":t.includes("api")||t.includes("network")?"Erro de Conexão":"Erro"}success(e,t){w.success(e,{description:t})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};var Ds=Object.defineProperty,$s=(e,t,a)=>((e,t,a)=>t in e?Ds(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const Us=import.meta.env.VITE_SUPABASE_URL,Vs=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,qs=class e{constructor(){$s(this,"client"),$s(this,"currentToken",null),$s(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:Vs};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return ut(Us,Vs,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,t)}})}static getInstance(){return e.instance||(e.instance=new e),e.instance}getClient(){const e=Fs.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{const t=JSON.parse(atob(e.split(".")[1])),a=Math.floor(Date.now()/1e3);return t.exp>a}catch(t){return zs.handleError(t instanceof Error?t:"❌ Supabase - Error validating token",!1),!1}}};$s(qs,"instance");let Bs=qs;function Ws(){return Bs.getInstance().getClient()}class Hs{static async generateToken(e,t,a,r=!1){try{if(!r){const e=Fs.getSupabaseToken();if(e&&Fs.isSupabaseTokenValid())return e}const s=Ws(),{data:n,error:i}=await s.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(a?.(),null):n?.access_token&&n.access_token?(Fs.setSupabaseToken(n.access_token),n.access_token):null}catch(s){return s instanceof Error&&(s.message.includes("401")||s.message.includes("Unauthorized"))&&a?.(),null}}}var Ks=Object.defineProperty,Gs=(e,t,a)=>((e,t,a)=>t in e?Ks(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);class Qs{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=Fs.getAccessToken(),t=Fs.getSelectedAlias();if(!e||!t)return null;const a=await Hs.generateToken(e,t,this.onLogoutCallback||void 0,!1);return a?(Fs.setSupabaseToken(a),a):null}catch(e){return null}finally{this.isRegenerating=!1}}}Gs(Qs,"isRegenerating",!1),Gs(Qs,"onLogoutCallback",null);class Js{static handleError(e){if(!e)return!1;const t=e.message||e.toString();return!!this.isAuthenticationError(e,t)&&(Fs.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,t){if(401===e.status||401===e.statusCode)return!0;const a=t.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>a.includes(e))}static async wrapAsync(e){try{return await e}catch(t){if(!this.handleError(t))throw t;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}var Xs=Object.defineProperty;class Ys{static async handleApiError(e){if(!e||this.isRetrying)return!1;const t=e.status||e.statusCode,a=e.message||e.toString();if(401===t||a.includes("401")||a.includes("Unauthorized")){this.isRetrying=!0;try{return await Qs.attemptRegeneration()?(this.isRetrying=!1,!0):(Js.handleError(e),this.isRetrying=!1,!1)}catch(r){return Js.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Fs.getAccessToken();return e?Fs.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}((e,t,a)=>{((e,t,a)=>{t in e?Xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a})(e,t+"",a)})(Ys,"isRetrying",!1);var Zs=Object.defineProperty,en=(e,t,a)=>((e,t,a)=>t in e?Zs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const tn=new class{constructor(){en(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const r=Ys.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Fs.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{n.searchParams.append(e,t)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,t){try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let r=a;if(a.data)r=a.data;else{if(!Array.isArray(a))return zs.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=a}if(!Array.isArray(r))return zs.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(a){if(await Ys.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let r=a;if(a.data)r=a.data;else{if(!Array.isArray(a))return zs.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=a}return Array.isArray(r)?r.map(this.mapToQualiexUser):(zs.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return zs.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}const s=a instanceof Error?a.message:"Erro ao buscar usuários da API Qualiex";return zs.handleError(s,!0),[]}}async fetchUserById(e,t,a){try{return(await this.fetchUsers(t,a)).find(t=>t.userId===e)||null}catch(r){return zs.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,t){const a=await this.fetchUsers(e,t),r=new Map;return a.forEach(e=>{r.set(e.userId,e)}),r}async getUsers(e){const t=Fs.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId):[]}async getAllUsers(e){return this.getUsers(e)}},an={oauth:{authUrl:import.meta.env.VITE_OAUTH_AUTH_URL,clientId:import.meta.env.VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},rn={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},sn={debounceDelay:500},nn=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||import.meta.env.DEV},on={crud:e=>[e],list:(e,t)=>[e,"list",t],detail:(e,t)=>[e,"detail",t]},ln={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},dn=()=>ln,cn={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},un={success:{created:e=>`${e} criado com sucesso`,updated:e=>`${e} atualizado com sucesso`,deleted:e=>`${e} removido com sucesso`},error:{create:e=>`Erro ao criar ${e}`,update:e=>`Erro ao atualizar ${e}`,delete:e=>`Erro ao remover ${e}`,load:e=>`Erro ao carregar ${e}`}};function mn(e,t){const a=dn(),r=t||a.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function hn(e,t){const a=dn(),r=t||a.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function pn(e,t){const a=dn(),r=t||a.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function fn(e,t){return t&&t.length>0?t.map(e=>({idField:e.idField,nameField:e.nameField||mn(e.idField),emailField:e.emailField||hn(e.idField),usernameField:e.usernameField||pn(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:mn(e),emailField:hn(e),usernameField:pn(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const gn=new Map;class bn{static async fetchQualiexUsers(e,t){const a=`${t}_${e}`,r=gn.get(a);if(r&&Date.now()-r.timestamp<3e5)return r.users;const s=await tn.fetchUsers(e,t);return gn.set(a,{users:s,timestamp:Date.now()}),s}static extractUserIds(e,t){const a=new Set;for(const r of e)for(const e of t){const t=r[e.idField];t&&"string"==typeof t&&""!==t.trim()&&a.add(t)}return a}static indexUsers(e){const t=new Map;for(const a of e)a.id&&t.set(a.id,a),a.userId&&t.set(a.userId,a);return t}static enrichEntity(e,t,a){const r={...e};for(const s of t){const t=e[s.idField];if(!t)continue;const n=a.get(t);if(n){if(s.nameField){r[s.nameField]||(r[s.nameField]=n.userName||n.displayName||null)}if(s.emailField){r[s.emailField]||(r[s.emailField]=n.userEmail||null)}if(s.usernameField){r[s.usernameField]||(r[s.usernameField]=n.userName||null)}}}return r}static async enrichWithUserData(e,t){if(!Array.isArray(e)||0===e.length)return e;try{if(!Fs.areAllTokensValid())return e;const a=Fs.extractTokenData();if(!a)return e;const{alias:r,companyId:s}=a;if(!r||!s)return e;const n=fn(t.userIdFields,t.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const i=await this.fetchQualiexUsers(r,s),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,n,o))}catch(a){return zs.handleError(a instanceof Error?a:new Error(`[QualiexEnrichment.${t.entityName}] Erro crítico`),!1),e}}static async enrichWithResponsibleNames(e,t){return this.enrichWithUserData(e,{entityName:t.entityName,userIdFields:["id_user"],userFieldsMapping:[{idField:"id_user",nameField:"responsible_name"}]})}}const vn=["responsible_name"],yn=e=>vn.includes(e);function xn(e,t,a){const r="string"==typeof e?{tableName:e,searchFields:t||[],schemaName:a||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:s,searchFields:n,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Fs.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Ws().schema(o).from(s)},u=(e,t,a,r)=>{let s=c().select(i||"*",{count:"exact"});s=s.eq("is_removed",!1),Object.entries(r).forEach(([e,t])=>{void 0!==t&&""!==t&&(Array.isArray(t)?s=s.in(e,t):"object"==typeof t&&t&&"operator"in t?"not_null"===t.operator?s=s.not(e,"is",null):"is_null"===t.operator&&(s=s.is(e,null)):null!==t&&(s=s.eq(e,t)))}),s=((e,t)=>{if(t&&n.length>0){const a=n.map(e=>`${e}.ilike.%${t}%`).join(",");return e.or(a)}return e})(s,e);const o=t.includes(".");return o||yn(t)||(s=s.order(t,{ascending:"asc"===a})),{query:s,isForeignKey:o}},m=async(e,t,a,s,n)=>{const i=fn(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===t||e.emailField===t||e.usernameField===t),o=t.includes(".");if(yn(t)||o||i){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},i=await this.getAll(e);if(!i?.data?.length)return i;const d=await bn.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const s=t.split(".").reduce((e,t)=>e?.[t],e)||"",n=t.split(".").reduce((e,t)=>e?.[t],r)||"",i=String(s).localeCompare(String(n),"pt-BR");return"asc"===a?i:-i}):((e,t,a)=>[...e].sort((e,r)=>{const s=e[t]||"",n=r[t]||"",i=s.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===a?i:-i}))(d,t,a);const u=((e,t=1,a=25)=>{const r=(t-1)*a,s=r+a,n=e.slice(r,s);return{data:n,pagination:{currentPage:t,totalPages:Math.ceil(e.length/a),totalItems:n.length,totalCount:e.length,itemsPerPage:a,hasNextPage:s<e.length,hasPreviousPage:t>1}}})(c,s,n);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalCount,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await bn.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})};return{async getAll(e={}){const{search:t,sortField:a,sortDirection:n,page:i,limit:o,additionalFilters:c}=(e=>{const{search:t="",sortField:a="updated_at",sortDirection:r="desc",page:s=1,limit:n=25,...i}=e;return{search:t,sortField:a,sortDirection:r,page:s,limit:n,additionalFilters:i}})(e),{query:h}=u(t,a,n,c),p=((e,t,a)=>{const r=(t-1)*a,s=r+a-1;return e.range(r,s)})(h,i,o),{data:f,error:g,count:b}=await p;if(g)throw new Error(`Error fetching ${s}: ${g.message}`);let v=((e,t,a,r)=>{const s=Math.ceil((t||0)/r);return{data:e,currentPage:a,totalPages:s,totalItems:t||0,itemsPerPage:r,hasNextPage:a<s,hasPreviousPage:a>1}})(f||[],b,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const t=fn(r.userIdFields,r.userFieldsMapping);return e.some(e=>t.some(t=>e[t.idField]))})(v.data)){const e=await m(v.data,a,n,i,o);if(!Array.isArray(e))return e;v={...v,data:e}}return v},async getById(e){const{data:t,error:a}=await c().select(i||"*").eq("id",e).maybeSingle();if(a)throw new Error(`Error fetching ${s}: ${a.message}`);return t},async create(e){const t=ja(e),a=Object.entries(t).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),{data:r,error:n}=await c().insert(a).select().single();if(n)throw new Error(`Error creating ${s}: ${n.message}`);if(!r)throw new Error(`No data returned from create ${s} operation`);return r},async update(e,t){const a={...ja(t),updated_at:(new Date).toISOString()},{data:r,error:n}=await c().update(a).eq("id",e).select().single();if(n)throw new Error(`Error updating ${s}: ${n.message}`);if(!r)throw new Error(`No data returned from update ${s} operation`);return r},async delete(e){const t={is_removed:!0,updated_at:(new Date).toISOString()},{error:a}=await c().update(t).eq("id",e);if(a)throw new Error(`Error soft deleting ${s}: ${a.message}`)}}}const Nn=()=>{Fs.clearManualLogout()},wn=e=>e?.placeId||null,kn=e=>e?.placeName||null,Cn=e=>({placeId:wn(e),placeName:kn(e)}),Sn=class{static async initialize(){try{if(!Fs.hasAllTokens()||!Fs.areAllTokensValid())return Fs.clearExpiredTokens(),{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};const t=Fs.getAccessToken(),a=Fs.getIdToken();Nn();const r=this.extractUserFromIdToken(a),s=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(t),i=Fs.extractTokenData(),o=i?.alias;let l=null;if(o&&s.some(e=>e.alias===o))l=o;else{const e=Fs.getSelectedAlias(),t=e&&s.some(t=>t.alias===e);l=t?e:n||s[0]?.alias||null}!Fs.isSupabaseTokenValid()&&l&&await Qs.attemptRegeneration();let d=null;if(l){const e=Fs.getCompanyId(l),t=s.find(e=>e.alias===l);t&&(d={id:e||t.id,name:t.name,alias:t.alias})}let c=null,u=null;if(r?.id&&l){const t=Fs.getCompanyId(l);if(t)try{const e=(await tn.fetchActiveUsersMap(l,t)).get(r.id);if(e){const t=Cn(e);c=t.placeId,u=t.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:s,selectedUnit:d,userId:r?.id||null,userAlias:r?.id||null,placeId:c,placeName:u,activePlaceId:c,activePlaceName:u}}catch(e){return{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null}}}static async loginDev(){try{const e=Ws(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=Fs.generateOAuthState();Fs.setOAuthState(e);const t=Fs.generateOAuthNonce();Fs.setOAuthNonce(t);const a=`${window.location.origin}/callback`,r=new URL(an.oauth.authUrl);r.searchParams.set("client_id",an.oauth.clientId),r.searchParams.set("response_type",an.oauth.responseType),r.searchParams.set("scope",an.oauth.scope),r.searchParams.set("redirect_uri",a),r.searchParams.set("state",e),r.searchParams.set("nonce",t),r.searchParams.set("response_mode","fragment"),nn(),window.location.href=r.toString()}static async processCallback(){try{if(Fs.hasAllTokens()){if(!Fs.getValidSupabaseToken()){Fs.getAccessToken();await Qs.attemptRegeneration()}return!0}const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),r=a("access_token"),s=a("id_token"),n=a("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!r||!s)throw new Error("Tokens não encontrados na URL de callback");Fs.setAccessToken(r),Fs.setIdToken(s),Nn();const i=this.extractAliasFromAccessToken(r);if(i)Fs.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Fs.setSelectedAlias(e[0].alias)}if(!await Qs.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return Fs.clearOAuthState(),Fs.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Fs.setManualLogout(),Fs.clearAll(),window.location.href="/login"}static decodeToken(e){return Ps.parseJwtPayload(e)}static extractUserFromIdToken(e){const t=this.decodeToken(e);return t?{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier}:null}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const r=t[e].split(";");if(r.length>=4)a.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,s]=t[e].split("|");r&&s&&a.push({id:"",alias:r.trim(),name:s.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}};Qs.setLogoutCallback(()=>{Sn.logout()});let _n=Sn;const Pn=n(void 0),En=({children:t})=>{const[a,r]=c({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let s=null;try{s=mt()}catch{}const[n,i]=c(!1),[l,m]=c(0),h=d(e=>{r(t=>({...t,...e}))},[]),p=d(e=>{r(t=>({...t,isLoading:e}))},[]),f=d(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=d(async e=>{try{p(!0);const r=Fs.getAccessToken();if(!r)return;const n=await Hs.generateToken(r,e.alias,void 0,!0);if(!n)return;Fs.setSupabaseToken(n),Fs.setSelectedAlias(e.alias);const i=Fs.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Fs.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let c=null,u=null;if(a.user?.id&&o&&l)try{const e=(await tn.fetchActiveUsersMap(o,l)).get(a.user.id);if(e){const t=Cn(e);c=t.placeId,u=t.placeName}}catch(t){}h({alias:o,selectedUnit:d,placeId:c,placeName:u,activePlaceId:c,activePlaceName:u}),s&&(await s.clear(),await new Promise(e=>setTimeout(e,100)))}catch(t){}finally{p(!1)}},[h,s,p,a.user]),b=d(async()=>await _n.processCallback(),[]),v=d(async()=>{_n.logout(),f(),s&&await s.clear()},[f,s]),y=d(e=>{i(e)},[]),x=d(()=>{m(e=>e+1)},[]),N=d(()=>{m(e=>e+1)},[]);u(()=>{if(!a.isAuthenticated)return;let e=!0;const t=setInterval(()=>{e&&(Fs.areAllTokensValid()||e&&v())},6e5);return()=>{e=!1,clearInterval(t)}},[a.isAuthenticated,v]),u(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const t=await _n.initialize();if(!e)return;t&&t.isAuthenticated?h({user:t.user,companies:t.companies,alias:t.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:t.selectedUnit,userId:t.userId,userAlias:t.userAlias,placeId:t.placeId,placeName:t.placeName,activePlaceId:t.activePlaceId,activePlaceName:t.activePlaceName}):e&&p(!1)}catch(t){e&&(Js.handleError(t),p(!1))}})(),()=>{e=!1}},[h,p,v]);const w=o(()=>({...a,logout:v,processCallback:b,switchUnit:g,availableUnits:a.companies,isSearchVisible:n,setSearchVisible:y,clearSearch:x,refreshData:N}),[a.user,a.companies,a.alias,a.isAuthenticated,a.isLoading,a.selectedUnit,a.userId,a.userAlias,a.placeId,a.placeName,a.activePlaceId,a.activePlaceName,v,b,g,n,y,x,N]);return e(Pn.Provider,{value:w,children:t})},In=()=>{const e=i(Pn);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Tn({queryKey:e,service:t,entityName:a,searchFields:r,additionalFilters:s={},onSuccess:n}){const[i,l]=bt(),u=mt(),{alias:m,userId:h,isAuthenticated:p}=In(),f=d(t=>{const a=`${e}_${t}`,r=i.get(a);return r||(i.get(t)||"")},[i,e]),g=f("search"),b=f("sortField")||rn.sorting.defaultField,v=f("sortDirection")||rn.sorting.defaultDirection,y=parseInt(f("page")||"1"),x=parseInt(f("limit")||String(rn.pagination.defaultPageSize)),N=g,k=o(()=>({search:N,sortField:b,sortDirection:v,page:y,limit:x,...s}),[N,b,v,y,x,s]),C=d(()=>t.getAll(k),[t,k]),S=ht({queryKey:[e,m,h,k],queryFn:C,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${a}". Ensure QueryClientProvider is configured in your app root.`);const _=pt({mutationFn:t.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),w.success(un.success.created(a)),n?.()},onError:e=>{w.error(`${un.error.create(a)}: ${e.message}`)}}),P=pt({mutationFn:({id:e,data:a})=>t.update(e,a),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),w.success(un.success.updated(a)),n?.()},onError:e=>{w.error(`${un.error.update(a)}: ${e.message}`)}}),E=pt({mutationFn:t.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),w.success(un.success.deleted(a))},onError:e=>{w.error(`${un.error.delete(a)}: ${e.message}`)}}),I=d(t=>{const a={...Object.fromEntries(i)};Object.entries(t).forEach(([t,r])=>{const s=`${e}_${t}`;""===r||0===r?delete a[s]:a[s]=String(r)}),delete a.sortField,delete a.sortDirection,l(a)},[i,l,e]),T=d(e=>{I({search:e,page:1})},[I]),A=d(e=>{I({sortField:e,sortDirection:b===e&&"asc"===v?"desc":"asc",page:1})},[b,v,I]),R=d(e=>{I({page:e})},[I]),O=d(e=>{I({limit:e,page:1})},[I]),L=d(()=>{const t=Object.fromEntries(i),a=`${e}_`,r=Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith(a)));l(r)},[l,i,e]),[F,j]=c([]),M=d(e=>{j(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),z=d(()=>{const e=S?.data?.data.map(e=>e.id)||[];j(t=>t.length===e.length?[]:e)},[S?.data?.data]),D=d(()=>{j([])},[]),$=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&F.length===e.length},[F,S?.data?.data]),U=pt({mutationFn:async e=>{await Promise.all(e.map(e=>t.delete(e)))},onSuccess:(t,r)=>{u.invalidateQueries({queryKey:[e]}),w.success(`${r.length} ${a}(s) deletado(s) com sucesso`),D()},onError:e=>{w.error(`Erro ao deletar itens: ${e.message}`)}}),V=d((e,t)=>{const a=t?t(e):e;e.id?P.mutate({id:e.id,data:a}):_.mutate({...a,alias:m})},[m,_,P]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||rn.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:_?.isPending??!1,isUpdating:P?.isPending??!1,isDeleting:E?.isPending??!1,error:S?.error||null,searchTerm:g,sortField:b,sortDirection:v,currentPage:y,itemsPerPage:x,queryKey:e,createEntity:_.mutate,updateEntity:(e,t)=>P.mutate({id:e,data:t}),deleteEntity:E.mutate,save:V,handleSearch:T,handleSort:A,handlePageChange:R,handleItemsPerPageChange:O,clearFilters:L,refetch:S.refetch,selectedIds:F,selectItem:M,selectAll:z,clearSelection:D,isAllSelected:$,bulkDelete:e=>U.mutateAsync(e),isBulkDeleting:U.isPending}}function An(e){const t=xn({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment||!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:t,useCrudHook:(a,r)=>Tn({queryKey:e.tableName,service:{...t,getAll:async(e={})=>await t.getAll({...e})},entityName:e.entityName,additionalFilters:a,onSuccess:r})}}const Rn=Nt.Root,On=Nt.Trigger,Ln=Nt.Portal,Fn=r.forwardRef(({className:t,...a},r)=>e(Nt.Overlay,{className:Fa("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a,ref:r}));Fn.displayName=Nt.Overlay.displayName;const jn=r.forwardRef(({className:a,...r},s)=>t(Ln,{children:[e(Fn,{}),e(Nt.Content,{ref:s,className:Fa("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...r})]}));jn.displayName=Nt.Content.displayName;const Mn=({className:t,...a})=>e("div",{className:Fa("flex flex-col space-y-2 text-center sm:text-left bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-6 rounded-t-lg",t),...a});Mn.displayName="AlertDialogHeader";const zn=({className:t,...a})=>e("div",{className:Fa("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});zn.displayName="AlertDialogFooter";const Dn=r.forwardRef(({className:t,...a},r)=>e(Nt.Title,{ref:r,className:Fa("text-lg font-semibold",t),...a}));Dn.displayName=Nt.Title.displayName;const $n=r.forwardRef(({className:t,...a},r)=>e(Nt.Description,{ref:r,className:Fa("text-sm text-muted-foreground",t),...a}));$n.displayName=Nt.Description.displayName;const Un=r.forwardRef(({className:t,...a},r)=>e(Nt.Action,{ref:r,className:Fa(Ua(),t),...a}));Un.displayName=Nt.Action.displayName;const Vn=r.forwardRef(({className:t,...a},r)=>e(Nt.Cancel,{ref:r,className:Fa(Ua({variant:"outline"}),"mt-2 sm:mt-0",t),...a}));Vn.displayName=Nt.Cancel.displayName;const qn=({open:a,onOpenChange:r,item:s,onConfirm:n,entityName:i="item",isDeleting:o=!1})=>{const{t:l}=Ns(),d=()=>{r(!1)};return s?e(Rn,{open:a,onOpenChange:d,children:t(jn,{className:"sm:max-w-[420px] bg-white",children:[t("button",{onClick:d,className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Fechar"})]}),t("div",{className:"flex flex-col items-center text-center space-y-3 py-2",children:[e("div",{className:"w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e(j,{className:"w-8 h-8 text-destructive"})}),e(Dn,{className:"text-xl font-semibold",children:"Tem certeza?"}),e($n,{asChild:!0,children:t("div",{className:"text-sm text-muted-foreground",children:[e("p",{children:"Você está prestes a excluir este registro."}),e("p",{children:"Esta ação não pode ser desfeita."})]})})]}),t("div",{className:"flex flex-row gap-2 justify-center mt-6",children:[e(Un,{onClick:()=>{s&&(n(s),r(!1))},disabled:o,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:l(o?"deleting":"confirm_delete")}),e(Vn,{onClick:d,className:"mt-0 border-none bg-transparent hover:bg-muted text-foreground shadow-none",children:"Cancelar"})]})]})}):null},Bn=r.forwardRef(({className:t,...a},r)=>e("table",{ref:r,className:Fa("w-full caption-bottom text-sm",t),...a}));Bn.displayName="Table";const Wn=r.forwardRef(({className:t,...a},r)=>e("thead",{ref:r,className:Fa("[&_tr]:border-b sticky top-0 z-[1] bg-background",t),...a}));Wn.displayName="TableHeader";const Hn=r.forwardRef(({className:t,...a},r)=>e("tbody",{ref:r,className:Fa("[&_tr:last-child]:border-0",t),...a}));Hn.displayName="TableBody";const Kn=r.forwardRef(({className:t,...a},r)=>e("tfoot",{ref:r,className:Fa("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...a}));Kn.displayName="TableFooter";const Gn=r.forwardRef(({className:t,...a},r)=>e("tr",{ref:r,className:Fa("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",t),...a}));Gn.displayName="TableRow";const Qn=r.forwardRef(({className:t,...a},r)=>e("th",{ref:r,className:Fa("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",t),...a}));Qn.displayName="TableHead";const Jn=r.forwardRef(({className:t,...a},r)=>e("td",{ref:r,className:Fa("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",t),...a}));Jn.displayName="TableCell";const Xn=r.forwardRef(({className:t,...a},r)=>e("caption",{ref:r,className:Fa("mt-4 text-sm text-muted-foreground",t),...a}));function Yn({rows:a=5,columns:r=4}){return e("div",{className:"w-full",children:t("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((t,a)=>e(Xr,{className:"h-4 w-24"},a))})}),e("div",{children:Array.from({length:a}).map((t,a)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((t,a)=>e(Xr,{className:"h-4 w-20"},a))})},a))})]})})}function Zn({count:a=3}){return e("div",{className:"space-y-4",children:Array.from({length:a}).map((a,r)=>t(Ka,{children:[t(Ga,{children:[e(Xr,{className:"h-4 w-3/4"}),e(Xr,{className:"h-3 w-1/2"})]}),e(Xa,{children:t("div",{className:"space-y-2",children:[e(Xr,{className:"h-3 w-full"}),e(Xr,{className:"h-3 w-2/3"})]})})]},r))})}function ei({fields:a=4}){return t("div",{className:"space-y-4",children:[Array.from({length:a}).map((a,r)=>t("div",{className:"space-y-2",children:[e(Xr,{className:"h-4 w-24"}),e(Xr,{className:"h-10 w-full"})]},r)),t("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Xr,{className:"h-10 w-20"}),e(Xr,{className:"h-10 w-20"})]})]})}function ti(){return t("div",{className:"flex items-center justify-between p-4 border-b",children:[t("div",{className:"flex items-center space-x-3",children:[e(Xr,{className:"h-8 w-8 rounded-full"}),e(Xr,{className:"h-6 w-32"})]}),t("div",{className:"flex items-center space-x-2",children:[e(Xr,{className:"h-8 w-8"}),e(Xr,{className:"h-8 w-24"})]})]})}function ai(){return e("div",{className:"w-64 border-r bg-muted/10",children:t("div",{className:"p-4",children:[e(Xr,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((a,r)=>t("div",{className:"flex items-center space-x-3 p-2",children:[e(Xr,{className:"h-4 w-4"}),e(Xr,{className:"h-4 w-20"})]},r))})]})})}Xn.displayName="TableCaption";const ri={default:z,search:M,error:F};function si({icon:a,title:r,description:s,action:n,className:i,variant:o="default"}){const l=a?()=>a:ri[o];return t("div",{className:Fa("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e(l,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),s&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),n&&e(Va,{onClick:n.onClick,variant:"outline",children:n.label})]})}const ni=wt.Root,ii=wt.Trigger,oi=wt.Group,li=wt.Portal,di=wt.Sub,ci=wt.RadioGroup,ui=r.forwardRef(({className:a,inset:r,children:s,...n},i)=>t(wt.SubTrigger,{ref:i,className:Fa("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",a),...n,children:[s,e(D,{className:"ml-auto h-4 w-4"})]}));ui.displayName=wt.SubTrigger.displayName;const mi=r.forwardRef(({className:t,...a},r)=>e(wt.SubContent,{ref:r,className:Fa("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a}));mi.displayName=wt.SubContent.displayName;const hi=r.forwardRef(({className:t,sideOffset:a=4,...r},s)=>e(wt.Portal,{children:e(wt.Content,{ref:s,sideOffset:a,className:Fa("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-white p-1 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:bg-gray-800 dark:border-gray-700",t),...r})}));hi.displayName=wt.Content.displayName;const pi=r.forwardRef(({className:t,inset:a,...r},s)=>e(wt.Item,{ref:s,className:Fa("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a&&"pl-8",t),...r}));pi.displayName=wt.Item.displayName;const fi=r.forwardRef(({className:a,children:r,checked:s,...n},i)=>t(wt.CheckboxItem,{ref:i,className:Fa("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:s,...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(wt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));fi.displayName=wt.CheckboxItem.displayName;const gi=r.forwardRef(({className:a,children:r,...s},n)=>t(wt.RadioItem,{ref:n,className:Fa("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(wt.ItemIndicator,{children:e($,{className:"h-2 w-2 fill-current"})})}),r]}));gi.displayName=wt.RadioItem.displayName;const bi=r.forwardRef(({className:t,inset:a,...r},s)=>e(wt.Label,{ref:s,className:Fa("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...r}));bi.displayName=wt.Label.displayName;const vi=r.forwardRef(({className:t,...a},r)=>e(wt.Separator,{ref:r,className:Fa("-mx-1 my-1 h-px bg-muted",t),...a}));vi.displayName=wt.Separator.displayName;const yi=({className:t,...a})=>e("span",{className:Fa("ml-auto text-xs tracking-widest opacity-60",t),...a});yi.displayName="DropdownMenuShortcut";const xi=kt.Root,Ni=kt.Trigger,wi=kt.Group,ki=kt.Portal,Ci=kt.Sub,Si=kt.RadioGroup,_i=r.forwardRef(({className:a,inset:r,children:s,...n},i)=>t(kt.SubTrigger,{ref:i,className:Fa("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",a),...n,children:[s,e(D,{className:"ml-auto h-4 w-4"})]}));_i.displayName=kt.SubTrigger.displayName;const Pi=r.forwardRef(({className:t,...a},r)=>e(kt.SubContent,{ref:r,className:Fa("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a}));Pi.displayName=kt.SubContent.displayName;const Ei=r.forwardRef(({className:t,...a},r)=>e(kt.Portal,{children:e(kt.Content,{ref:r,className:Fa("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})}));Ei.displayName=kt.Content.displayName;const Ii=r.forwardRef(({className:t,inset:a,...r},s)=>e(kt.Item,{ref:s,className:Fa("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a&&"pl-8",t),...r}));Ii.displayName=kt.Item.displayName;const Ti=r.forwardRef(({className:a,children:r,checked:s,...n},i)=>t(kt.CheckboxItem,{ref:i,className:Fa("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:s,...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(kt.ItemIndicator,{children:e(E,{className:"h-4 w-4"})})}),r]}));Ti.displayName=kt.CheckboxItem.displayName;const Ai=r.forwardRef(({className:a,children:r,...s},n)=>t(kt.RadioItem,{ref:n,className:Fa("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(kt.ItemIndicator,{children:e($,{className:"h-2 w-2 fill-current"})})}),r]}));Ai.displayName=kt.RadioItem.displayName;const Ri=r.forwardRef(({className:t,inset:a,...r},s)=>e(kt.Label,{ref:s,className:Fa("px-2 py-1.5 text-sm font-semibold text-foreground",a&&"pl-8",t),...r}));Ri.displayName=kt.Label.displayName;const Oi=r.forwardRef(({className:t,...a},r)=>e(kt.Separator,{ref:r,className:Fa("-mx-1 my-1 h-px bg-border",t),...a}));Oi.displayName=kt.Separator.displayName;const Li=({className:t,...a})=>e("span",{className:Fa("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});Li.displayName="ContextMenuShortcut";const Fi=({onEdit:r,onDelete:s,onToggleStatus:n,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const{t:c}=Ns(),u=[];if(r){const e={icon:U,label:c("edit"),onClick:r};u.push(e)}if(l.forEach(e=>{u.push(e)}),n){const e={icon:i?V:q,label:c(i?"deactivate":"activate"),onClick:n};u.push(e)}if(o&&s){const e={icon:B,label:c("delete"),onClick:s,destructive:!0};u.push(e)}const m="dropdown"===d?pi:Ii;return e(a,{children:u.map((a,r)=>t(m,{onClick:a.onClick,className:Fa("whitespace-normal cursor-pointer",a.destructive&&"text-destructive focus:text-destructive"),children:[e(a.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),a.label]},r))})},ji=({onEdit:a,onDelete:r,canDelete:s=!0,onToggleStatus:n,isActive:i=!0,customActions:o=[]})=>t(ni,{children:[e(ii,{asChild:!0,children:e(Va,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(C,{size:12})})}),e(hi,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(Fi,{onEdit:a?e=>{e?.stopPropagation(),a?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:n?e=>{e?.stopPropagation(),n?.()}:void 0,isActive:i,canDelete:s&&!!r,customActions:o,renderAs:"dropdown"})})]}),Mi=h(({checked:t,onCheckedChange:a})=>e(Ar,{checked:t,onCheckedChange:a}),(e,t)=>e.checked===t.checked),zi=({manager:a,columns:r,onEdit:s,onView:n,onToggleStatus:i,onDelete:l,renderActions:d,customRowActions:m,enableBulkActions:h=!1,onNew:p,newButtonLabel:f,showNewButton:g=!0,customActions:b=[],hideActionBar:v=!1})=>{const{t:y}=Ns(),{setSearchVisible:x}=In(),[N,w]=c(!1);u(()=>(x(!0),()=>x(!1)),[x]),u(()=>{const e=()=>w(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const k=o(()=>(()=>{r.length;let e=0;const t=r.map(t=>{if(t.width)return e+=t.width,{...t,calculatedWidth:t.width,isFixed:!0};{const a=t.minWidth||120,r=t.weight||1;return e+=a,{...t,calculatedWidth:a,weight:r,isFixed:!1}}});return e+=50,t.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r]),C=!v&&(p||b.length>0);return N?a.isLoading?e(Zn,{count:3}):0===a.entities.length?e(si,{title:y("empty_title"),description:y("empty_description"),variant:"search"}):t("div",{className:"flex flex-col h-full",children:[C&&e("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:t("div",{className:"flex items-center gap-2",children:[p&&g&&t(Va,{onClick:p,children:[e(W,{size:16,className:"mr-2"}),f||y("new")]}),b.map((a,r)=>{const s=a.icon;return t(Va,{onClick:a.action,variant:a.variant||"outline",children:[s&&e(s,{size:16,className:"mr-2"}),a.label]},r)})]})}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:a.entities.map(o=>t(xi,{children:[e(Ni,{asChild:!0,children:e(Ka,{className:Fa("overflow-hidden cursor-pointer hover:bg-muted/50",h&&a.selectedIds.includes(o.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?a.selectItem(o.id):s?.(o)},children:e(Xa,{className:"p-4",children:t("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(Mi,{checked:a.selectedIds.includes(o.id),onCheckedChange:()=>a.selectItem(o.id)})}),t("div",{className:"flex-1",children:[r.map(a=>t("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[t("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[a.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:a.render?a.render(o):String(o[a.key]??"")})]},String(a.key))),(s||n||d)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(o):e(ji,{onEdit:s?()=>{s(o)}:void 0,onDelete:l?()=>l(o):void 0,onToggleStatus:i?()=>i(o):void 0,isActive:o.is_actived,customActions:m?m(o):[]})})]})]})})})}),e(Ei,{className:"w-[160px]",children:e(Fi,{onEdit:s?()=>s(o):void 0,onDelete:l?()=>l(o):void 0,onToggleStatus:i?()=>i(o):void 0,isActive:o.is_actived,canDelete:!!l,customActions:m?m(o):[],renderAs:"context"})})]},o.id))})]}):t("div",{className:"flex flex-col h-full",children:[C&&e("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:t("div",{className:"flex items-center gap-2",children:[p&&g&&t(Va,{onClick:p,children:[e(W,{size:16,className:"mr-2"}),f||y("new")]}),b.map((a,r)=>{const s=a.icon;return t(Va,{onClick:a.action,variant:a.variant||"outline",children:[s&&e(s,{size:16,className:"mr-2"}),a.label]},r)})]})}),a.isLoading?e(Yn,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:t(Bn,{className:"table-auto",children:[t("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),k.map((t,a)=>e("col",{style:t.style},a)),e("col",{style:{width:"50px"}})]}),e(Wn,{children:t(Gn,{children:[h&&e(Qn,{className:"w-[50px]",children:e(Mi,{checked:a.isAllSelected,onCheckedChange:a.selectAll})}),r.map(r=>{return e(Qn,{className:`${r.className||""} ${r.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:r.sortable?()=>a.handleSort(String(r.key)):void 0,children:t("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(s=String(r.key),a.sortField!==s?e(H,{size:14,className:"ml-1 opacity-50"}):"asc"===a.sortDirection?e(K,{size:14,className:"ml-1"}):e(G,{size:14,className:"ml-1"}))]})},String(r.key));var s}),e(Qn,{className:"w-[50px] text-center",children:y("actions")})]})}),e(Hn,{children:0===a.entities.length?e(Gn,{children:e(Jn,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(si,{title:y("empty_title"),description:y("empty_description"),variant:"search"})})}):a.entities.map(n=>t(xi,{children:[e(Ni,{asChild:!0,children:t(Gn,{className:Fa("cursor-pointer hover:bg-muted/50",h&&a.selectedIds.includes(n.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?a.selectItem(n.id):s?.(n)},children:[h&&e(Jn,{onClick:e=>e.stopPropagation(),children:e(Mi,{checked:a.selectedIds.includes(n.id),onCheckedChange:()=>a.selectItem(n.id)})}),r.map(t=>e(Jn,{className:t.className,children:t.render?t.render(n):String(n[t.key]??"")},String(t.key))),e(Jn,{className:"text-center",children:d?d(n):e(ji,{onEdit:s?()=>s(n):void 0,onDelete:l?()=>l(n):void 0,onToggleStatus:i?()=>i(n):void 0,isActive:n.is_actived,customActions:m?m(n):[]})})]})}),e(Ei,{className:"w-[160px]",children:e(Fi,{onEdit:s?()=>s(n):void 0,onDelete:l?()=>l(n):void 0,onToggleStatus:i?()=>i(n):void 0,isActive:n.is_actived,canDelete:!!l,customActions:m?m(n):[],renderAs:"context"})})]},n.id))})]})})})]})};function Di(e,t,a,r){const[s,n]=c({}),[i,l]=c({}),d=o(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,t)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(t)}catch(a){return h(e)}},f=(e,t,a)=>{if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length))return`${e.label} é obrigatório`;if(e.validation){let s;if("function"==typeof e.validation?s=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(s=e.validation.custom),s)try{const e=s(t,a);if(e)return e}catch(r){}}};u(()=>{if(!r)return;const e=t=>{const a=[];return t.forEach(t=>{a.push(t),t.fields&&a.push(...e(t.fields))}),a},s=e(d),i={};s.forEach(e=>{let a;if(t&&void 0!==t[e.name]){if(a=t[e.name],null==a&&(a=""),"date"===e.type&&a)if("string"==typeof a){const e=new Date(a);m(e)&&(a=e.toISOString().split("T")[0])}else m(a)&&(a=a.toISOString().split("T")[0])}else a=h(e);i[e.name]=a}),s.forEach(e=>{const t=p(e,i);void 0!==t&&(i[e.name]=t)}),t&&Object.keys(t).forEach(e=>{s.find(t=>t.name===e)||void 0===t[e]||(i[e]=t[e])}),n(i),l({}),a&&a(i)},[d,t,a,r]);const g=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...g(e.fields))}),t},b=()=>{const e=g(d),t={};return e.forEach(e=>{const a=f(e,s[e.name],s);a&&(t[e.name]=a)}),l(t),0===Object.keys(t).length};return{formData:s,errors:i,updateField:(e,t)=>{n(r=>{const s={...r,[e]:t},n=((e,t)=>{let a={...t};const r=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...r(e.fields))}),t};return r(d).filter(t=>t.dependsOn===e).forEach(e=>{const t=p(e,a);void 0!==t&&(a={...a,[e.name]:t})}),a})(e,s);return a&&a(n),n}),i[e]&&l(t=>{const a={...t};return delete a[e],a});const r=g(d).find(t=>t.name===e);if(r){const a=f(r,t,s);a&&l(t=>({...t,[e]:a}))}},validateForm:b,handleSubmit:e=>t=>{t&&(t.preventDefault(),t.stopPropagation()),b()&&e(s)}}}const $i=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Ui=({value:a="#3b82f6",onChange:r,label:s})=>t("div",{className:"space-y-2",children:[s&&e(Ha,{children:s}),t(Dr,{children:[e($r,{asChild:!0,children:t(Va,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:a}}),a]})}),e(Ur,{className:"w-64",children:t("div",{className:"space-y-3",children:[t("div",{children:[e(Ha,{htmlFor:"color-input",children:"Cor personalizada"}),e(Ba,{id:"color-input",type:"color",value:a,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),t("div",{children:[e(Ha,{children:"Cores predefinidas"}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:$i.map(t=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:t},onClick:()=>r?.(t),"aria-label":`Selecionar cor ${t}`},t))})]})]})})]})]}),Vi=r.forwardRef(({className:a,children:r,...s},n)=>t(Ct.Root,{ref:n,className:Fa("relative overflow-hidden",a),...s,children:[e(Ct.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(qi,{}),e(Ct.Corner,{})]}));Vi.displayName=Ct.Root.displayName;const qi=r.forwardRef(({className:t,orientation:a="vertical",...r},s)=>e(Ct.ScrollAreaScrollbar,{ref:s,orientation:a,className:Fa("flex touch-none select-none transition-colors","vertical"===a&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===a&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...r,children:e(Ct.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));qi.displayName=Ct.ScrollAreaScrollbar.displayName;const Bi={Star:De,Heart:ze,Home:Me,User:je,Settings:Fe,Mail:Le,Phone:Oe,Calendar:Re,MapPin:Ae,Camera:Te,Image:Ie,Music:Ee,Video:Pe,Book:_e,Bookmark:Se,Search:M,Filter:Ce,Edit:U,Trash2:B,Plus:W,Minus:ke,Check:E,X:S,ChevronDown:_,ChevronUp:P,ChevronLeft:we,ChevronRight:D,ArrowUp:K,ArrowDown:G,ArrowLeft:Ne,ArrowRight:xe,Clock:ye,Bell:ve,AlertCircle:F,Info:be,HelpCircle:ge,Download:fe,Upload:pe,Share:he,Copy:me,Save:ue,FileText:ce,Folder:de,FolderOpen:le,Archive:oe,Lock:ie,Unlock:ne,Eye:se,EyeOff:re,Shield:ae,Key:te,Zap:ee,Flame:Z,Sparkles:Y,Award:X,Trophy:J,Target:Q},Wi=({value:a="Star",onChange:r,label:s})=>{const{t:n}=Ns(),[i,o]=c(""),l=Object.entries(Bi).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=Bi[a]||De;return t("div",{className:"space-y-2",children:[s&&e(Ha,{children:s}),t(Dr,{children:[e($r,{asChild:!0,children:t(Va,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(d,{className:"h-4 w-4 mr-2"}),a]})}),e(Ur,{className:"w-80",children:t("div",{className:"space-y-3",children:[t("div",{children:[e(Ha,{htmlFor:"icon-search",children:n("search")}),e(Ba,{id:"icon-search",placeholder:n("search"),value:i,onChange:e=>o(e.target.value)})]}),e(Vi,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:l.map(([t,s])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(a===t?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(t),title:t,children:e(s,{className:"h-4 w-4"})},t))})})]})})]})]})},Hi=r.forwardRef(({className:t,...a},r)=>e(St.Root,{className:Fa("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...a,ref:r,children:e(St.Thumb,{className:Fa("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Hi.displayName=St.Root.displayName;const Ki=(e={})=>{const{user:t,alias:a}=In(),{enabled:r=!0}=e;return ht({queryKey:["qualiex-users",a],queryFn:()=>tn.getUsers(a),enabled:r&&!!a&&!!t,retry:2,retryDelay:1e3})},Gi=({value:t="",onChange:a,placeholder:r,disabled:s,className:n,enabled:i})=>{const{t:o}=Ns(),{data:l=[],isLoading:d,error:c}=Ki({enabled:i});return e(Ss,{value:t,onChange:a,options:l,isLoading:d,error:c,getOptionValue:e=>e.userId,getOptionLabel:e=>e.userName,placeholder:r||o("search_placeholder"),searchPlaceholder:o("search_placeholder"),emptyMessage:o("no_results"),disabled:s,className:n})};function Qi({title:a,sections:r,initialData:n,onSubmit:i,onCancel:u,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const{t:g}=Ns(),[b,v]=c(r?.[0]?.id||""),y=l(null),[x,N]=c(null),w=d(e=>{y.current=e,N(e)},[]),k=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:S,updateField:_,handleSubmit:P}=Di(k,n,void 0,m),E=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),I=o(()=>{const e=E.find(e=>e.id===b);if(e&&!e.disabled)return b;const t=E.find(e=>!e.disabled);return t?.id||b},[E,b]);s.useEffect(()=>{I!==b&&v(I)},[I,b]);const T=E.find(e=>e.id===I),A=a=>{const r=(a.computedValue,C[a.name]),s=void 0!==r?r:"",n=S[a.name];switch(a.type){case"group":const r="horizontal"===a.layout,i=r?`flex gap-3 w-full ${a.className||""}`:"space-y-3",o=r?Fa("space-y-2 w-full",a.wrapperClassName):Fa("space-y-2",a.className,a.wrapperClassName);return t("div",{className:o,children:[a.label,e("div",{className:i,children:a.fields?.map(e=>A(e))})]},a.name);case"user-select":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Gi,{value:s||"",onChange:e=>_(a.name,e),placeholder:a.placeholder,disabled:a.disabled,className:n?"border-red-500":""}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"textarea":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rr,{id:a.name,value:s||"",onChange:e=>{_(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,rows:a.rows,maxLength:a.maxLength,className:`${n?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"select":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t(Nr,{value:String(s),onValueChange:e=>{_(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,children:[e(Cr,{className:`${n?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e(kr,{placeholder:a.placeholder})}),e(Pr,{children:a.options?.map(t=>e(Ir,{value:t.value,children:t.label},t.value))})]}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"multiselect":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ss,{options:a.options||[],value:Array.isArray(s)?s:[],onChange:e=>_(a.name,e),placeholder:a.placeholder,disabled:a.disabled,error:n,popoverContainer:x,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"date":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ba,{id:a.name,type:"date",value:String(s),onChange:e=>_(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,className:Fa("w-full",n?"border-red-500":"",a.disabled?"bg-gray-100 cursor-not-allowed":"")}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"color":return t("div",{children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ba,{id:a.name,type:"color",value:s||a.defaultValue||"#000000",onChange:e=>_(a.name,e.target.value),className:"h-10"}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},a.name);case"color-picker":return t("div",{children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ui,{value:s||a.defaultValue||"#3b82f6",onChange:e=>_(a.name,e)}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},a.name);case"icon-picker":return t("div",{children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Wi,{value:s||a.defaultValue||"Star",onChange:e=>_(a.name,e)}),n&&e("p",{className:"text-sm text-destructive mt-1",children:n})]},a.name);case"custom":if(!a.component)return null;const l=a.component,d="function"==typeof a.componentProps?a.componentProps(C):a.componentProps||{};return t("div",{className:`space-y-2 ${a.className||""}`,children:[a.label&&t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:s,onChange:e=>{_(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,error:n,popoverContainer:x,...d}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"number":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ba,{id:a.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const t=e.target.value,r=""===t?null:Number(t);_(a.name,r)},placeholder:a.placeholder,disabled:a.disabled,className:`${n?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:a.min,step:a.step||"1"}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"checkbox":return t("div",{className:`flex items-center space-x-2 ${a.className||""}`,children:[e(Ar,{id:a.name,checked:!!s,onCheckedChange:e=>_(a.name,e),disabled:a.disabled}),t(Ha,{htmlFor:a.name,className:"cursor-pointer",children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name);case"switch":return t("div",{className:`flex items-center justify-between space-x-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Hi,{id:a.name,checked:!!s,onCheckedChange:e=>_(a.name,e),disabled:a.disabled}),n&&e("p",{className:"text-sm text-red-500 mt-2",children:n})]},a.name);default:return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ba,{id:a.name,type:"text",value:s||"",onChange:e=>{_(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${n?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:a.disabled}),n&&e("p",{className:"text-sm text-red-500",children:n})]},a.name)}},R=d(()=>{if(!T)return null;if(T.disabled)return t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(T.component){const t=T.component;return e(t,{formData:C,updateField:_,errors:S,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(A)})},[T,C,_,S,f,A]),O=t("div",{className:"flex flex-col max-h-[80vh]",children:[E.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:E.map(t=>e(Va,{variant:I===t.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const t=E.find(t=>t.id===e);t&&!t.disabled&&v(e)})(t.id),disabled:t.disabled,className:t.disabled?"opacity-50 cursor-not-allowed":"",children:t.title},t.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:g("loading")})}):t("form",{onSubmit:P(i),className:"space-y-3 md:space-y-4",children:[R(),t("div",{className:"flex justify-end space-x-2 pt-4",children:[e(Va,{type:"button",variant:"outline",onClick:u,children:g("cancel")}),e(Va,{type:"submit",disabled:p,children:h||g("save")})]})]})})]});return e(er,{open:m,onOpenChange:e=>{!1===e&&!0===m&&u()},children:t(nr,{ref:w,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[t(ir,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e(dr,{className:"text-white",children:a}),e(cr,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),O]})})}function Ji({currentPage:r,totalPages:s,totalItems:n,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const c=(r-1)*i+1,u=Math.min(r*i,n);return t("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===d&&t(a,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),t(Nr,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(Cr,{className:"h-8 w-[70px]",children:e(kr,{})}),t(Pr,{children:[e(Ir,{value:"10",children:"10"}),e(Ir,{value:"25",children:"25"}),e(Ir,{value:"50",children:"50"}),e(Ir,{value:"100",children:"100"})]})]})]})}),t("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",u," de ",n," itens"]}),t("div",{className:"flex items-center gap-1",children:[e(Va,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e($e,{size:16})}),e(Va,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(we,{size:16})}),t("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:"de"}),e("span",{className:"text-sm font-medium",children:s})]}),e(Va,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===s,className:"h-8 w-8 p-0",children:e(D,{size:16})}),e(Va,{variant:"outline",size:"sm",onClick:()=>o(s),disabled:r===s,className:"h-8 w-8 p-0",children:e(Ue,{size:16})})]})]})}function Xi({manager:t}){return e(Ji,{currentPage:t.pagination.currentPage,totalPages:t.pagination.totalPages,totalItems:t.pagination.totalItems,itemsPerPage:t.pagination.itemsPerPage,onPageChange:t.handlePageChange,onItemsPerPageChange:t.handleItemsPerPageChange,variant:"full"})}const Yi=({selectedCount:a,onClearSelection:r,onBulkDelete:s,customActions:n=[],isLoading:i=!1})=>{const{t:o}=Ns();return t("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[t("div",{className:"flex items-center gap-3",children:[e("span",{className:"text-sm font-medium",children:o("selected_count",{count:a})}),t(Va,{variant:"ghost",size:"sm",onClick:r,className:"h-7 px-2",children:[e(S,{size:14,className:"mr-1"}),o("clear")]})]}),t("div",{className:"flex items-center gap-2",children:[n.map((a,r)=>{const s=a.icon;return t(Va,{variant:a.variant||"outline",size:"sm",onClick:()=>a.action([]),disabled:i,className:"h-7",children:[s&&e(s,{size:14,className:"mr-1"}),a.label]},r)}),s&&t(Va,{variant:"destructive",size:"sm",onClick:s,disabled:i,className:"h-7",children:[e(B,{size:14,className:"mr-1"}),o("delete")]})]})]})},Zi={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},eo={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},to={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function ao({children:t,direction:a="column",gap:r="md",align:s="stretch",justify:n="start",wrap:i=!1,className:o}){return e("div",{className:Fa("flex","column"===a?"flex-col":"flex-row",Zi[r],eo[s],to[n],i&&"flex-wrap",o),children:t})}function ro({manager:r,filters:s,inline:n=!1}){const{t:i}=Ns(),{isSearchVisible:o}=In(),l=r.searchTerm,d=t(a,{children:[s.some(e=>"search"===e.type)&&!o&&t("div",{className:"relative flex-1",children:[e(M,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Ba,{placeholder:i("search"),value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),s.filter(e=>"select"===e.type&&e.options).map((a,r)=>t("select",{value:a.value||"",onChange:e=>a.onChange?.(e.target.value),className:"h-10 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[a.placeholder&&e("option",{value:"",children:a.placeholder}),a.options.map(t=>e("option",{value:t.value,children:t.label},t.value))]},`select-${r}`)),s.filter(e=>"custom"===e.type&&e.component).map((t,a)=>{const r=t.component;return e("div",{className:n?"":"w-full sm:w-auto",children:e(r,{...t.props})},`custom-${a}`)}),l&&t(Va,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(S,{className:"h-4 w-4 mr-2"}),i("clear")]})]});return n?e("div",{className:"flex items-center gap-2",children:d}):e(ao,{direction:"column",gap:"md",className:"mb-6",children:e(ao,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:d})})}function so({manager:a,config:r,formSections:s,onSave:n,onToggleStatus:i,defaultSort:o}){a&&a.queryKey;const{t:l}=Ns(),{setSearchVisible:d}=In(),[m,h]=bt(),[p,f]=c(!1),[g,b]=c(null),[v,y]=c({isOpen:!1,entityId:null,entityName:""}),[x,N]=c({isOpen:!1,count:0});u(()=>(d(!0),()=>{d(!1)}),[d]),u(()=>{if(o&&a){const e=`${a.queryKey}_sortField`,t=`${a.queryKey}_sortDirection`;if(!m.has(e)&&!m.has(t)){const a=Object.fromEntries(m);a[e]=o.column,a[t]=o.direction,h(a)}}},[]);return t("div",{className:"flex-1 flex flex-col h-full",children:[r.enableBulkActions&&a.selectedIds.length>0&&e(Yi,{selectedCount:a.selectedIds.length,onClearSelection:a.clearSelection,onBulkDelete:r.bulkActions&&r.bulkActions.length>0?void 0:()=>{N({isOpen:!0,count:a.selectedIds.length})},customActions:r.bulkActions,isLoading:a.isBulkDeleting}),t("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[t("div",{className:"flex items-center gap-2",children:[t(Va,{onClick:()=>{r.onNew?r.onNew():(b(null),f(!0))},children:[e(W,{size:16,className:"mr-2"}),l("new")]}),r.customActions?.map((a,r)=>t(Va,{onClick:a.action,variant:a.variant||"outline",children:[a.icon&&e(a.icon,{size:16,className:"mr-2"}),a.label]},r))]}),r.filters&&r.filters.length>0&&e("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e(ro,{manager:a,filters:r.filters,inline:!0})})]}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(a.entities,a)}):e(zi,{manager:a,columns:r.columns,onEdit:e=>{r.onEdit?r.onEdit(e):(b(e),f(!0))},onDelete:e=>{y({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:i,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(Xi,{manager:a})}),!r.useCustomRouting&&e(Qi,{open:p,title:g?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:s,initialData:g||void 0,onSubmit:e=>{n(e),f(!1),b(null)},onCancel:()=>{f(!1),b(null)},isLoading:a.isLoading,submitButtonText:l(g?"update":"create")}),e(qn,{open:v.isOpen,onOpenChange:()=>{y({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{v.entityId&&(a.deleteEntity(v.entityId),y({isOpen:!1,entityId:null,entityName:""}))},item:v.entityId?{id:v.entityId,title:v.entityName}:void 0,entityName:r.entityName,isDeleting:a.isDeleting}),e(qn,{open:x.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),onConfirm:()=>(a.bulkDelete?.(a.selectedIds),void N({isOpen:!1,count:0})),item:{id:"bulk",title:`${x.count} ${1===x.count?r.entityName:r.entityNamePlural}`},entityName:r.entityNamePlural,isDeleting:a.isBulkDeleting,isBulk:!0,bulkCount:x.count})]})}function no(t){return({manager:a})=>{const{manager:r,config:s,onSave:n,onEdit:i,onToggleStatus:o}=t,l=a??r,d={entityName:s.entityName,entityNamePlural:s.entityNamePlural,filters:s.filters||[],columns:s.columns,cardFields:s.cardFields||[],enableBulkActions:s.enableBulkActions??!1,bulkActions:s.bulkActions||[],customActions:s.customActions,customRowActions:s.customRowActions,customListView:s.customListView,onEdit:i||s.onEdit};return e(so,{manager:l,config:d,formSections:s.formSections,onSave:n,onToggleStatus:o,defaultSort:s.defaultSort})}}function io(e,t,a){return r=>{if(r.id){const t=a(r);e.updateEntity(r.id,t)}else{const a=t(r);e.createEntity(a)}}}function oo(e,t,a={}){const r=[];return Object.keys(t).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const a=t[e],s={key:e,header:co(e),label:co(e),...lo(e,a),sortable:!0,searchable:"string"==typeof a};r.push(s)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...a}}function lo(e,t){const a=e.toLowerCase();return a.includes("email")?{type:"email",required:!0}:a.includes("phone")||a.includes("tel")?{type:"tel"}:a.includes("description")||a.includes("content")||a.includes("notes")?{type:"textarea"}:a.includes("status")||a.includes("type")||a.includes("category")?{type:"select",options:[]}:"boolean"==typeof t?{type:"boolean"}:"number"==typeof t?{type:"number"}:t instanceof Date?{type:"date"}:{type:"text"}}function co(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const uo=r.forwardRef(({className:t,value:a,...r},s)=>e(_t.Root,{ref:s,className:Fa("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...r,children:e(_t.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(a||0)}%)`}})}));function mo({steps:a,currentStepIndex:r,onStepClick:s,className:n}){return e("div",{className:Fa("flex items-center justify-between mb-6",n),children:a.map((r,n)=>t("div",{className:"flex items-center flex-1",children:[e("div",{className:Fa("flex items-center justify-center w-10 h-10 rounded-full border-2 transition-colors font-medium",r.isActive&&"border-primary bg-primary text-primary-foreground",r.isCompleted&&"border-primary bg-primary text-primary-foreground",!r.isActive&&!r.isCompleted&&"border-muted-foreground/30 text-muted-foreground bg-background",s&&!r.isDisabled&&"cursor-pointer hover:border-primary/50",r.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>s&&!r.isDisabled&&s(n),role:s&&!r.isDisabled?"button":void 0,tabIndex:s&&!r.isDisabled?0:void 0,"aria-label":`${r.label} - ${r.isCompleted?"Completo":r.isActive?"Atual":"Pendente"}`,children:r.isCompleted?e(E,{className:"w-5 h-5"}):n+1}),n<a.length-1&&e("div",{className:Fa("flex-1 h-0.5 mx-2 transition-colors",r.isCompleted?"bg-primary":"bg-muted-foreground/30"),"aria-hidden":"true"})]},r.id))})}function ho({steps:a,currentStepIndex:r,onStepClick:s,className:n}){return e("div",{className:Fa("flex items-center gap-2 mb-6 overflow-x-auto",n),children:a.map((r,n)=>t("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[t("div",{className:Fa("flex items-center gap-2 px-3 py-2 rounded-md transition-colors",r.isActive&&"bg-primary text-primary-foreground font-medium",r.isCompleted&&"bg-primary/10 text-primary",!r.isActive&&!r.isCompleted&&"bg-muted text-muted-foreground",s&&!r.isDisabled&&"cursor-pointer hover:bg-primary/20",r.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>s&&!r.isDisabled&&s(n),role:s&&!r.isDisabled?"button":void 0,tabIndex:s&&!r.isDisabled?0:void 0,"aria-label":`${r.label} - ${r.isCompleted?"Completo":r.isActive?"Atual":"Pendente"}`,children:[e("span",{className:"text-sm font-medium",children:n+1}),e("span",{className:"text-sm",children:r.label}),r.isCompleted&&e(E,{className:"w-4 h-4 ml-1"})]}),n<a.length-1&&e("span",{className:"text-muted-foreground","aria-hidden":"true",children:"/"})]},r.id))})}function po({steps:a,currentStepIndex:r,className:s}){const n=a[r],i=(r+1)/a.length*100;return t("div",{className:Fa("mb-6 space-y-2",s),children:[t("div",{className:"flex items-center justify-between text-sm",children:[t("span",{className:"text-muted-foreground",children:["Etapa ",r+1," de ",a.length]}),e("span",{className:"font-medium",children:n?.label})]}),e(uo,{value:i,className:"h-2"})]})}function fo({isFirstStep:r,isLastStep:s,canGoNext:n,canGoPrevious:i,isLoading:o,onPrevious:l,onNext:d,onSubmit:c,previousButtonText:u,nextButtonText:m,submitButtonText:h}){const{t:p}=Ns();return t(a,{children:[e("div",{children:i&&!r&&e(Va,{type:"button",variant:"outline",onClick:l,disabled:o,children:u||p("previous")})}),t("div",{className:"flex gap-2",children:[n&&!s&&e(Va,{type:"button",onClick:d,disabled:o,children:m||p("next")}),s&&e(Va,{type:"button",onClick:c,disabled:o,children:o?p("saving"):h||p("save")})]})]})}function go({title:a,sections:r,initialData:n,onSubmit:i,onCancel:u,open:m,submitButtonText:h,isLoading:p=!1,usersData:f,showProgressIndicator:g=!0,progressType:b="stepper",validateOnNext:v=!0,allowSkipSections:y=!1,previousButtonText:x,nextButtonText:N,onStepChange:w,onStepValidationFail:k,renderProgressIndicator:C,renderButtons:S,currentStepIndex:_,onCurrentStepChange:P}){const[E,I]=c(0),T=_??E,A=P??I,R=l(null),[O,L]=c(null),F=d(e=>{R.current=e,L(e)},[]),j=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:M,errors:z,updateField:D,handleSubmit:$}=Di(j,n,void 0,m);s.useEffect(()=>{m&&A(0)},[m,A]);const U=d(()=>{const e=r[T];if(!e)return!0;const t=e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e),a={};let s=!0;return t.forEach(e=>{const t=M[e.name];if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length)&&(a[e.name]=`${e.label} é obrigatório`,s=!1),e.validation&&"function"==typeof e.validation){const r=e.validation(t,M);r&&(a[e.name]=r,s=!1)}}),!s&&k&&k(T,a),s},[r,T,M,k]),V=d(()=>{if(v&&!U())return;const e=T+1;e<r.length&&(A(e),w?.(e,r[e].id))},[T,r,v,U,A,w]),q=d(()=>{const e=T-1;e>=0&&(A(e),w?.(e,r[e].id))},[T,r,A,w]),B=d(()=>{let e=!0;for(let t=0;t<r.length;t++){r[t].fields.flatMap(e=>"group"===e.type?e.fields||[]:e).forEach(t=>{const a=M[t.name];t.required&&(""===a||null==a||Array.isArray(a)&&0===a.length)&&(e=!1)})}e&&$(i)()},[r,M,$,i]),W=o(()=>r.map((e,t)=>({index:t,id:e.id,label:e.label||e.id,isActive:t===T,isCompleted:t<T,isDisabled:e.disabled||!1})),[r,T]),H=0===T,K=T===r.length-1,G=o(()=>{if(!g)return null;if(C)return C(T,r.length,r);const t=y?e=>{A(e),w?.(e,r[e].id)}:void 0;switch(b){case"breadcrumb":return e(ho,{steps:W,currentStepIndex:T,onStepClick:t});case"progressbar":return e(po,{steps:W,currentStepIndex:T});default:return e(mo,{steps:W,currentStepIndex:T,onStepClick:t})}},[g,C,b,W,T,r,y,A,w]),Q=o(()=>{const t={isFirstStep:H,isLastStep:K,canGoNext:T<r.length-1,canGoPrevious:T>0,isLoading:p,onPrevious:q,onNext:V,onSubmit:B,previousButtonText:x,nextButtonText:N,submitButtonText:h};return S?S(t):e(fo,{...t})},[H,K,T,r.length,p,q,V,B,x,N,h,S]),J=a=>{const r=(a.computedValue,M[a.name]),s=void 0!==r?r:"",n=z[a.name];switch(a.type){case"group":return t("div",{className:"space-y-2",children:[a.label&&e(Ha,{className:"text-sm font-medium",children:a.label}),e("div",{className:Fa("grid gap-4",1===a.columns&&"grid-cols-1",2===a.columns&&"grid-cols-1 md:grid-cols-2",3===a.columns&&"grid-cols-1 md:grid-cols-3",4===a.columns&&"grid-cols-1 md:grid-cols-4",!a.columns&&"grid-cols-1"),children:a.fields?.map(e=>J(e))})]},a.name);case"number":return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ba,{id:a.name,type:"number",value:s,onChange:e=>D(a.name,""===e.target.value?"":Number(e.target.value)),placeholder:a.placeholder,disabled:a.disabled||void 0!==a.computedValue,className:n?"border-destructive":""}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name);case"textarea":return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Rr,{id:a.name,value:s,onChange:e=>D(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,rows:a.rows||3,className:n?"border-destructive":""}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name);case"select":return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t(Nr,{value:s,onValueChange:e=>D(a.name,e),children:[e(Cr,{className:n?"border-destructive":"",children:e(kr,{placeholder:a.placeholder||`Selecione ${a.label}`})}),e(Pr,{children:a.options?.map(t=>e(Ir,{value:String(t.value),children:t.label},t.value))})]}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name);case"multiselect":return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ss,{options:a.options||[],value:Array.isArray(s)?s:[],onChange:e=>D(a.name,e),placeholder:a.placeholder,className:n?"border-destructive":""}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name);case"color":case"color-picker":return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ui,{value:s,onChange:e=>D(a.name,e),label:""}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name);case"icon-picker":return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Wi,{value:s,onChange:e=>D(a.name,e),label:""}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name);case"user-select":return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Gi,{value:s,onChange:e=>D(a.name,e),placeholder:a.placeholder,disabled:a.disabled}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name);case"custom":return a.render?t("div",{className:"space-y-2",children:[a.label&&t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a.render({value:s,onChange:e=>D(a.name,e),error:n,disabled:a.disabled}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name):null;default:return t("div",{className:"space-y-2",children:[t(Ha,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Ba,{id:a.name,type:a.type||"text",value:s,onChange:e=>D(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled||void 0!==a.computedValue,className:n?"border-destructive":""}),n&&e("p",{className:"text-sm text-destructive",children:n})]},a.name)}},X=r[T];return e(er,{open:m,onOpenChange:u,children:t(nr,{ref:F,className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e(ir,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:e(dr,{className:"text-white",children:a})}),G,e("div",{className:"space-y-4 py-4",children:X?.fields.map(e=>J(e))}),e("div",{className:"flex justify-between pt-4 border-t",children:Q})]})})}uo.displayName=_t.Root.displayName;const bo=({children:r})=>{const{isAuthenticated:n,isLoading:i}=In();if(s.useEffect(()=>{if(!n)return;const e=()=>{Fs.areAllTokensValid()||_n.logout()};e();const t=setInterval(e,3e5);return()=>clearInterval(t)},[n]),s.useEffect(()=>{if(i)return;if(n)return;if(Fs.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),t=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,a=new URLSearchParams(t);if(e.has("access_token")||a.has("access_token"))return;const r=nn();(async()=>{r?await _n.loginDev():_n.loginProd()})()},[n,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ka,{className:"w-full max-w-md",children:[e(Ga,{className:"text-center",children:e(Qa,{className:"text-xl font-semibold",children:"Carregando..."})}),t(Xa,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!n){const a=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",a?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ka,{className:"w-full max-w-md",children:[e(Ga,{className:"text-center",children:e(Qa,{className:"text-xl font-semibold",children:"Processando..."})}),t(Xa,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ka,{className:"w-full max-w-md",children:[e(Ga,{className:"text-center",children:e(Qa,{className:"text-xl font-semibold",children:"Iniciando..."})}),t(Xa,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:nn()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(a,{children:r})},vo=g("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),yo=r.forwardRef(({className:t,variant:a,...r},s)=>e("div",{ref:s,role:"alert",className:Fa(vo({variant:a}),t),...r}));yo.displayName="Alert";const xo=r.forwardRef(({className:t,...a},r)=>e("h5",{ref:r,className:Fa("mb-1 font-medium leading-none tracking-tight",t),...a}));xo.displayName="AlertTitle";const No=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("text-sm [&_p]:leading-relaxed",t),...a}));No.displayName="AlertDescription";const wo=()=>{const{processCallback:r}=In(),[s,n]=c(null),[i,o]=c(!1);u(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");e?(localStorage.removeItem("auth_return_url"),window.location.href=e):window.location.href="/"}else n("Falha na autenticação. Tente novamente.")}catch(e){n(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r]);const l=async()=>{o(!0),n(null);try{await r()||n("Falha na autenticação. Tente novamente.")}catch(e){n(e?.message||"Erro ao tentar novamente.")}finally{o(!1)}},d=()=>{window.location.href="/"};return e("div",s?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ka,{className:"w-full max-w-md",children:[e(Ga,{className:"text-center",children:t(Qa,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(F,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),t(Xa,{className:"space-y-4",children:[e(yo,{variant:"destructive",children:e(No,{children:s})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),t("div",{className:"flex gap-2",children:[e(Va,{onClick:l,disabled:i,className:"flex-1",children:t(a,i?{children:[e(jr,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(Ve,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(Va,{onClick:d,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ka,{className:"w-full max-w-md",children:[e(Ga,{className:"text-center",children:e(Qa,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),t(Xa,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(jr,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},ko=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ka,{className:"w-full max-w-md",children:[e(Ga,{className:"text-center",children:e(Qa,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),t(Xa,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(Va,{onClick:async()=>{nn()?await _n.loginDev():_n.loginProd()},className:"w-full",size:"lg",children:nn()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),Co=n(void 0);function So({children:t,actions:a}){const[r,s]=c({}),[n,i]=c(a);return u(()=>{i(a)},[a]),e(Co.Provider,{value:{metadata:r,setMetadata:s,clearMetadata:()=>s({}),headerActions:n,setHeaderActions:i},children:t})}function _o(){const e=i(Co);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Po(e){const{setMetadata:t,clearMetadata:a}=_o();u(()=>(t(e),()=>a()),[e.title,e.subtitle,t,a])}function Eo(e){return{queryClient:e.queryClient||new ft({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}const Io=import.meta.env.VITE_SUPABASE_URL,To=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;let Ao=null;var Ro=Object.defineProperty,Oo=(e,t,a)=>((e,t,a)=>t in e?Ro(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const Lo=new class{constructor(){Oo(this,"cache",{}),Oo(this,"cacheTimestamps",new Map),Oo(this,"CACHE_TTL",3e5),Oo(this,"loadingPromises",new Map)}isCacheValid(e){const t=this.cacheTimestamps.get(e);return!!t&&Date.now()-t<this.CACHE_TTL}async loadTranslations(e){if(this.isCacheValid(e))return this.cache[e]||{};const t=this.loadingPromises.get(e);if(t)return t;const a=this.fetchTranslations(e);this.loadingPromises.set(e,a);try{return await a}finally{this.loadingPromises.delete(e)}}async fetchTranslations(e){try{const t=(!Ao&&Io&&To&&(Ao=ut(Io,To,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1}})),Ao),{data:a,error:r}=await t.schema("common").from("translations").select("key, pt, en, es").eq("is_removed",!1);if(r)return"42501"===r.code||"PGRST301"===r.code||r.message?.includes("permission denied")||r.message?.includes("No suitable key"),{};const s={};return a?.forEach(t=>{let a;a="pt-BR"===e?t.pt:"en-US"===e?t.en||t.pt:"es-ES"===e&&t.es||t.pt,a&&(s[t.key]=a)}),this.cache[e]=s,this.cacheTimestamps.set(e,Date.now()),s}catch(t){return{}}}async upsertTranslation(e,t,a,r){const s=Ws(),{error:n}=await s.schema("common").from("translations").upsert({key:e,pt:t,en:a,es:r},{onConflict:"key"});if(n)throw n;this.clearCache()}async bulkUpsertTranslations(e){const t=Ws(),{error:a}=await t.schema("common").from("translations").upsert(e.map(e=>({key:e.key,pt:e.pt,en:e.en,es:e.es})),{onConflict:"key"});if(a)throw a;this.clearCache()}clearCache(){this.cache={},this.cacheTimestamps.clear()}clearCacheForLocale(e){delete this.cache[e],this.cacheTimestamps.delete(e)}};var Fo=Object.defineProperty,jo=(e,t,a)=>((e,t,a)=>t in e?Fo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const Mo="true"===import.meta.env.VITE_I18N_DEBUG_MODE;Oa.use(new class{constructor(e=!1){jo(this,"type","backend"),jo(this,"isDebugMode"),jo(this,"cache",new Map),jo(this,"loadingPromises",new Map),this.isDebugMode=e}read(e,t,a){if(this.cache.has(e))return void a(null,this.cache.get(e));if(this.loadingPromises.has(e))return void this.loadingPromises.get(e).then(()=>{a(null,this.cache.get(e)||{})});const r=Lo.loadTranslations(e).then(t=>{if(this.isDebugMode){const a={};Object.keys(t).forEach(e=>{a[e]=`[${e} ✅]`}),this.cache.set(e,a)}else this.cache.set(e,t)}).catch(t=>{this.cache.set(e,{})}).finally(()=>{this.loadingPromises.delete(e)});this.loadingPromises.set(e,r),r.then(()=>{a(null,this.cache.get(e)||{})})}create(e,t,a,r){}}(Mo)).use(ds).init({fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:(e,t)=>Mo?`[${e} ❌]`:`[⚠️ ${e}]`});const zo=new class{async getUserPreferences(e,t){if(!Fs.areAllTokensValid())return null;const a=Ws();try{const{data:r,error:s}=await a.schema("common").from("user_preferences").select("*").eq("id_user",e).eq("alias",t).maybeSingle();if(s)return"PGRST116"===s.code?this.createDefaultPreferences(e,t):("42501"===s.code||"PGRST301"===s.code||s.message?.includes("permission denied"),null);if(!r)return this.createDefaultPreferences(e,t);const n=r;return{locale:n.locale,timezone:n.timezone,datetimeFormat:n.datetime_format}}catch(r){return null}}async createDefaultPreferences(e,t){const a=Ws(),r={id_user:e,locale:"pt-BR",timezone:"America/Sao_Paulo",datetime_format:"dd/MM/yyyy HH:mm",alias:t};try{const{data:e,error:t}=await a.schema("common").from("user_preferences").insert(r).select().single();if(t)throw t;const s=e;return{locale:s.locale,timezone:s.timezone,datetimeFormat:s.datetime_format}}catch(s){throw s}}async updatePreferences(e,t,a){const r=Ws();try{const{error:s}=await r.schema("common").from("user_preferences").update(a).eq("id_user",e).eq("alias",t);if(s)throw s}catch(s){throw s}}},Do=n(void 0),$o=({children:t})=>{const{user:a,alias:r}=In(),[s,n]=c({locale:"pt-BR",timezone:"America/Sao_Paulo",datetimeFormat:"dd/MM/yyyy HH:mm"}),[i,o]=c(!0);u(()=>{(async()=>{if(a?.id&&r)try{const e=await zo.getUserPreferences(a.id,r);e&&(n({locale:e.locale,timezone:e.timezone,datetimeFormat:e.datetimeFormat}),await Oa.changeLanguage(e.locale),localStorage.setItem("i18nextLng",e.locale))}catch(e){}finally{o(!1)}else o(!1)})()},[a?.id,r]);const l=d(async e=>{if(a?.id&&r)try{await zo.updatePreferences(a.id,r,{locale:e}),n(t=>({...t,locale:e})),await Oa.changeLanguage(e),localStorage.setItem("i18nextLng",e)}catch(t){throw t}},[a?.id,r]),m=d(async e=>{if(a?.id&&r)try{await zo.updatePreferences(a.id,r,{timezone:e}),n(t=>({...t,timezone:e}))}catch(t){throw t}},[a?.id,r]),h=d(async e=>{if(a?.id&&r)try{await zo.updatePreferences(a.id,r,{datetime_format:e}),n(t=>({...t,datetimeFormat:e}))}catch(t){throw t}},[a?.id,r]);return e(Do.Provider,{value:{...s,setLocale:l,setTimezone:m,setDatetimeFormat:h,isLoading:i},children:t})},Uo=()=>{const e=i(Do);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e};function Vo({children:r}){const{ready:s}=Ns(),[n,i]=c(!0);return u(()=>{s&&n&&i(!1)},[s,n]),n&&!s?e("div",{className:"flex items-center justify-center min-h-screen bg-background",children:t("div",{className:"flex flex-col items-center gap-4",children:[e(jr,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Carregando traduções..."})]})}):e(a,{children:r})}const qo=Pt.Root,Bo=Pt.CollapsibleTrigger,Wo=Pt.CollapsibleContent;var Ho=Object.defineProperty,Ko=(e,t,a)=>((e,t,a)=>t in e?Ho(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);class Go extends p{constructor(e){super(e),Ko(this,"copyErrorDetails",()=>{const e=zs.getErrors().slice(0,2),t=`\n=== ERRO ATUAL ===\n${this.state.error?.message||"Erro desconhecido"}\n\nStack Trace:\n${this.state.error?.stack||"Não disponível"}\n\n=== ÚLTIMOS ERROS ===\n${e.map((e,t)=>`${t+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(t),w.success("Detalhes copiados!",{description:"Os detalhes do erro foram copiados para a área de transferência."})}),this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,t){if(import.meta.env.DEV)throw e;zs.handleError(e,!1),this.setState({errorInfo:t})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const a=zs.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:t(Ka,{className:"w-full max-w-2xl",children:[t(Ga,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(j,{className:"h-12 w-12 text-destructive"})}),e(Qa,{children:"Algo deu errado"})]}),t(Xa,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),t(qo,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(Bo,{asChild:!0,children:t(Va,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(_,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),t(Wo,{className:"mt-4 space-y-4",children:[t("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[t("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),t("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(Vi,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),a.length>0&&t("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:a.map((a,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:t("div",{className:"flex items-start gap-2",children:[t("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),t("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:t("span",{className:"text-xs text-muted-foreground",children:["[",new Date(a.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:a.message})]})]})},a.id))})]})]}),t(Va,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(me,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(Va,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}function Qo({children:t,queryClient:a}){const r=a??new ft({defaultOptions:{queries:{staleTime:3e5,retry:1}}});return e(Go,{children:e(ws,{i18n:Oa,children:e(gt,{client:r,children:e(En,{children:e($o,{children:e(Vo,{children:t})})})})})})}const Jo=Et.Root,Xo=r.forwardRef(({className:t,...a},r)=>e(Et.Item,{ref:r,className:Fa("border-b",t),...a}));Xo.displayName="AccordionItem";const Yo=r.forwardRef(({className:a,children:r,...s},n)=>e(Et.Header,{className:"flex",children:t(Et.Trigger,{ref:n,className:Fa("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",a),...s,children:[r,e(_,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Yo.displayName=Et.Trigger.displayName;const Zo=r.forwardRef(({className:t,children:a,...r},s)=>e(Et.Content,{ref:s,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:Fa("pb-4 pt-0",t),children:a})}));Zo.displayName=Et.Content.displayName;const el=It.Root,tl=r.forwardRef(({className:t,...a},r)=>e(Tt.Root,{ref:r,className:Fa("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...a}));tl.displayName=Tt.Root.displayName;const al=r.forwardRef(({className:t,...a},r)=>e(Tt.Image,{ref:r,className:Fa("aspect-square h-full w-full",t),...a}));al.displayName=Tt.Image.displayName;const rl=r.forwardRef(({className:t,...a},r)=>e(Tt.Fallback,{ref:r,className:Fa("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...a}));rl.displayName=Tt.Fallback.displayName;const sl=r.forwardRef(({...t},a)=>e("nav",{ref:a,"aria-label":"breadcrumb",...t}));sl.displayName="Breadcrumb";const nl=r.forwardRef(({className:t,...a},r)=>e("ol",{ref:r,className:Fa("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",t),...a}));nl.displayName="BreadcrumbList";const il=r.forwardRef(({className:t,...a},r)=>e("li",{ref:r,className:Fa("inline-flex items-center gap-1.5",t),...a}));il.displayName="BreadcrumbItem";const ol=r.forwardRef(({asChild:t,className:a,...r},s)=>e(t?f:"a",{ref:s,className:Fa("transition-colors hover:text-foreground",a),...r}));ol.displayName="BreadcrumbLink";const ll=r.forwardRef(({className:t,...a},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Fa("font-normal text-foreground",t),...a}));ll.displayName="BreadcrumbPage";const dl=({children:t,className:a,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:Fa("[&>svg]:h-3.5 [&>svg]:w-3.5",a),...r,children:t??e(D,{})});dl.displayName="BreadcrumbSeparator";const cl=({className:a,...r})=>t("span",{role:"presentation","aria-hidden":"true",className:Fa("flex h-9 w-9 items-center justify-center",a),...r,children:[e(qe,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});cl.displayName="BreadcrumbEllipsis";const ul=g("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),ml=r.forwardRef(({className:t,orientation:a,...r},s)=>e("div",{ref:s,className:Fa(ul({orientation:a}),t),...r}));function hl(e){return(t={})=>{const a=t.width?String(t.width):e.defaultWidth;return e.formats[a]||e.formats[e.defaultWidth]}}function pl(e){return(t,a)=>{let r;if("formatting"===(a?.context?String(a.context):"standalone")&&e.formattingValues){const t=e.defaultFormattingWidth||e.defaultWidth,s=a?.width?String(a.width):t;r=e.formattingValues[s]||e.formattingValues[t]}else{const t=e.defaultWidth,s=a?.width?String(a.width):e.defaultWidth;r=e.values[s]||e.values[t]}return r[e.argumentCallback?e.argumentCallback(t):t]}}function fl(e){return(t,a={})=>{const r=a.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],n=t.match(s);if(!n)return null;const i=n[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,t){for(let a=0;a<e.length;a++)if(t(e[a]))return a;return}(o,e=>e.test(i)):function(e,t){for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return a;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=a.valueCallback?a.valueCallback(d):d;return{value:d,rest:t.slice(i.length)}}}function gl(e){return(t,a={})=>{const r=t.match(e.matchPattern);if(!r)return null;const s=r[0],n=t.match(e.parsePattern);if(!n)return null;let i=e.valueCallback?e.valueCallback(n[0]):n[0];i=a.valueCallback?a.valueCallback(i):i;return{value:i,rest:t.slice(s.length)}}}ml.displayName="ButtonGroup";const bl={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},vl={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},yl={ordinalNumber:(e,t)=>{const a=Number(e),r=a%100;if(r>20||r<10)switch(r%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},era:pl({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:pl({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:pl({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:pl({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:pl({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},xl={ordinalNumber:gl({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:fl({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:fl({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:fl({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:fl({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:fl({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},Nl={code:"en-US",formatDistance:(e,t,a)=>{let r;const s=bl[e];return r="string"==typeof s?s:1===t?s.one:s.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"in "+r:r+" ago":r},formatLong:{date:hl({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:hl({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:hl({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,t,a,r)=>vl[e],localize:yl,match:xl,options:{weekStartsOn:0,firstWeekContainsDate:1}},wl={lessThanXSeconds:{one:"menos de un segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"medio minuto",lessThanXMinutes:{one:"menos de un minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"alrededor de 1 hora",other:"alrededor de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 día",other:"{{count}} días"},aboutXWeeks:{one:"alrededor de 1 semana",other:"alrededor de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"alrededor de 1 mes",other:"alrededor de {{count}} meses"},xMonths:{one:"1 mes",other:"{{count}} meses"},aboutXYears:{one:"alrededor de 1 año",other:"alrededor de {{count}} años"},xYears:{one:"1 año",other:"{{count}} años"},overXYears:{one:"más de 1 año",other:"más de {{count}} años"},almostXYears:{one:"casi 1 año",other:"casi {{count}} años"}},kl={date:hl({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:hl({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:hl({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Cl={lastWeek:"'el' eeee 'pasado a la' p",yesterday:"'ayer a la' p",today:"'hoy a la' p",tomorrow:"'mañana a la' p",nextWeek:"eeee 'a la' p",other:"P"},Sl={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},_l={ordinalNumber:(e,t)=>Number(e)+"º",era:pl({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:pl({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>Number(e)-1}),month:pl({values:{narrow:["e","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],wide:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},defaultWidth:"wide"}),day:pl({values:{narrow:["d","l","m","m","j","v","s"],short:["do","lu","ma","mi","ju","vi","sá"],abbreviated:["dom","lun","mar","mié","jue","vie","sáb"],wide:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"]},defaultWidth:"wide"}),dayPeriod:pl({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"}},defaultFormattingWidth:"wide"})},Pl={ordinalNumber:gl({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:fl({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|a\.?\s?e\.?\s?c\.?|d\.?\s?c\.?|e\.?\s?c\.?)/i,wide:/^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^(antes de cristo|antes de la era com[uú]n)/i,/^(despu[eé]s de cristo|era com[uú]n)/i]},defaultParseWidth:"any"}),quarter:fl({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:fl({matchPatterns:{narrow:/^[efmajsond]/i,abbreviated:/^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,wide:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^e/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^en/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i]},defaultParseWidth:"any"}),day:fl({matchPatterns:{narrow:/^[dlmjvs]/i,short:/^(do|lu|ma|mi|ju|vi|s[áa])/i,abbreviated:/^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,wide:/^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^do/i,/^lu/i,/^ma/i,/^mi/i,/^ju/i,/^vi/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:fl({matchPatterns:{narrow:/^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,any:/^([ap]\.?\s?m\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn/i,noon:/^md/i,morning:/mañana/i,afternoon:/tarde/i,evening:/tarde/i,night:/noche/i}},defaultParseWidth:"any"})},El={code:"es",formatDistance:(e,t,a)=>{let r;const s=wl[e];return r="string"==typeof s?s:1===t?s.one:s.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"en "+r:"hace "+r:r},formatLong:kl,formatRelative:(e,t,a,r)=>1!==t.getHours()?Sl[e]:Cl[e],localize:_l,match:Pl,options:{weekStartsOn:1,firstWeekContainsDate:1}},Il={lessThanXSeconds:{one:"menos de um segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"meio minuto",lessThanXMinutes:{one:"menos de um minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"cerca de 1 hora",other:"cerca de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 dia",other:"{{count}} dias"},aboutXWeeks:{one:"cerca de 1 semana",other:"cerca de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"cerca de 1 mês",other:"cerca de {{count}} meses"},xMonths:{one:"1 mês",other:"{{count}} meses"},aboutXYears:{one:"cerca de 1 ano",other:"cerca de {{count}} anos"},xYears:{one:"1 ano",other:"{{count}} anos"},overXYears:{one:"mais de 1 ano",other:"mais de {{count}} anos"},almostXYears:{one:"quase 1 ano",other:"quase {{count}} anos"}},Tl={date:hl({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/yyyy"},defaultWidth:"full"}),time:hl({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:hl({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Al={lastWeek:e=>{const t=e.getDay();return"'"+(0===t||6===t?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},Rl={ordinalNumber:(e,t)=>{const a=Number(e);return"week"===t?.unit?a+"ª":a+"º"},era:pl({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:pl({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:pl({values:{narrow:["j","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],wide:["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"]},defaultWidth:"wide"}),day:pl({values:{narrow:["D","S","T","Q","Q","S","S"],short:["dom","seg","ter","qua","qui","sex","sab"],abbreviated:["domingo","segunda","terça","quarta","quinta","sexta","sábado"],wide:["domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado"]},defaultWidth:"wide"}),dayPeriod:pl({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"}},defaultFormattingWidth:"wide"})},Ol={ordinalNumber:gl({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:fl({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|d\.?\s?c\.?)/i,wide:/^(antes de cristo|depois de cristo)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^antes de cristo/i,/^depois de cristo/i]},defaultParseWidth:"any"}),quarter:fl({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:fl({matchPatterns:{narrow:/^[jfmajsond]/i,abbreviated:/^(jan|fev|mar|abr|mai|jun|jul|ago|set|out|nov|dez)/i,wide:/^(janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^fev/i,/^mar/i,/^abr/i,/^mai/i,/^jun/i,/^jul/i,/^ago/i,/^set/i,/^out/i,/^nov/i,/^dez/i]},defaultParseWidth:"any"}),day:fl({matchPatterns:{narrow:/^(dom|[23456]ª?|s[aá]b)/i,short:/^(dom|[23456]ª?|s[aá]b)/i,abbreviated:/^(dom|seg|ter|qua|qui|sex|s[aá]b)/i,wide:/^(domingo|(segunda|ter[cç]a|quarta|quinta|sexta)([- ]feira)?|s[aá]bado)/i},defaultMatchWidth:"wide",parsePatterns:{short:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],narrow:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],any:[/^d/i,/^seg/i,/^t/i,/^qua/i,/^qui/i,/^sex/i,/^s[aá]b/i]},defaultParseWidth:"any"}),dayPeriod:fl({matchPatterns:{narrow:/^(a|p|mn|md|(da) (manhã|tarde|noite))/i,any:/^([ap]\.?\s?m\.?|meia[-\s]noite|meio[-\s]dia|(da) (manhã|tarde|noite))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn|^meia[-\s]noite/i,noon:/^md|^meio[-\s]dia/i,morning:/manhã/i,afternoon:/tarde/i,evening:/tarde/i,night:/noite/i}},defaultParseWidth:"any"})},Ll={code:"pt-BR",formatDistance:(e,t,a)=>{let r;const s=Il[e];return r="string"==typeof s?s:1===t?s.one:s.other.replace("{{count}}",String(t)),a?.addSuffix?a.comparison&&a.comparison>0?"em "+r:"há "+r:r},formatLong:Tl,formatRelative:(e,t,a,r)=>{const s=Al[e];return"function"==typeof s?s(t):s},localize:Rl,match:Ol,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Fl({className:t,classNames:a,showOutsideDays:r=!0,...s}){return e(At,{showOutsideDays:r,className:Fa("p-3 pointer-events-auto",t),locale:Ll,classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:Fa(Ua({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:Fa(Ua({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...a},components:{IconLeft:({...t})=>e(we,{className:"h-4 w-4"}),IconRight:({...t})=>e(D,{className:"h-4 w-4"})},...s})}Fl.displayName="Calendar";const jl={Root:function({children:t,className:a}){return e("div",{className:Fa("space-y-4",a),children:t})},Item:function({children:t,onClick:a,className:r}){return e(Ka,{className:Fa("transition-colors",a&&"cursor-pointer hover:bg-muted/50",r),onClick:a,children:e(Xa,{className:"p-4",children:t})})},Field:function({label:a,value:r,className:s}){return t("div",{className:Fa("flex justify-between items-center text-sm",s),children:[t("span",{className:"text-muted-foreground font-medium",children:[a,":"]}),e("span",{className:"text-foreground",children:r})]})}};function Ml({date:a,onDateChange:r,placeholder:s="Pick a date",disabled:n=!1,className:i,disabledDates:o}){return t(Dr,{children:[e($r,{asChild:!0,children:t(Va,{variant:"outline",disabled:n,className:Fa("w-full justify-start text-left font-normal",!a&&"text-muted-foreground",i),children:[e(Re,{className:"mr-2 h-4 w-4"}),a?N(a,"PPP"):e("span",{children:s})]})}),e(Ur,{className:"w-auto p-0",align:"start",children:e(Fl,{mode:"single",selected:a,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const zl=({shouldScaleBackground:t=!0,...a})=>e(Rt.Root,{shouldScaleBackground:t,...a});zl.displayName="Drawer";const Dl=Rt.Trigger,$l=Rt.Portal,Ul=Rt.Close,Vl=r.forwardRef(({className:t,...a},r)=>e(Rt.Overlay,{ref:r,className:Fa("fixed inset-0 z-50 bg-black/80",t),...a}));Vl.displayName=Rt.Overlay.displayName;const ql=r.forwardRef(({className:a,children:r,...s},n)=>t($l,{children:[e(Vl,{}),t(Rt.Content,{ref:n,className:Fa("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",a),...s,children:[e("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));ql.displayName="DrawerContent";const Bl=({className:t,...a})=>e("div",{className:Fa("grid gap-1.5 p-4 text-center sm:text-left",t),...a});Bl.displayName="DrawerHeader";const Wl=({className:t,...a})=>e("div",{className:Fa("mt-auto flex flex-col gap-2 p-4",t),...a});Wl.displayName="DrawerFooter";const Hl=r.forwardRef(({className:t,...a},r)=>e(Rt.Title,{ref:r,className:Fa("text-lg font-semibold leading-none tracking-tight",t),...a}));Hl.displayName=Rt.Title.displayName;const Kl=r.forwardRef(({className:t,...a},r)=>e(Rt.Description,{ref:r,className:Fa("text-sm text-muted-foreground",t),...a}));function Gl({value:t,onChange:a,activeLabel:r,inactiveLabel:s,allLabel:n,placeholder:i,className:o="w-full sm:w-[180px]"}){const{t:l}=Ns(),d=[{id:"active",name:r||l("active")},{id:"inactive",name:s||l("inactive")},{id:"all",name:n||l("all")}];return e(Ss,{value:t,onChange:e=>a(e),options:d,getOptionValue:e=>e.id,getOptionLabel:e=>e.name,placeholder:i||l("select"),className:o})}Kl.displayName=Rt.Description.displayName;const Ql={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6","auto-fit":"grid-cols-[repeat(auto-fit,minmax(250px,1fr))]","auto-fill":"grid-cols-[repeat(auto-fill,minmax(250px,1fr))]"},Jl={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Xl({children:t,cols:a="auto-fit",gap:r="md",className:s}){return e("div",{className:Fa("grid",Ql[a],Jl[r],s),children:t})}const Yl=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-slot":"input-group",className:Fa("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",t),...a}));Yl.displayName="InputGroup";const Zl=g("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),ed=r.forwardRef(({className:t,align:a,...r},s)=>e("div",{ref:s,"data-slot":"input-group-addon",className:Fa(Zl({align:a}),t),...r}));ed.displayName="InputGroupAddon";const td=g("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),ad=r.forwardRef(({className:t,size:a,variant:r="ghost",...s},n)=>e(Va,{ref:n,"data-slot":"input-group-button",variant:r,className:Fa(td({size:a}),"rounded-none first:rounded-l-md last:rounded-r-md",t),...s}));ad.displayName="InputGroupButton";const rd=r.forwardRef(({className:t,...a},r)=>e(Ba,{ref:r,"data-slot":"input-group-control",className:Fa("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));rd.displayName="InputGroupInput";const sd=r.forwardRef(({className:t,...a},r)=>e(Rr,{ref:r,"data-slot":"input-group-control",className:Fa("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));sd.displayName="InputGroupTextarea";const nd=r.forwardRef(({className:a,keys:r,children:s,...n},i)=>r&&r.length>0?t("span",{className:Fa("inline-flex items-center gap-1",a),children:[r.map((t,a)=>e("kbd",{className:Fa("pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border border-border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100"),children:t},a)),s&&e("kbd",{ref:i,className:Fa("pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border border-border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100"),...n,children:s})]}):e("kbd",{ref:i,className:Fa("pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border border-border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100",a),...n,children:s}));nd.displayName="Kbd";const id=r.forwardRef(({className:t,children:a,...r},s)=>e("select",{ref:s,className:Fa("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...r,children:a}));id.displayName="NativeSelect";const od=r.forwardRef(({className:t,...a},r)=>e("h1",{ref:r,className:Fa("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",t),...a}));od.displayName="H1";const ld=r.forwardRef(({className:t,...a},r)=>e("h2",{ref:r,className:Fa("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",t),...a}));ld.displayName="H2";const dd=r.forwardRef(({className:t,...a},r)=>e("h3",{ref:r,className:Fa("scroll-m-20 text-2xl font-semibold tracking-tight",t),...a}));dd.displayName="H3";const cd=r.forwardRef(({className:t,...a},r)=>e("h4",{ref:r,className:Fa("scroll-m-20 text-xl font-semibold tracking-tight",t),...a}));cd.displayName="H4";const ud=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:Fa("leading-7 [&:not(:first-child)]:mt-6",t),...a}));ud.displayName="P";const md=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:Fa("text-xl text-muted-foreground",t),...a}));md.displayName="Lead";const hd=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:Fa("text-lg font-semibold",t),...a}));hd.displayName="Large";const pd=r.forwardRef(({className:t,...a},r)=>e("small",{ref:r,className:Fa("text-sm font-medium leading-none",t),...a}));pd.displayName="Small";const fd=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:Fa("text-sm text-muted-foreground",t),...a}));fd.displayName="Muted";const gd=r.forwardRef(({className:t,...a},r)=>e("code",{ref:r,className:Fa("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",t),...a}));gd.displayName="InlineCode";const bd=r.forwardRef(({className:t,...a},r)=>e("blockquote",{ref:r,className:Fa("mt-6 border-l-2 pl-6 italic",t),...a}));bd.displayName="Blockquote";const vd=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,className:Fa("my-6 ml-6 list-disc [&>li]:mt-2",t),...a}));function yd({items:t,maxItems:a=3,className:r}){return t.length>a&&(t[0],t.slice(-(a-1))),t.length,e(sl,{className:r})}function xd(){const e=vt();return(()=>{const t=e.pathname.split("/").filter(Boolean),a=[{label:"Exemplos",href:"/"}];let r="";return t.forEach((e,s)=>{r+=`/${e}`;const n=s===t.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");a.push({label:i,href:n?void 0:r,isCurrentPage:n})}),a})()}vd.displayName="List";const Nd=({className:t,...a})=>e("nav",{role:"navigation","aria-label":"pagination",className:Fa("mx-auto flex w-full justify-center",t),...a});Nd.displayName="Pagination";const wd=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,className:Fa("flex flex-row items-center gap-1",t),...a}));wd.displayName="PaginationContent";const kd=r.forwardRef(({className:t,...a},r)=>e("li",{ref:r,className:Fa("",t),...a}));kd.displayName="PaginationItem";const Cd=({className:t,isActive:a,size:r="icon",...s})=>e("a",{"aria-current":a?"page":void 0,className:Fa(Ua({variant:a?"outline":"ghost",size:r}),t),...s});Cd.displayName="PaginationLink";const Sd=({className:a,...r})=>t(Cd,{"aria-label":"Go to previous page",size:"default",className:Fa("gap-1 pl-2.5",a),...r,children:[e(we,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});Sd.displayName="PaginationPrevious";const _d=({className:a,...r})=>t(Cd,{"aria-label":"Go to next page",size:"default",className:Fa("gap-1 pr-2.5",a),...r,children:[e("span",{children:"Next"}),e(D,{className:"h-4 w-4"})]});_d.displayName="PaginationNext";const Pd=({className:a,...r})=>t("span",{"aria-hidden":!0,className:Fa("flex h-9 w-9 items-center justify-center",a),...r,children:[e(qe,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});Pd.displayName="PaginationEllipsis";const Ed=r.forwardRef(({className:t,...a},r)=>e(Ot.Root,{className:Fa("grid gap-2",t),...a,ref:r}));Ed.displayName=Ot.Root.displayName;const Id=r.forwardRef(({className:t,...a},r)=>e(Ot.Item,{ref:r,className:Fa("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...a,children:e(Ot.Indicator,{className:"flex items-center justify-center",children:e($,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Id.displayName=Ot.Item.displayName;const Td=g("flex h-10 w-full items-center rounded-md border border-input bg-background text-sm ring-offset-background transition-colors focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",{variants:{variant:{default:"",filled:"bg-muted border-transparent",outline:"border-2"},size:{default:"h-10",sm:"h-8",lg:"h-12"}},defaultVariants:{variant:"default",size:"default"}}),Ad=r.forwardRef(({className:a,variant:r,size:s,onClear:n,showClearButton:i=!0,value:o,...l},d)=>{const c=null!=o&&""!==o;return t("div",{className:Fa(Td({variant:r,size:s,className:a})),children:[e(M,{className:"ml-3 h-4 w-4 shrink-0 text-muted-foreground"}),e("input",{type:"text",className:Fa("flex-1 bg-transparent px-3 py-2 placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50","sm"===s&&"py-1 text-xs","lg"===s&&"py-3"),ref:d,value:o,...l}),i&&c&&n&&e("button",{type:"button",onClick:n,className:"mr-2 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none","aria-label":"Clear search",children:e(S,{className:"h-4 w-4"})})]})});Ad.displayName="Searchbar";const Rd=tt.Root,Od=tt.Trigger,Ld=tt.Close,Fd=tt.Portal,jd=r.forwardRef(({className:t,...a},r)=>e(tt.Overlay,{className:Fa("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a,ref:r}));jd.displayName=tt.Overlay.displayName;const Md=g("fixed z-50 flex flex-col bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),zd=r.forwardRef(({side:a="right",className:r,children:s,...n},i)=>t(Fd,{children:[e(jd,{}),t(tt.Content,{ref:i,className:Fa(Md({side:a}),r),...n,children:[s,t(tt.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(S,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));zd.displayName=tt.Content.displayName;const Dd=({className:a,showSeparator:r=!1,children:s,...n})=>t("div",{className:Fa("flex flex-col flex-shrink-0",a),...n,children:[e("div",{className:"flex flex-col text-left",children:s}),r&&e(Za,{className:"mt-2"})]});Dd.displayName="SheetHeader";const $d=({className:t,...a})=>e("div",{className:Fa("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});$d.displayName="SheetBody";const Ud=({className:a,children:r,...s})=>t("div",{className:"flex-shrink-0 pt-4",children:[e(Za,{className:"mb-4"}),e("div",{className:Fa("flex flex-row justify-end gap-2",a),...s,children:r})]});Ud.displayName="SheetFooter";const Vd=r.forwardRef(({className:t,...a},r)=>e(tt.Title,{ref:r,className:Fa("text-lg font-semibold text-foreground",t),...a}));Vd.displayName=tt.Title.displayName;const qd=r.forwardRef(({className:t,...a},r)=>e(tt.Description,{ref:r,className:Fa("text-sm text-muted-foreground",t),...a}));qd.displayName=tt.Description.displayName;const Bd=Lt.Provider,Wd=Lt.Root,Hd=Lt.Trigger,Kd=r.forwardRef(({className:t,sideOffset:a=4,...r},s)=>e(Lt.Content,{ref:s,sideOffset:a,className:Fa("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r}));Kd.displayName=Lt.Content.displayName;const Gd="sidebar:state",Qd=r.createContext(null);function Jd(){const e=r.useContext(Qd);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Xd=r.forwardRef(({defaultOpen:t=!0,open:a,onOpenChange:s,className:n,style:i,children:o,...l},d)=>{const[c,u]=r.useState(!1);r.useEffect(()=>{const e=()=>u(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[m,h]=r.useState(!1),[p,f]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Gd);return null!==e?"true"===e:t}return t}),g=a??p,b=r.useCallback(e=>{const t="function"==typeof e?e(g):e;s?s(t):f(t),"undefined"!=typeof window&&localStorage.setItem(Gd,String(t))},[s,g]),v=r.useCallback(()=>c?h(e=>!e):b(e=>!e),[c,b,h]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const y=g?"expanded":"collapsed",x=r.useMemo(()=>({state:y,open:g,setOpen:b,isMobile:c,openMobile:m,setOpenMobile:h,toggleSidebar:v}),[y,g,b,c,m,h,v]);return e(Qd.Provider,{value:x,children:e(Bd,{delayDuration:0,children:e("div",{className:Fa("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",n),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...i},ref:d,...l,children:o})})})});Xd.displayName="SidebarProvider";const Yd=r.forwardRef(({side:a="left",variant:r="sidebar",collapsible:s="offcanvas",className:n,children:i,...o},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Jd();return"none"===s?e("div",{className:Fa("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",n),ref:l,...o,children:i}):d?e(Rd,{open:u,onOpenChange:m,...o,children:t(zd,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:a,children:[e(Vd,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):t("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?s:"","data-variant":r,"data-side":a,children:[e("div",{className:Fa("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:Fa("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===a?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});Yd.displayName="Sidebar";const Zd=r.forwardRef(({className:a,onClick:r,...s},n)=>{const{toggleSidebar:i}=Jd();return t(Va,{ref:n,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Fa("h-7 w-7",a),onClick:e=>{r?.(e),i()},...s,children:[e(Be,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Zd.displayName="SidebarTrigger";const ec=r.forwardRef(({className:t,...a},r)=>{const{toggleSidebar:s}=Jd();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:s,title:"Toggle Sidebar",className:Fa("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),...a})});ec.displayName="SidebarRail";const tc=r.forwardRef(({className:t,...a},r)=>e("main",{ref:r,className:Fa("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",t),...a}));tc.displayName="SidebarInset";const ac=r.forwardRef(({className:t,...a},r)=>e(Ba,{ref:r,"data-sidebar":"input",className:Fa("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),...a}));ac.displayName="SidebarInput";const rc=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"header",className:Fa("flex flex-col gap-2 p-2",t),...a}));rc.displayName="SidebarHeader";const sc=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"footer",className:Fa("flex flex-col gap-2 p-2",t),...a}));sc.displayName="SidebarFooter";const nc=r.forwardRef(({className:t,...a},r)=>e(Za,{ref:r,"data-sidebar":"separator",className:Fa("mx-2 w-auto bg-sidebar-border",t),...a}));nc.displayName="SidebarSeparator";const ic=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"content",className:Fa("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...a}));ic.displayName="SidebarContent";const oc=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"group",className:Fa("relative flex w-full min-w-0 flex-col p-2",t),...a}));oc.displayName="SidebarGroup";const lc=r.forwardRef(({className:t,asChild:a=!1,...r},s)=>e(a?f:"div",{ref:s,"data-sidebar":"group-label",className:Fa("duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),...r}));lc.displayName="SidebarGroupLabel";const dc=r.forwardRef(({className:t,asChild:a=!1,...r},s)=>e(a?f:"button",{ref:s,"data-sidebar":"group-action",className:Fa("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",t),...r}));dc.displayName="SidebarGroupAction";const cc=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:Fa("w-full text-sm",t),...a}));cc.displayName="SidebarGroupContent";const uc=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:Fa("flex w-full min-w-0 flex-col gap-1",t),...a}));uc.displayName="SidebarMenu";const mc=r.forwardRef(({className:t,...a},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:Fa("group/menu-item relative",t),...a}));mc.displayName="SidebarMenuItem";const hc=g("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-primary data-[active=true]:font-medium data-[active=true]:text-sidebar-primary-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=icon]:[&>*]:!mr-0 group-data-[collapsible=icon]:[&>*]:!ml-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-10 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),pc=r.forwardRef(({asChild:a=!1,isActive:r=!1,variant:s="default",size:n="default",tooltip:i,className:o,...l},d)=>{const c=a?f:"button",{isMobile:u,state:m}=Jd(),h=e(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":r,className:Fa(hc({variant:s,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),t(Wd,{children:[e(Hd,{asChild:!0,children:h}),e(Kd,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):h});pc.displayName="SidebarMenuButton";const fc=r.forwardRef(({className:t,asChild:a=!1,showOnHover:r=!1,...s},n)=>e(a?f:"button",{ref:n,"data-sidebar":"menu-action",className:Fa("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",t),...s}));fc.displayName="SidebarMenuAction";const gc=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:Fa("absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),...a}));gc.displayName="SidebarMenuBadge";const bc=r.forwardRef(({className:a,showIcon:s=!1,...n},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return t("div",{ref:i,"data-sidebar":"menu-skeleton",className:Fa("rounded-md h-8 flex gap-2 px-2 items-center",a),...n,children:[s&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});bc.displayName="SidebarMenuSkeleton";const vc=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:Fa("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),...a}));vc.displayName="SidebarMenuSub";const yc=r.forwardRef(({...t},a)=>e("li",{ref:a,...t}));yc.displayName="SidebarMenuSubItem";const xc=r.forwardRef(({asChild:t=!1,size:a="md",isActive:r,className:s,...n},i)=>e(t?f:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":a,"data-active":r,className:Fa("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===a&&"text-xs","md"===a&&"text-sm","group-data-[collapsible=icon]:hidden",s),...n}));xc.displayName="SidebarMenuSubButton";const Nc=r.forwardRef(({className:a,...r},s)=>t(Ft.Root,{ref:s,className:Fa("relative flex w-full touch-none select-none items-center",a),...r,children:[e(Ft.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(Ft.Range,{className:"absolute h-full bg-primary"})}),e(Ft.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Nc.displayName=Ft.Root.displayName;const wc=jt.Root,kc=r.forwardRef(({className:t,...a},r)=>e(jt.List,{ref:r,className:Fa("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",t),...a}));kc.displayName=jt.List.displayName;const Cc=r.forwardRef(({className:t,...a},r)=>e(jt.Trigger,{ref:r,className:Fa("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",t),...a}));Cc.displayName=jt.Trigger.displayName;const Sc=r.forwardRef(({className:t,...a},r)=>e(jt.Content,{ref:r,className:Fa("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));function _c({children:t,className:a}){return e("div",{className:Fa("flex flex-col h-full",a),children:e(Vi,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:t})})})}function Pc({title:a,description:r,actions:s,className:n}){return t("div",{className:Fa("space-y-4",n),children:[t("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[t("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:a}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),s&&e("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e(Za,{})]})}function Ec({children:t,className:a}){return e("div",{className:Fa("space-y-6",a),children:t})}Sc.displayName=jt.Content.displayName;const Ic=g("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Tc=r.forwardRef(({className:t,variant:a,size:r,...s},n)=>e(Mt.Root,{ref:n,className:Fa(Ic({variant:a,size:r,className:t})),...s}));Tc.displayName=Mt.Root.displayName;const Ac=r.createContext({size:"default",variant:"default"}),Rc=r.forwardRef(({className:t,variant:a,size:r,children:s,...n},i)=>e(zt.Root,{ref:i,className:Fa("flex items-center justify-center gap-1",t),...n,children:e(Ac.Provider,{value:{variant:a,size:r},children:s})}));Rc.displayName=zt.Root.displayName;const Oc=r.forwardRef(({className:t,children:a,variant:s,size:n,...i},o)=>{const l=r.useContext(Ac);return e(zt.Item,{ref:o,className:Fa(Ic({variant:l.variant||s,size:l.size||n}),t),...i,children:a})});function Lc({manager:a,config:r,onEdit:s,onDelete:n}){const{t:i}=Ns();return a.isLoading?e(Xl,{children:Array.from({length:3}).map((a,r)=>t(Ka,{children:[t(Ga,{children:[e(Xr,{className:"h-4 w-3/4"}),e(Xr,{className:"h-3 w-1/2"})]}),e(Xa,{children:t("div",{className:"space-y-2",children:[e(Xr,{className:"h-3 w-full"}),e(Xr,{className:"h-3 w-2/3"})]})})]},r))}):e(jl.Root,{children:a.entities.map(a=>t(jl.Item,{onClick:()=>s(a),children:[e(Ga,{className:"pb-3",children:t("div",{className:"flex items-start justify-between",children:[t("div",{className:"flex-1 min-w-0",children:[e(Qa,{className:"text-base leading-6 truncate",children:a.title||a.name||i("no_title")}),e(Ja,{className:"text-sm",children:N(new Date(a.created_at),"dd/MM/yyyy HH:mm",{locale:Ll})})]}),t("div",{className:"flex items-center gap-2 ml-2",children:[a.link&&e(Va,{variant:"external-link",size:"icon-xs",onClick:e=>{e.stopPropagation(),(e=>{try{const t=window.open(e,"_blank");t&&!t.closed&&void 0!==t.closed||(navigator.clipboard.writeText(e),w.info(i("link_copied")))}catch(t){window.location.href=e}})(a.link)},title:i("open_external_link"),children:e(We,{className:"h-4 w-4"})}),e("div",{onClick:e=>e.stopPropagation(),children:e(ji,{onEdit:()=>s(a),onDelete:n?()=>n(a):void 0,canDelete:!!n})})]})]})}),e(Xa,{className:"pt-0",children:e("div",{className:"space-y-2",children:r.cardFields?.map(t=>{const r=a[t.key];return r?e(jl.Field,{label:t.label,value:t.render?t.render(r,a):String(r)},String(t.key)):null})})})]},a.id))})}function Fc({data:a,columns:r,sortField:s,sortDirection:n,onSort:i,onRowClick:l,renderActions:d,isLoading:c=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:b=!1}){const v=o(()=>{const e=r.reduce((e,t)=>t.width?e:e+(t.weight??1),0);return r.map(t=>{if(t.width)return`${t.width}px`;if(t.minWidth&&!t.weight)return`${t.minWidth}px`;const a=(t.weight??1)/e*100;return t.minWidth?`minmax(${t.minWidth}px, ${a}%)`:`${a}%`})},[r]);return c?e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((t,a)=>e(Xr,{className:"h-12 w-full"},a))})}):0===a.length?e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:u})})}):e("div",{className:"flex-1 overflow-auto",children:t(Bn,{className:m,children:[e(Wn,{className:"sticky top-0 bg-background z-10",children:t(Gn,{children:[h&&e(Qn,{className:"w-[40px]",children:e(Ar,{checked:b,onCheckedChange:g,"aria-label":"Selecionar todos"})}),r.map((a,r)=>{return e(Qn,{className:a.className,style:{width:v[r]},children:a.sortable&&i?t("button",{onClick:()=>i(String(a.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[a.header,(o=String(a.key),s!==o?e(H,{size:14,className:"ml-1 opacity-50"}):e("asc"===n?K:G,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:a.header})},String(a.key));var o}),d&&e(Qn,{className:"w-[80px] text-right",children:"Ações"})]})}),e(Hn,{children:a.map(a=>t(Gn,{onClick:()=>l?.(a),className:l?"cursor-pointer":"",children:[h&&e(Jn,{children:e(Ar,{checked:p.includes(a.id),onCheckedChange:()=>f?.(a.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${a.id}`})}),r.map(t=>e(Jn,{className:t.className,children:t.render?t.render(a):String(a[t.key]??"-")},String(t.key))),d&&e(Jn,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(a)})]},a.id))})]})})}function jc({onEdit:a,onDelete:r,onToggleStatus:s,isActive:n=!0,canEdit:i=!0,canDelete:o=!0,customActions:l=[],renderAs:d="dropdown",variant:c="default"}){const{t:u}=Ns(),m=[];return a&&i&&m.push({icon:U,label:u("edit"),onClick:a,variant:"default"}),s&&m.push({icon:n?V:q,label:u(n?"deactivate":"activate"),onClick:s,variant:"default"}),l.forEach(e=>{!1!==e.show&&m.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),r&&o&&m.push({icon:B,label:u("remove"),onClick:r,variant:"destructive"}),0===m.length?null:"dropdown"===d?t(ni,{children:[e(ii,{asChild:!0,children:e(Va,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e(C,{size:"compact"===c?14:16})})}),e(hi,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:m.map((a,r)=>t(pi,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},r))})]}):e("div",{className:"flex items-center gap-1",children:m.map((a,r)=>t(Va,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:a.onClick,className:"compact"===c?"h-7 px-2":"",children:[a.icon&&e(a.icon,{size:"compact"===c?14:16}),"compact"!==c&&e("span",{className:"ml-1",children:a.label})]},r))})}function Mc({searchValue:a="",onSearchChange:r,customFilters:s=[],onClearFilters:n,showClearButton:i=!0,layout:o="horizontal"}){const{t:l}=Ns(),d=a||s.length>0;return t("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&t("div",{className:"relative flex-1 min-w-[200px]",children:[e(M,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Ba,{type:"text",placeholder:l("search"),value:a,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),s.map((t,a)=>e("div",{className:"vertical"===o?"w-full":"",children:t},a)),i&&d&&n&&t(Va,{variant:"ghost",size:"sm",onClick:n,className:"h-9 px-3 whitespace-nowrap",children:[e(S,{size:14,className:"mr-1"}),l("clear_filters")]})]})}function zc({data:t,renderCard:a,isLoading:r=!1,emptyMessage:s="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return r?e(Xl,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((t,a)=>e(Xr,{className:"h-48 w-full"},a))}):0===t.length?e("div",{className:"flex items-center justify-center p-8",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:s})})}):e(Xl,{cols:n?String(n):"auto-fit",gap:i,className:o,children:t.map(a)})}function Dc(e){const t=yt();return{onNew:()=>{const a=e.newPath||`${e.basePath}/new`;t(a)},onEdit:a=>{const r=e.editPath?e.editPath.replace(":id",a.id):`${e.basePath}/${a.id}/edit`;t(r)}}}function $c(e,t){const a=Dc({basePath:e,newPath:t.newPath,editPath:t.editPath});return{useCustomRouting:!0,onNew:a.onNew,onEdit:a.onEdit}}Oc.displayName=zt.Item.displayName;const Uc=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Vc=[{value:"dd/MM/yyyy HH:mm",label:"dd/MM/yyyy HH:mm",example:"28/11/2024 14:30",description:"Padrão Brasileiro"},{value:"MM/dd/yyyy hh:mm a",label:"MM/dd/yyyy hh:mm a",example:"11/28/2024 02:30 PM",description:"Padrão Americano (12h)"},{value:"MM/dd/yyyy HH:mm",label:"MM/dd/yyyy HH:mm",example:"11/28/2024 14:30",description:"Padrão Americano (24h)"},{value:"yyyy-MM-dd HH:mm",label:"yyyy-MM-dd HH:mm",example:"2024-11-28 14:30",description:"ISO 8601"},{value:"dd.MM.yyyy HH:mm",label:"dd.MM.yyyy HH:mm",example:"28.11.2024 14:30",description:"Padrão Europeu"},{value:"d MMM yyyy, HH:mm",label:"d MMM yyyy, HH:mm",example:"28 Nov 2024, 14:30",description:"Formato Longo"}],qc=[{value:"America/Sao_Paulo",label:"Brasília (UTC-3)",offset:"-03:00"},{value:"America/Noronha",label:"Fernando de Noronha (UTC-2)",offset:"-02:00"},{value:"America/Manaus",label:"Manaus (UTC-4)",offset:"-04:00"},{value:"America/Rio_Branco",label:"Rio Branco (UTC-5)",offset:"-05:00"},{value:"America/New_York",label:"New York (UTC-5/-4)",offset:"-05:00"},{value:"America/Chicago",label:"Chicago (UTC-6/-5)",offset:"-06:00"},{value:"America/Los_Angeles",label:"Los Angeles (UTC-8/-7)",offset:"-08:00"},{value:"Europe/London",label:"Londres (UTC+0/+1)",offset:"+00:00"},{value:"Europe/Paris",label:"Paris (UTC+1/+2)",offset:"+01:00"},{value:"Europe/Berlin",label:"Berlim (UTC+1/+2)",offset:"+01:00"},{value:"Asia/Tokyo",label:"Tóquio (UTC+9)",offset:"+09:00"},{value:"Australia/Sydney",label:"Sydney (UTC+10/+11)",offset:"+10:00"}],Bc=()=>{const{locale:a,datetimeFormat:r,timezone:s,setLocale:n,setDatetimeFormat:i,setTimezone:o}=Uo(),{t:l}=Ns();return t("div",{className:"space-y-4 p-4",children:[t("div",{children:[t("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e(He,{className:"h-4 w-4"}),l("language")]}),t(Nr,{value:a,onValueChange:n,children:[e(Cr,{children:e(kr,{})}),e(Pr,{children:Uc.map(e=>t(Ir,{value:e.value,children:[e.flag," ",e.label]},e.value))})]})]}),t("div",{children:[t("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e(ye,{className:"h-4 w-4"}),l("timezone")||"Fuso Horário"]}),t(Nr,{value:s,onValueChange:o,children:[e(Cr,{children:e(kr,{})}),e(Pr,{children:qc.map(t=>e(Ir,{value:t.value,children:t.label},t.value))})]})]}),t("div",{children:[t("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e(Re,{className:"h-4 w-4"}),l("dateTimeFormat")||"Formato de Data/Hora"]}),t(Nr,{value:r,onValueChange:i,children:[e(Cr,{children:e(kr,{})}),e(Pr,{children:Vc.map(a=>e(Ir,{value:a.value,children:t("div",{className:"flex flex-col items-start",children:[e("span",{children:a.label}),t("span",{className:"text-xs text-muted-foreground",children:[a.description," • ",a.example]})]})},a.value))})]})]})]})},Wc=s.memo(({variant:r="card",className:n="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:d,alias:u,isAuthenticated:m,logout:h,switchUnit:p}=In(),[f,g]=c(!1),b="true"===import.meta.env.VITE_SHOW_USER_PREFERENCES,v=d?.[0]||null,y=u?d?.find(e=>e.alias===u):v,x=d||[],N=i||y||v||v,w=s.useCallback(e=>{o?o(e):p(e)},[o,p]),k=s.useMemo(()=>{if(!x?.length)return[];const e=new Map;x.forEach(t=>{e.set(t.alias,t)});const t=Array.from(e.values()),a=t.find(e=>e.alias===N?.alias),r=t.filter(e=>e.alias!==N?.alias);return r.sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"})),a?[a,...r]:r},[x,N?.alias]);if(!m||!l)return null;const C=()=>t(a,{children:[t("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(je,{className:"h-5 w-5 text-primary-foreground"})})}),t("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),t("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",N?.name||"N/A"]})]})]}),N&&e("div",{className:"mt-3",children:t("div",{className:"flex items-center space-x-2",children:[e(Ke,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:N.name})]})}),k.length>1&&t("div",{className:"mt-2",children:[t("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",k.length]}),t("div",{className:"flex flex-wrap gap-1",children:[k.slice(0,3).map(t=>e(Lr,{variant:t.alias===N?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>w(t),children:t.name},t.alias)),k.length>3&&t(Lr,{variant:"outline",className:"text-xs",children:["+",k.length-3]})]})]})]});return"dropdown"===r?t(ni,{children:[e(ii,{asChild:!0,children:e(Va,{variant:"ghost",className:`h-auto p-2 ${n}`,children:t("div",{className:"flex items-center space-x-2",children:[t("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:N?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(je,{className:"h-4 w-4 text-primary-foreground"})}),e(_,{className:"h-4 w-4"})]})})}),t(hi,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[t(di,{children:[t(ui,{children:[e(Ve,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(mi,{children:k.map(a=>t(pi,{onClick:()=>w(a),className:a.alias===N?.alias?"bg-muted":"",children:[e(Ke,{className:"mr-2 h-4 w-4"}),a.name,a.alias===N?.alias&&e(Lr,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},a.alias))})]}),b&&e(vi,{}),b&&t(pi,{onClick:()=>g(!0),children:[e(Fe,{className:"mr-2 h-4 w-4"}),"Preferências"]}),t(pi,{onClick:h,children:[e(Ge,{className:"mr-2 h-4 w-4"}),"Sair"]})]}),b&&e(er,{open:f,onOpenChange:g,children:t(nr,{children:[e(ir,{children:e(dr,{children:"Preferências de Internacionalização"})}),e(Bc,{})]})})]}):t(Ka,{className:n,children:[e(Ga,{children:e(Qa,{className:"text-lg",children:"Informações do Usuário"})}),t(Xa,{className:"space-y-4",children:[e(C,{}),e(Za,{}),b&&t(Va,{variant:"outline",onClick:()=>g(!0),size:"sm",className:"w-full",children:[e(Fe,{className:"mr-2 h-4 w-4"}),"Preferências"]}),t(Va,{variant:"outline",onClick:h,size:"sm",className:"w-full",children:[e(Ge,{className:"mr-2 h-4 w-4"}),"Sair"]}),b&&e(er,{open:f,onOpenChange:g,children:t(nr,{children:[e(ir,{children:e(dr,{children:"Preferências de Internacionalização"})}),e(Bc,{})]})})]})]})}),Hc=n({});function Kc({children:t,config:a}){const r=o(()=>({navigation:a?.navigation,appName:a?.appName}),[a?.navigation,a?.appName]);return e(Hc.Provider,{value:r,children:t})}function Gc(){return i(Hc)}function Qc(){const e=vt(),{navigation:t}=Gc(),{t:a}=Ns();if(!t)return a("page");const r=t.find(t=>t.path===e.pathname);if(r)return r.label;const s=t.find(t=>e.pathname.startsWith(t.path+"/"));return s?.label||a("page")}function Jc(e,t){const[a,r]=c(e),s=l(),n=d(()=>{s.current&&(clearTimeout(s.current),s.current=void 0)},[]);return u(()=>(n(),s.current=setTimeout(()=>{r(e)},t),n),[e,t,n]),[a,n]}const Xc=h(function({actions:a}){const r=vt(),s=Qc(),{navigation:n,appName:i}=Gc(),{metadata:o,headerActions:l}=_o(),{t:d}=Ns(),{companies:m,alias:h,isSearchVisible:p,clearSearch:f,refreshData:g,switchUnit:b}=In(),v=h?m?.find(e=>e.alias===h)||m?.[0]||null:m?.[0]||null,[y,x]=bt(),[N,w]=c(()=>y.get("search")||""),[k,C]=Jc(N,sn.debounceDelay);u(()=>{if(!p)return;const e=new URLSearchParams(y);k?(e.set("search",k),e.set("page","1")):e.delete("search"),x(e)},[k,x,p]);const _=n?.find(e=>e.path===r.pathname)||n?.find(e=>r.pathname.startsWith(e.path+"/")),P=o.title||s,E=o.subtitle||_?.complementaryText||d("item_details");return e("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:t("div",{className:"flex items-center gap-4",children:[t("div",{className:"flex-shrink-0",children:[t("div",{className:"flex items-center gap-2 mb-1",children:[e("h1",{className:"text-lg font-semibold text-foreground truncate",children:P}),e(Lr,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:i||d("module")})]}),E&&e("p",{className:"text-sm text-muted-foreground truncate",children:E})]}),p&&t("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[t("div",{className:"relative flex-1",children:[e(M,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(Ba,{placeholder:d("search"),value:N,onChange:e=>(e=>{w(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e(Va,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-gray-100",onClick:()=>{C(),w("");const e=new URLSearchParams(y);e.delete("search"),e.delete("page"),x(e)},title:d("clear_search"),children:e(S,{size:14})})]}),e(Va,{variant:"outline",size:"sm",onClick:g,className:"flex-shrink-0 h-10 w-10 p-0",title:d("refresh_data"),children:e(Ve,{size:14})})]}),t("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(l||a)&&e("div",{className:"flex items-center gap-2",children:l||a}),import.meta.env.VITE_WIKI_URL&&e(Va,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>La(import.meta.env.VITE_WIKI_URL,e),title:d("open_wiki"),children:"Wiki"}),e("div",{className:"text-sm",children:e(Wc,{variant:"dropdown",selectedUnit:v,onUnitChange:b})})]})]})})}),Yc=({key:e,enabled:t,checkFn:a,staleTime:r=3e5,gcTime:s=6e5})=>ht({queryKey:["permission",e],queryFn:a,enabled:t,staleTime:r,gcTime:s,retry:0,refetchOnWindowFocus:!1}),Zc=(e={})=>{const{enabled:t=!0}=e,{alias:a}=In();return ht({queryKey:["active-modules",a],queryFn:async()=>{if(!a)return[];const e=Ws(),{data:t,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",a).eq("status","active").order("name");if(r){if(!Js.handleError(r))throw r;return[]}return t||[]},enabled:t&&!!a})},eu="forlogic-sidebar-pinned",tu=()=>{try{const e=localStorage.getItem(eu);return!!e&&JSON.parse(e)}catch{return!1}},au=e=>{const t=["border-l-yellow-400","border-l-green-400","border-l-blue-400","border-l-red-400","border-l-purple-400","border-l-pink-400"];return t[e%t.length]},ru=`https://${import.meta.env.VITE_SUPABASE_PROJECT_ID_STORAGE??import.meta.env.VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,su={logo:`${ru}/${cn.isQualiex?"logo-qualiex.svg":"logo.svg"}`,smallLogo:`${ru}/${cn.isQualiex?"small-forlogic.svg":"small.svg"}`},nu=su.logo,iu=su.smallLogo;function ou({appName:r,isPinned:s,onPinToggle:n,open:i,dropdownOpen:o,onDropdownChange:l}){const{t:d}=Ns(),{data:c,isLoading:u,error:m}=Zc({enabled:o}),h=e=>{((e,t)=>{const a=e?.find(e=>e.url===t);a?.url&&window.open(a.url,"_blank")})(c,e)};return t(rc,{className:"p-0 gap-0",children:[e("div",{className:"flex items-center justify-between h-[34px]",children:i?t(a,{children:[e("div",{className:"flex items-center pl-[12px]",children:e("img",{src:su.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e("button",{onClick:n,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(s?"bg-primary/20 text-primary":"hover:bg-muted text-muted-foreground"),children:e(Be,{className:"h-4 w-4"})})]}):e("div",{className:"flex items-center justify-center w-full h-[34px]",children:e("img",{src:su.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e("div",{className:"mt-2 pt-0",children:t(ni,{onOpenChange:l,children:[e(ii,{asChild:!0,children:i?t("div",{className:"bg-muted hover:bg-muted/80 text-foreground font-medium text-sm flex items-center justify-between cursor-pointer transition-all duration-200 h-8 px-3 gap-3 rounded-md w-full",children:[t("div",{className:"flex items-center gap-2 min-w-0",children:[e("img",{src:"https://ccjfvpnndclajkleyqkc.supabase.co/storage/v1/object/public/library-assets/composit.svg",alt:"Menu",className:"h-6 w-6 text-muted-foreground flex-shrink-0"}),e("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:r})]}),e(_,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e("div",{className:"flex items-center justify-center w-full h-8 bg-muted hover:bg-muted/80 rounded-md cursor-pointer transition-all duration-200 p-[5px]",children:e(_,{className:"h-6 w-6 text-muted-foreground"})})}),e(hi,{className:i?"w-80 bg-white rounded-lg shadow-lg border border-gray-200 p-4 z-50":"w-[58px] bg-white rounded-lg shadow-lg border border-gray-200 p-2 z-50",align:i?"start":"center",children:u?t("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e(I,{className:"h-4 w-4 animate-spin"}),e("span",{className:"text-sm",children:d("loading")})]}):m?t("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:d("error")})]}):c&&0!==c.length?e("div",{className:"space-y-2",children:c.map((a,r)=>e("div",{onClick:()=>h(a.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${au(r)} transition-colors duration-200\n `,children:t("div",{className:"flex items-center justify-between",children:[e("span",{className:"font-medium text-foreground text-sm",children:a.name}),a.url&&e(We,{className:"h-4 w-4 text-muted-foreground"})]})},a.id))}):e("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:d("no_results")})})]})})]})}function lu({direction:e="right",minWidth:t=224,maxWidth:a=384,defaultWidth:r=240,storageKey:s="sidebar-width",onResize:n,isOpen:i=!0}={}){const[o,m]=c(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(s);return e?parseInt(e):r}),[h,p]=c(!1),f=l(null);u(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(i?e.style.setProperty("--sidebar-width",`${o}px`):e.style.setProperty("--sidebar-width","240px"))},[o,i]);const g=d(e=>{e.preventDefault(),p(!0)},[]);return u(()=>{if(!h)return;const r=r=>{let s;s="left"===e?window.innerWidth-r.clientX:r.clientX,s=Math.max(t,Math.min(a,s)),m(s),n?.(s)},i=()=>{p(!1),localStorage.setItem(s,o.toString())};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",i),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)}},[h,e,t,a,o,s,n]),u(()=>{h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h,e]),{width:o,isDragging:h,dragRef:f,handleMouseDown:g}}function du({config:a,customContent:r,resizable:s=!1,minWidth:n=224,maxWidth:i=384}={}){const{t:o}=Ns(),{open:d,setOpen:m}=Jd(),h=vt(),{alias:p,user:f}=In(),[g,b]=c(!1),[v,y]=c(tu),[x,N]=c(!1),w=l(!1),k=s?lu({minWidth:n,maxWidth:i,storageKey:"app-sidebar-width",isOpen:d}):null;u(()=>{m(!!v||!(!x&&!g))},[v,x,g,m]);return t(Yd,{collapsible:"icon",onMouseEnter:()=>{v||w.current||N(!0)},onMouseLeave:()=>{v||N(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:k&&d?{width:`${k.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(ou,{appName:a?.appName||o("module_title"),isPinned:v,onPinToggle:()=>{const e=!v;y(e),(e=>{try{localStorage.setItem(eu,JSON.stringify(e))}catch{}})(e),e||(w.current=!0,N(!1),m(!1),setTimeout(()=>{w.current=!1},300))},open:d,dropdownOpen:g,onDropdownChange:b}),e(ic,{children:r||e(oc,{className:"p-0 mt-6",children:e(cc,{children:e(uc,{className:"space-y-2",children:e(Bd,{children:a?.navigation?.map((a,r)=>{const s=({item:a,index:r})=>{const n=`${a.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:i=!0,isLoading:l}=Yc({key:n,enabled:Boolean(a.permissionCheck&&p&&f?.id),checkFn:a.permissionCheck||(()=>Promise.resolve(!0))}),d=a.permissionCheck&&!i;if(d&&"Admin"===a.label)return null;const c=l?I:d?ie:a.icon;d?o("restricted_access"):a.complementaryText;return a.children&&a.children.length>0?e(qo,{defaultOpen:!0,className:"group/collapsible",children:t(mc,{children:[e(Bo,{asChild:!0,children:e(pc,{size:"lg",className:"h-10",children:t("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(c,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label}),e(D,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e(Wo,{children:e(vc,{children:a.children.map((t,a)=>e(s,{item:t,index:a},t.path))})})]})},a.path):e(mc,{children:d||l?t(Wd,{children:[e(Hd,{asChild:!0,children:e(pc,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:t("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(c,{className:"h-4 w-4 "+(l?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})}),e(Kd,{children:e("p",{children:o(l?"checking_access":"restricted_access")})})]}):e(pc,{asChild:!0,isActive:(u=a.path,h.pathname===u||h.pathname.startsWith(u+"/")),size:"lg",className:"h-10",children:t(xt,{to:a.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(c,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})},a.path);var u};return e(s,{item:a,index:r},a.path)})})})})})}),s&&k&&d&&e("div",{ref:k.dragRef,onMouseDown:k.handleMouseDown,className:Fa("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",k.isDragging&&"bg-primary/40")})]})}const cu=h(function({children:a,sidebar:r,sidebarConfig:s,showHeader:n=!0}){const i=o(()=>r||e(du,{config:s}),[r,s]),l=o(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(Kc,{config:s,children:e(So,{children:e(Xd,{defaultOpen:!1,style:l,children:t("div",{className:"sidebar-container min-h-screen flex w-full",children:[i,t("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(Xc,{})}),e("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:a})]})]})})})})}),uu={"pt-BR":Ll,"en-US":Nl,"es-ES":El},mu=(e,t="pt-BR")=>{if(!e)return"";const a=y(e);if(!x(a))return"Invalid date";return N(a,"PP",{locale:uu[t]||Ll})},hu=()=>{const{locale:e,timezone:t,datetimeFormat:a}=Uo();return{formatDatetime:e=>((e,t="dd/MM/yyyy HH:mm")=>{if(!e)return"";const a=y(e);return x(a)?N(a,t):"Invalid date"})(e,a,t),formatDate:t=>mu(t,e),locale:e,timezone:t,datetimeFormat:a}};class pu{static async sendEmail(e){const t=Ws(),{data:a,error:r}=await t.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return a}}const fu=pu;function gu(){const[e,t]=c([]),[a,r]=c(!1),[s,n]=c(null),[i,o]=c(null);u(()=>{l()},[]);const l=async()=>{try{const e=Ws(),{data:a,error:r}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(r)throw r;n(a.threadId),t([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){o("Erro ao inicializar conversa"),w.error("Erro ao inicializar conversa")}};return{messages:e,isLoading:a,error:i,sendMessage:d(async e=>{if(!s||!e.trim())return;const a={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};t(e=>[...e,a]),r(!0),o(null);try{const a=Ws(),{data:r,error:n}=await a.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:s,message:e}});if(n)throw n;const{runId:i}=r,o=await(async e=>{if(!s)return!1;for(let a=0;a<60;a++)try{const t=Ws(),{data:a,error:r}=await t.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:s,runId:e}});if(r)throw r;const{status:n}=a;if("completed"===n)return!0;if("failed"===n||"cancelled"===n)throw new Error("O assistente encontrou um erro");await new Promise(e=>setTimeout(e,1e3))}catch(t){throw t}throw new Error("Tempo limite excedido")})(i);o&&await(async()=>{if(s)try{const e=Ws(),{data:a,error:r}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:s}});if(r)throw r;const n=a.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));t(n)}catch(e){throw e}})()}catch(n){const e=n instanceof Error?n.message:"Erro ao enviar mensagem";o(e),w.error(e),t(e=>e.filter(e=>e.id!==a.id))}finally{r(!1)}},[s]),threadId:s}}function bu({content:t,className:a}){return e("div",{className:Fa("prose prose-sm max-w-none",a),children:e(Dt,{remarkPlugins:[$t],components:{h1:({children:t})=>e("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:t}),h2:({children:t})=>e("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:t}),h3:({children:t})=>e("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:t}),p:({children:t})=>e("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:t}),ul:({children:t})=>e("ul",{className:"list-disc list-inside mb-2 space-y-1",children:t}),ol:({children:t})=>e("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:t}),li:({children:t})=>e("li",{className:"text-sm text-foreground",children:t}),code:({inline:t,children:a,...r})=>e("code",t?{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...r,children:a}:{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...r,children:a}),pre:({children:t})=>e("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:t}),a:({children:t,href:a})=>e("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:t}),blockquote:({children:t})=>e("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:t}),strong:({children:t})=>e("strong",{className:"font-bold text-foreground",children:t}),em:({children:t})=>e("em",{className:"italic text-foreground",children:t})},children:t})})}function vu(){const{t:r}=Ns(),[s,n]=c(!1),[i,o]=c(""),{messages:d,isLoading:m,error:h,sendMessage:p}=gu(),f=l(null),g=l(null);u(()=>{if(f.current){const e=f.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[d]),u(()=>{s&&g.current&&g.current.focus()},[s]),u(()=>{const e=e=>{"Escape"===e.key&&s&&n(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[s]);const b=()=>{i.trim()&&!m&&(p(i),o(""))};return t(a,{children:[e(Va,{onClick:()=>n(!s),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:e(s?S:Qe,{className:"h-6 w-6"})}),s&&t(Ka,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[t(Ga,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e(Qa,{className:"text-lg font-semibold",children:r("title")}),e(Va,{variant:"ghost",size:"icon",onClick:()=>n(!1),className:"h-8 w-8",children:e(S,{className:"h-4 w-4"})})]}),t(Xa,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e(Vi,{ref:f,className:"flex-1 px-4",children:t("div",{className:"space-y-4 py-4",children:[d.map(t=>e("div",{className:"flex "+("user"===t.role?"justify-end":"justify-start"),children:e("div",{className:"max-w-[80%] rounded-lg px-4 py-2 "+("user"===t.role?"bg-primary text-primary-foreground":"bg-muted"),children:"assistant"===t.role?e(bu,{content:t.content}):e("p",{className:"text-sm whitespace-pre-wrap",children:t.content})})},t.id)),m&&e("div",{className:"flex justify-start",children:e("div",{className:"bg-muted rounded-lg px-4 py-2",children:t("div",{className:"flex space-x-2",children:[e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),e("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),h&&e("div",{className:"text-center text-sm text-destructive py-2",children:h})]})}),e("div",{className:"border-t p-4",children:t("div",{className:"flex space-x-2",children:[e(Ba,{ref:g,value:i,onChange:e=>o(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),b())},placeholder:r("placeholder"),disabled:m,className:"flex-1"}),e(Va,{onClick:b,disabled:m||!i.trim(),size:"icon",children:e(Je,{className:"h-4 w-4"})})]})})]})]})]})}function yu({open:a,onOpenChange:r,placeId:s,placeName:n,onMakeManager:i,onMakeMembers:l,currentManagerId:d,currentMemberIds:u=[]}){const{t:m}=Ns(),[h,p]=c([]),[f,g]=c(!1),[b,v]=c(""),{data:y=[],isLoading:x}=Ki({enabled:a}),N=o(()=>{let e=[...y];if(e.sort((e,t)=>{const a=e.userName?.toLowerCase()||"",r=t.userName?.toLowerCase()||"";return a.localeCompare(r)}),b){const t=b.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(t)||e.userEmail?.toLowerCase().includes(t))}return e},[y,b]),w=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},k=1===h.length,C=h.length>0;return e(er,{open:a,onOpenChange:r,children:t(nr,{className:"max-w-2xl",children:[e(ir,{children:t(dr,{className:"flex items-center gap-2",children:[e(Xe,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),t("div",{className:"relative",children:[e(M,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(Ba,{placeholder:m("search_placeholder"),value:b,onChange:e=>v(e.target.value),className:"pl-9"})]}),e(Vi,{className:"h-[400px] pr-4",children:x?e("div",{className:"space-y-2",children:[...Array(5)].map((t,a)=>e(Xr,{className:"h-16 w-full"},a))}):0===N.length?t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(Xe,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:b?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:N.map(a=>{const r=a.userId===d,s=u.includes(a.userId||""),n=h.includes(a.userId||"");return t("div",{className:Fa("flex items-center gap-3 p-3 rounded-lg border transition-colors",n&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>w(a.userId||""),children:[e(Ar,{checked:n,onCheckedChange:()=>w(a.userId||""),onClick:e=>e.stopPropagation()}),t("div",{className:"flex-1",children:[t("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:a.userName}),r&&e(Ye,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(r||s)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},a.userId)})})}),t(lr,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:h.length>0&&t("span",{children:[h.length," selecionado(s)"]})}),k&&i&&t(Va,{onClick:async()=>{if(i&&1===h.length){g(!0);try{await i(h[0],s),p([])}finally{g(!1)}}},disabled:f,variant:"outline",children:[e(Ye,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&l&&t(Va,{onClick:async()=>{if(l&&0!==h.length){g(!0);try{await l(h,s),p([])}finally{g(!1)}}},disabled:f,children:[e(Ze,{className:"h-4 w-4 mr-2"}),"Tornar ",h.length>1?"Membros":"Membro"]})]})]})})}function xu({place:a,level:r=0,manageAccessConfig:s}){const[n,i]=c(!1),[o,l]=c(!1),d=a.subPlaces&&a.subPlaces.length>0,u=a.isActive??!0,m=a.usersCount??0;return t("div",{children:[t(qo,{open:n,onOpenChange:i,children:[t("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[d?t(Bo,{className:"flex items-center gap-2 flex-1",children:[e(D,{className:Fa("h-4 w-4 transition-transform shrink-0",n&&"rotate-90")}),e(Ke,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:a.name}),t("span",{className:"text-sm text-muted-foreground",children:["(",a.subPlaces.length,")"]})]}):t("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(Ke,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:a.name})]}),t("div",{className:"flex items-center gap-3 ml-auto",children:[t("div",{className:"flex items-center gap-1.5",children:[e(Xe,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(Lr,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),s&&e(jc,{customActions:[{label:"Gerenciar Acessos",icon:Fe,onClick:()=>l(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e(Wo,{children:a.subPlaces.map(t=>e(xu,{place:t,level:r+1,manageAccessConfig:s},t.id))})]}),0===r&&e(Za,{}),s&&e(yu,{open:o,onOpenChange:l,placeId:a.id,placeName:a.name,onMakeManager:s.onMakeManager,onMakeMembers:s.onMakeMembers,currentManagerId:s.getCurrentManagerId?.(a.id),currentMemberIds:s.getCurrentMemberIds?.(a.id)})]})}function Nu({places:a,isLoading:r,manageAccessConfig:s}){const{t:n}=Ns();return r?e("div",{className:"flex items-center justify-center py-12",children:t("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:n("loading_data")})]})}):a&&0!==a.length?t("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(t=>e(xu,{place:t,manageAccessConfig:s},t.id))]}):t("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(Ke,{className:"h-12 w-12 text-muted-foreground/50"}),t("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}var wu=Object.defineProperty,ku=(e,t,a)=>((e,t,a)=>t in e?wu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const Cu=new class{constructor(){ku(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const r=Ys.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const s=Fs.getAccessToken();if(!s)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{n.searchParams.append(e,t)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const t=new Map,a=[];return e.forEach(e=>{t.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=t.get(e.id);if(e.parentId){const s=t.get(e.parentId);s?(s.subPlaces=s.subPlaces||[],s.subPlaces.push(r)):a.push(r)}else a.push(r)}),a}async getPlaces(e,t){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(a){if(await Ys.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(r){return zs.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return zs.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};function Su(e,t){const a=e.map(e=>({...e})),r=new Set(a.filter(e=>!t.has(e.id_user)).map(e=>e.id_user));return a.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let t=e.id_leader;for(;t&&r.has(t);){const e=a.find(e=>e.id_user===t);t=e?.id_leader||null}e.id_leader=t}}),a.filter(e=>t.has(e.id_user))}function _u(e){const t=new Map,a=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};t.set(e.id,r),a.set(e.id_user,r)}),e.forEach(e=>{const s=t.get(e.id);if(e.id_leader){const t=a.get(e.id_leader);if(t)return void t.children.push(s)}r.push(s)});const s=(e,t)=>{e.level=t,e.children.forEach(e=>s(e,t+1))};r.forEach(e=>s(e,0));const n=e=>{e.sort((e,t)=>{const a=e.name||e.id_user||e.email||"",r=t.name||t.id_user||t.email||"";return a.localeCompare(r)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(r),r}function Pu(e){const t=[],a=e=>{t.push(e),e.children.forEach(a)};return e.forEach(a),t}function Eu(){const{alias:e,isAuthenticated:t}=In(),a=Fs.getAccessToken(),{data:r=[]}=Ki({enabled:!0});return ht({queryKey:["leadership",e,r.length],queryFn:async()=>{if(!a||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=Ws(),{data:s,error:n}=await t.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(n)throw new Error("Erro ao buscar hierarquia de liderança");if(!s||0===s.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=s.map(e=>({...e,name:i[e.id_user]?.name||"[Não encontrado]",email:i[e.id_user]?.email||"",subordinatesCount:s.filter(t=>t.id_leader===e.id_user).length})),l=new Set(s.map(e=>e.id_user));return new Set(s.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const t=i[e];o.push({id:`virtual-${e}`,alias:s[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:t?.name||"[Não encontrado]",email:t?.email||"",subordinatesCount:s.filter(t=>t.id_leader===e).length})}),_u(o)},enabled:!!a&&!!e&&t&&r.length>0})}function Iu(){const e="common",{alias:t}=In(),a=mt(),r=Ws();return pt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");if(a.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");if((await r.schema(e).from("leaders").select("id").eq("alias",t).eq("id_user",a.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");a.id_leader&&await Fu(r,t,e,a.id_user,a.id_leader);const{data:s,error:n}=await r.schema(e).from("leaders").insert({alias:t,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return s},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),w.success("Líder adicionado com sucesso")},onError:e=>{w.error(e.message||"Erro ao adicionar líder")}})}function Tu(){const e="common",{alias:t}=In(),a=mt(),r=Ws();return pt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");if(a.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await Fu(r,t,e,a.id_user,a.id_leader);const{data:s,error:n}=await r.schema(e).from("leaders").insert({alias:t,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return s},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),w.success("Líder virtual promovido com sucesso")},onError:e=>{w.error(e.message||"Erro ao criar líder")}})}function Au(){const e="common",{alias:t}=In(),a=mt(),r=Ws();return pt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");if(!a.users.length)throw new Error("Selecione pelo menos um liderado");const s=a.users.map(e=>e.id_user),{data:n}=await r.schema(e).from("leaders").select("id_user").eq("alias",t).in("id_user",s).eq("is_removed",!1);if(n&&n.length>0){const e=n.map(e=>e.id_user);throw new Error(`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`)}for(const d of a.users){if(a.id_leader&&d.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await Fu(r,t,e,d.id_user,a.id_leader)}const i=a.users.map(e=>({alias:t,id_user:e.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await r.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),w.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{w.error(e.message||"Erro ao adicionar liderados")}})}function Ru(){const e="common",{alias:t}=In(),a=mt(),r=Ws();return pt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");const{data:s}=await r.schema(e).from("leaders").select("id_user").eq("id",a.id).eq("alias",t).single();if(!s)throw new Error("Líder não encontrado");if(s.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await Fu(r,t,e,s.id_user,a.id_leader,a.id);const{data:n,error:i}=await r.schema(e).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",t).select().single();if(i)throw i;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),w.success("Líder atualizado com sucesso")},onError:e=>{w.error(e.message||"Erro ao atualizar líder")}})}function Ou(){const{alias:e}=In(),t=mt(),a=Ws();return pt({mutationFn:async t=>{if(!e)throw new Error("Unidade não selecionada");const{error:r}=await a.schema("common").from("leaders").update({is_removed:!0}).eq("id",t).eq("alias",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",e]}),w.success("Líder removido com sucesso")},onError:e=>{w.error(e.message||"Erro ao remover líder")}})}function Lu(){const e="common",{alias:t}=In(),a=mt(),r=Ws();return pt({mutationFn:async({leaderUserId:a,selectedUsers:s})=>{if(!t)throw new Error("Unidade não selecionada");const n=s.map(e=>e.id_user),i=await Promise.all([r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).eq("id_leader",a),r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).in("id_user",n.length?n:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=i;if(l)throw l;if(c)throw c;const u=o||[],m=d||[],h=new Set(n),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),b=s.filter(e=>!g.has(e.id_user));for(const x of f)await Fu(r,t,e,x.id_user,a,x.id);for(const x of b){if(x.id_user===a)throw new Error("Usuário não pode ser seu próprio líder");await Fu(r,t,e,x.id_user,a)}const v=[];if(p.length){const a=p.map(e=>e.id);v.push(r.schema(e).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",t))}if(f.length){const s=f.map(e=>e.id);v.push(r.schema(e).from("leaders").update({id_leader:a}).in("id",s).eq("alias",t))}if(b.length){const s=b.map(e=>({alias:t,id_user:e.id_user,id_leader:a,is_active:!0,is_removed:!1}));v.push(r.schema(e).from("leaders").insert(s))}const y=(await Promise.all(v)).find(e=>e?.error);if(y?.error)throw y.error;return{unlinked:p.length,updated:f.length,created:b.length}},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),w.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{w.error(e.message||"Erro ao sincronizar subordinados")}})}async function Fu(e,t,a,r,s,n){const{data:i,error:o}=await e.schema(a).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(o)throw o;const l=n?i.filter(e=>e.id!==n):i,d=new Set;let c=s;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===r)throw new Error("Esta associação criaria um ciclo na hierarquia");d.add(c);const e=l.find(e=>e.id_user===c);c=e?.id_leader||null}}function ju({leader:r,expandedIds:s,onToggleExpand:n,onEdit:i}){const o=s.has(r.id),l=r.children.length>0,d=32*r.level;return t(a,{children:[t("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:t("div",{className:"flex items-center gap-2",style:{paddingLeft:`${d}px`},children:[l?e("button",{onClick:()=>n(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?_:D,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(je,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(t=>e(ju,{leader:t,expandedIds:s,onToggleExpand:n,onEdit:i},t.id))]})}var Mu=function(e,t){for(var a={};e.length;){var r=e[0],s=r.code,n=r.message,i=r.path.join(".");if(!a[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];a[i]={message:o.message,type:o.code}}else a[i]={message:n,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=a[i].types,d=l&&l[r.code];a[i]=it(i,t,a,s,d?[].concat(d,r.message):r.message)}e.shift()}return a},zu=function(e,t,a){return void 0===a&&(a={}),function(r,s,n){try{return Promise.resolve(function(s,i){try{var o=Promise.resolve(e["sync"===a.mode?"parse":"parseAsync"](r,t)).then(function(e){return n.shouldUseNativeValidation&&Vt({},n),{errors:{},values:a.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:qt(Mu(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const Du=Ut.object({id_leader:Ut.string().nullable(),id_users:Ut.array(Ut.string()).min(1,"Selecione pelo menos um liderado")}),$u=Ut.object({id_leader:Ut.string().nullable(),id_users:Ut.array(Ut.string())});function Uu({value:a,onChange:r,excludeUserIds:s=[],error:n}){const{data:i=[],isLoading:o}=Ki(),[d,m]=c(""),h=l(null),p=l(0),{t:f}=Ns(),g=i.filter(e=>!s.includes(e.userId||"")).filter(e=>{const t=d.toLowerCase(),a=e.userName?.toLowerCase().includes(t);return a}).sort((e,t)=>{const r=a.includes(e.userId),s=a.includes(t.userId);if(r&&!s)return-1;if(!r&&s)return 1;const n=e.userName||e.userEmail||"",i=t.userName||t.userEmail||"";return n.localeCompare(i)});return u(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[g]),t("div",o?{className:"flex items-center justify-center p-4",children:[e(I,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:f("loading_data")})]}:{className:"space-y-2",children:[e(Ba,{placeholder:f("search_user"),value:d,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===g.length?e("p",{className:"text-sm text-muted-foreground",children:f("search_user")}):e("div",{className:"space-y-2",children:g.map(s=>t("div",{className:"flex items-center space-x-2",children:[e(Ar,{id:s.userId,checked:a.includes(s.userId),onCheckedChange:()=>{return e=s.userId,h.current&&(p.current=h.current.scrollTop),void(a.includes(e)?r(a.filter(t=>t!==e)):r([...a,e]));var e}}),e(Ha,{htmlFor:s.userId,className:"flex-1 cursor-pointer",children:s.userName||s.userEmail})]},s.userId))})}),a.length>0&&e("p",{className:"text-sm text-muted-foreground",children:f("selected_count",{count:a.length})}),n&&e("p",{className:"text-sm text-destructive",children:n})]})}function Vu({leader:r,prefilledLeaderId:s,onSuccess:n}){const{t:i}=Ns(),{alias:o}=In(),l=!!r,d=r?.id.startsWith("virtual-"),m=Au(),h=Tu(),p=Ru(),f=Lu(),g=Ou(),{data:b=[]}=Eu(),{data:v=[]}=Ki(),[y,x]=c(""),N=Pu(b).map(e=>e.id_user),w=l?Pu(b).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],k=ot({resolver:zu(l?$u:Du),defaultValues:{id_leader:s||(l?r?.id_leader:null)||null,id_users:l?w:[]}});u(()=>{if(r){const e=Pu(b).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);k.reset({id_leader:r.id_leader||null,id_users:e})}else s?k.reset({id_leader:s,id_users:[]}):k.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,s,b]);const C=m.isPending||h.isPending||p.isPending||f.isPending||g.isPending,S=k.watch("id_leader"),_=k.watch("id_users"),P=l?[r.id_user,...N.filter(e=>e!==r.id_user&&!_.includes(e)&&!w.includes(e))]:[S,...N.filter(e=>!_.includes(e))].filter(Boolean);return t("form",{onSubmit:k.handleSubmit(async e=>{try{if(l)if(d){await h.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const t=v.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await f.mutateAsync({leaderUserId:r.id_user,selectedUsers:t})}else{await p.mutateAsync({id:r.id,id_leader:e.id_leader});const t=v.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await f.mutateAsync({leaderUserId:r.id_user,selectedUsers:t})}else{const t=v.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({id_leader:e.id_leader,users:t})}n?.()}catch(t){}}),className:"space-y-4",children:[l&&t("div",{children:[e(Ha,{children:i("leader")}),e(Ba,{value:v.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),t("div",{children:[e(Ha,{children:i("superior")}),t(Nr,{value:S||"none",onValueChange:e=>k.setValue("id_leader","none"===e?null:e),children:[e(Cr,{children:e(kr,{placeholder:i("select_placeholder")})}),t(Pr,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(Ba,{placeholder:i("superior_search"),value:y,onChange:e=>x(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),t(Vi,{className:"h-[200px]",children:[e(Ir,{value:"none",children:"[Nenhum]"}),v.filter(e=>{const t=l?e.userId!==r.id_user:!_.includes(e.userId),a=!y||e.userName?.toLowerCase().includes(y.toLowerCase());return t&&a}).sort((e,t)=>{const a=e.userName||e.userEmail||"",r=t.userName||t.userEmail||"";return a.localeCompare(r)}).map(t=>e(Ir,{value:t.userId,children:t.userName},t.userId))]})]})]},`superior-select-${o}`),k.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:k.formState.errors.id_leader.message})]}),t("div",{children:[t(Ha,{children:[i("subordinates")," *"]}),e(Uu,{value:_,onChange:e=>k.setValue("id_users",e),excludeUserIds:P,error:k.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),t("div",{className:"flex items-center justify-between gap-2",children:[e(Va,{type:"submit",disabled:C||!l&&0===_.length,children:C&&!g.isPending?t(a,{children:[e(I,{className:"mr-2 h-4 w-4 animate-spin"}),i(l?"updating":"saving")]}):l?_.length>0?i("update_success",{count:_.length}):i("update"):i("create_success",{count:_.length})}),l&&!S&&0===_.length&&e(Va,{type:"button",variant:"destructive",disabled:C,onClick:async()=>{if(r&&window.confirm(i("remove_confirm")))try{await g.mutateAsync(r.id),n?.()}catch(e){}},className:"ml-auto",children:g.isPending?t(a,{children:[e(I,{className:"mr-2 h-4 w-4 animate-spin"}),i("removing")]}):t(a,{children:[e(B,{className:"mr-2 h-4 w-4"}),i("remove")]})})]})]})}function qu({open:a,onOpenChange:r,leader:s,prefilledLeaderId:n,title:i}){return e(er,{open:a,onOpenChange:r,children:t(nr,{className:"sm:max-w-[500px]",children:[e(ir,{children:e(dr,{children:i})}),e(Vu,{leader:s,prefilledLeaderId:n,onSuccess:()=>r(!1)})]})})}const Bu="leadership-expanded-nodes",Wu=(e,t)=>{try{localStorage.setItem(`${Bu}-${e}`,JSON.stringify(Array.from(t)))}catch(a){}};function Hu(){const{alias:a}=In(),{t:r}=Ns(),{data:s,isLoading:n,error:i,refetch:o}=Eu(),{data:l=[]}=Ki({enabled:!0}),[d,m]=c(()=>a?(e=>{try{const t=localStorage.getItem(`${Bu}-${e}`);if(t)return new Set(JSON.parse(t))}catch(i){}return new Set})(a):new Set),[h,p]=c(!1),[f,g]=c(),[b,v]=c(null),y=l.filter(e=>e.userName&&"Nome não disponível"!==e.userName),x=new Set(y.map(e=>e.userId)),N=y.length-(s?Pu(s).filter(e=>x.has(e.id_user)&&"[Não encontrado]"!==e.name).length:0);u(()=>{if(s&&s.length>0&&a){if(!localStorage.getItem(`${Bu}-${a}`)){const e=s.map(e=>e.id),t=new Set(e);m(t),Wu(a,t)}}},[s,a]);const w=e=>{m(t=>{const r=new Set(t);return r.has(e)?r.delete(e):r.add(e),a&&Wu(a,r),r})},k=e=>{g(e),v(null),p(!0)};return n?e("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center",children:[e(Ve,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:r("loading")})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(Va,{onClick:()=>o(),children:"Tentar novamente"})]})}):t("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:t("div",{className:"flex gap-2 items-center",children:[t(Va,{size:"sm",onClick:()=>{g(void 0),v(null),p(!0)},children:[e(W,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),t(Va,{variant:"outline",size:"sm",onClick:()=>{if(!s)return;const e=Pu(s).filter(e=>e.children.length>0).map(e=>e.id),t=new Set(e);m(t),a&&Wu(a,t)},disabled:!s||0===s.length,children:[e(_,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),t(Va,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;m(e),a&&Wu(a,e)},disabled:!s||0===s.length,children:[e(D,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:t("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(Xe,{className:"h-4 w-4 text-muted-foreground"}),t("span",{className:"text-sm font-medium",children:[N," usuário",1!==N?"s":""," não associado",1!==N?"s":""]})]})})]})}),s&&0!==s.length?e(Vi,{className:"flex-1",children:e("div",{children:t("table",{className:"w-full",children:[e("thead",{children:t("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:s.map(t=>e(ju,{leader:t,expandedIds:d,onToggleExpand:w,onEdit:k},t.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:t("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(qu,{open:h,onOpenChange:()=>{p(!1),g(void 0),v(null)},leader:f,prefilledLeaderId:b,title:f?r("edit")+" "+r("name"):b?r("add")+" Liderado":r("add")+" Líder Raiz"},`leadership-dialog-${a}`)]})}function Ku(e){const[t,a]=c(!1),[r,s]=c(0),{t:n}=Ns(),{uploadFunction:i,deleteFunction:o,defaultOptions:l,onSuccess:d,onError:u}=e||{};return{upload:async(e,t)=>{if(!i){const e=new Error("uploadFunction não fornecida");throw w.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}a(!0),s(0);try{const a={...l,...t};if(a.maxSize&&e.size>a.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(a.maxSize/1024/1024)}MB`);if(a.allowedTypes){if(!a.allowedTypes.some(t=>t.endsWith("/*")?e.type.startsWith(t.replace("/*","")):e.type===t))throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${a.allowedTypes.join(", ")}`)}const r=await i(e,a);return s(100),w.success("Sucesso",{description:n("file_upload_success")}),d?.(r),r}catch(r){const e=r instanceof Error?r:new Error("Erro ao fazer upload");throw w.error("Erro",{description:e.message}),u?.(e),e}finally{a(!1)}},deleteMedia:async(e,t)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw w.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await o(e,t),w.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(a){throw w.error("Erro",{description:"Erro ao remover o arquivo"}),a}},uploading:t,progress:r}}function Gu(e){const t=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const a of t){const t=e.match(a);if(t)return t[1]}return null}function Qu(e,t){const a=Gu(e);if(!a)return e;return`https://www.youtube.com/embed/${a}${t?"?autoplay=1&mute=1":""}`}function Ju(e){const t=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function Xu(e,t){const a=Ju(e);if(!a)return e;return`https://player.vimeo.com/video/${a}${t?"?autoplay=1&muted=1":""}`}function Yu(e){if(!e)return;const t=e.match(/src="([^"]+)"/);return t?t[1]:void 0}function Zu(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function em(e,t,a){switch(t||Zu(e)){case"youtube":return Qu(e,a);case"vimeo":return Xu(e,a);default:return e}}function tm({value:r,onChange:s,onSubmit:n,onCancel:i,uploadFunction:d,deleteFunction:u,uploadOptions:m}){const{t:h}=Ns(),[p,f]=c(r||{inputType:"url",controls:!0}),g=l(null),b=l(null),{upload:v,uploading:y}=Ku({uploadFunction:d,deleteFunction:u,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:x,uploading:N}=Ku({uploadFunction:d,deleteFunction:u,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),k=o(()=>Zu(p.videoUrl||Yu(p.embedCode)||""),[p.videoUrl,p.embedCode]),C=(e,t)=>{const a={...p,[e]:t};f(a),s(a)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[e(Ha,{children:h("input_type")}),t(Nr,{value:p.inputType||"url",onValueChange:e=>C("inputType",e),children:[e(Cr,{children:e(kr,{})}),t(Pr,{children:[e(Ir,{value:"url",children:h("url")}),e(Ir,{value:"upload",children:h("input_type_upload")}),e(Ir,{value:"embed",children:h("input_type_embed")})]})]})]}),"upload"===p.inputType&&d&&t("div",{className:"space-y-2",children:[e(Ha,{children:h("file")}),t("div",{className:"flex gap-2",children:[e("input",{ref:g,type:"file",accept:"video/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await v(t),a={...p,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:p.title||t.name.replace(/\.[^/.]+$/,"")};f(a),s(a)}catch(a){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(Va,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:y,children:t(a,y?{children:[e(I,{className:"mr-2 h-4 w-4 animate-spin"}),h("uploading")]}:{children:[e(pe,{className:"mr-2 h-4 w-4"}),h("select_video")]})}),p.videoFile&&e("span",{className:"text-xs text-muted-foreground truncate self-center",children:h("video.fileInfo",{name:p.videoFile,size:Math.round((p.videoSize||0)/1024/1024)})})]})]}),"embed"===p.inputType&&t("div",{className:"space-y-2",children:[e(Ha,{children:h("embed")}),e(Rr,{placeholder:h("embed"),value:p.embedCode||"",onChange:e=>C("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),d&&t("div",{className:"space-y-2",children:[e(Ha,{children:h("thumbnail")}),t("div",{className:"flex gap-2",children:[e(Ba,{type:"url",placeholder:h("thumbnail"),value:p.thumbnail||"",onChange:e=>C("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:b,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await x(t),a={...p,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};f(a),s(a)}catch(a){}finally{b.current&&(b.current.value="")}},className:"hidden"}),e(Va,{type:"button",variant:"outline",onClick:()=>b.current?.click(),disabled:N,children:t(a,N?{children:[e(I,{className:"mr-2 h-4 w-4 animate-spin"}),h("video.uploading")]}:{children:[e(pe,{className:"mr-2 h-4 w-4"}),h("upload")]})})]}),p.thumbnailFile&&e("p",{className:"text-xs text-muted-foreground",children:h("video.thumbnailFileInfo",{name:p.thumbnailFile})})]}),t("div",{className:"space-y-2",children:[e(Ha,{htmlFor:"title",children:h("title")}),e(Ba,{id:"title",placeholder:h("title"),value:p.title||"",onChange:e=>C("title",e.target.value)})]}),t("div",{className:"flex gap-6",children:[t("div",{className:"flex items-center gap-2",children:[e("input",{id:"autoplay",type:"checkbox",checked:p.autoplay||!1,onChange:e=>C("autoplay",e.target.checked),className:"h-4 w-4"}),e(Ha,{htmlFor:"autoplay",className:"cursor-pointer",children:h("video.autoplay")})]}),t("div",{className:"flex items-center gap-2",children:[e("input",{id:"controls",type:"checkbox",checked:!1!==p.controls,onChange:e=>C("controls",e.target.checked),className:"h-4 w-4"}),e(Ha,{htmlFor:"controls",className:"cursor-pointer",children:h("video.controls")})]})]}),t("div",{className:"space-y-2",children:[e(Ha,{children:h("preview")}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const a=p.videoUrl||Yu(p.embedCode)||"";if(!a)return e("div",{className:"text-center py-8 text-muted-foreground",children:h("no_content_preview")});if("file"===k)return t("video",{controls:!1!==p.controls,autoPlay:p.autoplay,poster:p.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:a}),h("unsupported")]});const r="youtube"===k?Qu(a,p.autoplay):Xu(a,p.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:p.title||h("video"),src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Va,{variant:"outline",onClick:i,children:h("cancel")}),e(Va,{onClick:()=>{p.videoUrl||p.embedCode?n(p):w.error(h("error"),{description:h("error_no_video")})},disabled:!(p.videoUrl||p.embedCode),children:h("save")})]})]})}function am({content:a,className:r="",style:s}){const n=a.videoUrl||Yu(a.embedCode)||"";if(!n)return null;const i=Zu(n),{t:o}=Ns();return e(Ka,{className:`overflow-hidden my-4 ${r}`,style:s,children:t(Xa,{className:"p-0",children:["file"===i?t("video",{controls:!1!==a.controls,autoPlay:a.autoplay,poster:a.thumbnail,className:"w-full h-auto",playsInline:!0,muted:a.autoplay,children:[e("source",{src:n}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:a.title||o("video"),src:"youtube"===i?Qu(n,a.autoplay):Xu(n,a.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),a.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:a.title})})]})})}function rm({value:r,onChange:s,onSubmit:n,onCancel:i,uploadFunction:o,deleteFunction:d,uploadOptions:u}){const{t:m}=Ns(),[h,p]=c(r||{alignment:"center",allowDownload:!1}),f=l(null),{upload:g,uploading:b}=Ku({uploadFunction:o,deleteFunction:d,defaultOptions:{...u,allowedTypes:["image/*"],maxSize:5242880}}),v=(e,t)=>{const a={...h,[e]:t};p(a),s(a)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[e(Ha,{children:m("url")}),t("div",{className:"flex gap-2",children:[e(Ba,{type:"url",placeholder:m("url_placeholder"),value:h.imageUrl||"",onChange:e=>v("imageUrl",e.target.value),className:"flex-1"}),o&&t(a,{children:[e("input",{ref:f,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await g(t),a={...h,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};p(a),s(a)}catch(a){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(Va,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:b,children:t(a,b?{children:[e(I,{className:"mr-2 h-4 w-4 animate-spin"}),m("uploading")]}:{children:[e(pe,{className:"mr-2 h-4 w-4"}),m("upload")]})})]})]}),h.imageFile&&e("p",{className:"text-xs text-muted-foreground",children:m("image.fileInfo",{name:h.imageFile,size:Math.round((h.imageSize||0)/1024)})})]}),h.imageUrl&&t("div",{className:"space-y-2",children:[e(Ha,{children:m("preview")}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===h.alignment?"justify-start":"right"===h.alignment?"justify-end":"justify-center"),children:e("img",{src:h.imageUrl,alt:h.alt||"Preview",style:{width:h.width?`${h.width}px`:"auto",height:h.height?`${h.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),t("div",{className:"space-y-2",children:[e(Ha,{htmlFor:"caption",children:m("caption")}),e(Rr,{id:"caption",placeholder:m("caption"),value:h.caption||"",onChange:e=>v("caption",e.target.value),rows:2})]}),t("div",{className:"space-y-2",children:[e(Ha,{htmlFor:"alt",children:m("alt")}),e(Ba,{id:"alt",placeholder:m("alt"),value:h.alt||"",onChange:e=>v("alt",e.target.value)})]}),t("div",{className:"space-y-2",children:[e(Ha,{children:m("alignment")}),t(Nr,{value:h.alignment||"center",onValueChange:e=>v("alignment",e),children:[e(Cr,{children:e(kr,{})}),t(Pr,{children:[e(Ir,{value:"left",children:m("left")}),e(Ir,{value:"center",children:m("center")}),e(Ir,{value:"right",children:m("right")})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[e(Ha,{htmlFor:"width",children:m("width")}),e(Ba,{id:"width",type:"number",placeholder:"px",value:h.width||"",onChange:e=>v("width",e.target.value?Number(e.target.value):void 0)})]}),t("div",{className:"space-y-2",children:[e(Ha,{htmlFor:"height",children:m("height")}),e(Ba,{id:"height",type:"number",placeholder:"px",value:h.height||"",onChange:e=>v("height",e.target.value?Number(e.target.value):void 0)})]})]}),t("div",{className:"flex items-center gap-2",children:[e("input",{id:"allowDownload",type:"checkbox",checked:h.allowDownload||!1,onChange:e=>v("allowDownload",e.target.checked),className:"h-4 w-4"}),e(Ha,{htmlFor:"allowDownload",className:"cursor-pointer",children:m("allow_download")})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(Va,{variant:"outline",onClick:i,children:m("cancel")}),e(Va,{onClick:()=>{h.imageUrl?n(h):w.error(m("error"),{description:m("error_no_image")})},disabled:!h.imageUrl,children:m("save")})]})]})}function sm({content:a,className:r="",style:s}){if(!a.imageUrl)return null;const n={left:"justify-start",center:"justify-center",right:"justify-end"}[a.alignment||"center"];return e("div",{className:`flex ${n} my-4 ${r}`,style:s,children:t("div",{className:"space-y-2 max-w-full",children:[e("img",{src:a.imageUrl,alt:a.alt||"",style:{width:a.width?`${a.width}px`:"auto",height:a.height?`${a.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),a.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:a.caption}),a.allowDownload&&a.imageUrl&&t("a",{href:a.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(fe,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function nm(e,t){return e/t}function im(e,t,a,r){const s=nm(e,t);return a&&!r?{width:a,height:Math.round(a/s)}:r&&!a?{width:Math.round(r*s),height:r}:{width:e,height:t}}function om(e){const t=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>t.includes(e))}function lm(e){try{const t=new URL(e),a=t.pathname.split("/");return a[a.length-1]||"image"}catch{const t=e.split("/");return t[t.length-1]||"image"}}function dm(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}export{an as AUTH_CONFIG,Jo as Accordion,Zo as AccordionContent,Xo as AccordionItem,Yo as AccordionTrigger,qa as ActionButton,jc as ActionMenu,Fi as ActionMenuItems,yo as Alert,No as AlertDescription,Rn as AlertDialog,Un as AlertDialogAction,Vn as AlertDialogCancel,jn as AlertDialogContent,$n as AlertDialogDescription,zn as AlertDialogFooter,Mn as AlertDialogHeader,Fn as AlertDialogOverlay,Ln as AlertDialogPortal,Dn as AlertDialogTitle,On as AlertDialogTrigger,xo as AlertTitle,Xc as AppHeader,cu as AppLayout,du as AppSidebar,el as AspectRatio,Js as AuthErrorInterceptor,En as AuthProvider,_n as AuthService,tl as Avatar,rl as AvatarFallback,al as AvatarImage,Lr as Badge,Qi as BaseForm,bd as Blockquote,sl as Breadcrumb,cl as BreadcrumbEllipsis,il as BreadcrumbItem,ol as BreadcrumbLink,nl as BreadcrumbList,ll as BreadcrumbPage,dl as BreadcrumbSeparator,Yi as BulkActionBar,Va as Button,ml as ButtonGroup,rn as CRUD_CONFIG,Fl as Calendar,wo as CallbackPage,Ka as Card,Xa as CardContent,Ja as CardDescription,Ya as CardFooter,Ga as CardHeader,Zn as CardSkeleton,Qa as CardTitle,zc as Cards,vu as ChatbotPage,Ar as Checkbox,qo as Collapsible,Wo as CollapsibleContent,Bo as CollapsibleTrigger,Ui as ColorPicker,Ss as Combobox,Vr as Command,qr as CommandDialog,Hr as CommandEmpty,Kr as CommandGroup,Br as CommandInput,Qr as CommandItem,Wr as CommandList,Gr as CommandSeparator,Jr as CommandShortcut,xi as ContextMenu,Ti as ContextMenuCheckboxItem,Ei as ContextMenuContent,wi as ContextMenuGroup,Ii as ContextMenuItem,Ri as ContextMenuLabel,ki as ContextMenuPortal,Si as ContextMenuRadioGroup,Ai as ContextMenuRadioItem,Oi as ContextMenuSeparator,Li as ContextMenuShortcut,Ci as ContextMenuSub,Pi as ContextMenuSubContent,_i as ContextMenuSubTrigger,Ni as ContextMenuTrigger,Qo as CoreProviders,Lc as CrudCards,so as CrudPageInternal,Xi as CrudPagination,Mc as CrudPrimitiveFilterBar,Ji as CrudPrimitivePagination,Fc as CrudPrimitiveTable,zi as CrudTable,jl as DataList,Ml as DatePicker,qn as DeleteConfirmationDialog,er as Dialog,or as DialogBody,rr as DialogClose,nr as DialogContent,cr as DialogDescription,lr as DialogFooter,ir as DialogHeader,sr as DialogOverlay,ar as DialogPortal,dr as DialogTitle,tr as DialogTrigger,zl as Drawer,Ul as DrawerClose,ql as DrawerContent,Kl as DrawerDescription,Wl as DrawerFooter,Bl as DrawerHeader,Vl as DrawerOverlay,$l as DrawerPortal,Hl as DrawerTitle,Dl as DrawerTrigger,ni as DropdownMenu,fi as DropdownMenuCheckboxItem,hi as DropdownMenuContent,oi as DropdownMenuGroup,pi as DropdownMenuItem,bi as DropdownMenuLabel,li as DropdownMenuPortal,ci as DropdownMenuRadioGroup,gi as DropdownMenuRadioItem,vi as DropdownMenuSeparator,yi as DropdownMenuShortcut,di as DropdownMenuSub,mi as DropdownMenuSubContent,ui as DropdownMenuSubTrigger,ii as DropdownMenuTrigger,pu as EmailService,si as EmptyState,Ss as EntitySelect,Go as ErrorBoundary,ro as FilterBar,ur as Form,vr as FormControl,yr as FormDescription,hr as FormField,gr as FormItem,br as FormLabel,xr as FormMessage,ei as FormSkeleton,Xl as Grid,od as H1,ld as H2,dd as H3,cd as H4,ti as HeaderSkeleton,ws as I18nextProvider,Wi as IconPicker,rm as ImageEditor,sm as ImageRenderer,gd as InlineCode,Ba as Input,Yl as InputGroup,ed as InputGroupAddon,ad as InputGroupButton,rd as InputGroupInput,sd as InputGroupTextarea,nd as Kbd,cn as LOGO_CONFIG,Ha as Label,hd as Large,md as Lead,ju as LeaderRow,qu as LeadershipDialog,Vu as LeadershipForm,Hu as LeadershipPage,vd as List,Mr as LoadingState,$o as LocaleProvider,Bc as LocaleSelector,ko as LoginPage,un as MESSAGES,yu as ManageAccessModal,bu as MarkdownMessage,Ss as MultiSelect,fd as Muted,id as NativeSelect,Kc as NavigationProvider,ud as P,yd as PageBreadcrumb,So as PageMetadataProvider,Nd as Pagination,wd as PaginationContent,Pd as PaginationEllipsis,kd as PaginationItem,Cd as PaginationLink,_d as PaginationNext,Sd as PaginationPrevious,xu as PlaceCard,Nu as PlacesList,Dr as Popover,Ur as PopoverContent,$r as PopoverTrigger,uo as Progress,bo as ProtectedRoute,ln as QUALIEX_CONFIG,on as QUERY_KEYS,bn as QualiexEnrichmentService,Ys as QualiexErrorInterceptor,Gi as QualiexUserField,Ed as RadioGroup,Id as RadioGroupItem,sn as SEARCH_CONFIG,Vi as ScrollArea,qi as ScrollBar,Ad as Searchbar,Nr as Select,Pr as SelectContent,wr as SelectGroup,Ir as SelectItem,Er as SelectLabel,_r as SelectScrollDownButton,Sr as SelectScrollUpButton,Ss as SelectSearch,Tr as SelectSeparator,Cr as SelectTrigger,kr as SelectValue,Za as Separator,Rd as Sheet,$d as SheetBody,Ld as SheetClose,zd as SheetContent,qd as SheetDescription,Ud as SheetFooter,Dd as SheetHeader,jd as SheetOverlay,Fd as SheetPortal,Vd as SheetTitle,Od as SheetTrigger,Yd as Sidebar,ic as SidebarContent,sc as SidebarFooter,oc as SidebarGroup,dc as SidebarGroupAction,cc as SidebarGroupContent,lc as SidebarGroupLabel,ou as SidebarHeader,ac as SidebarInput,tc as SidebarInset,uc as SidebarMenu,fc as SidebarMenuAction,gc as SidebarMenuBadge,pc as SidebarMenuButton,mc as SidebarMenuItem,bc as SidebarMenuSkeleton,vc as SidebarMenuSub,xc as SidebarMenuSubButton,yc as SidebarMenuSubItem,Xd as SidebarProvider,ec as SidebarRail,nc as SidebarSeparator,ai as SidebarSkeleton,Zd as SidebarTrigger,Xr as Skeleton,Nc as Slider,pd as Small,zr as SonnerToaster,jr as Spinner,ao as Stack,Gl as StatusSelect,Hi as Switch,Ec as TabPageContent,Pc as TabPageHeader,_c as TabPageLayout,Bn as Table,Hn as TableBody,Xn as TableCaption,Jn as TableCell,Kn as TableFooter,Qn as TableHead,Wn as TableHeader,Gn as TableRow,ji as TableRowActions,Yn as TableSkeleton,wc as Tabs,Sc as TabsContent,kc as TabsList,Cc as TabsTrigger,Rr as Textarea,zr as Toaster,Tc as Toggle,Rc as ToggleGroup,Oc as ToggleGroupItem,Fs as TokenManager,Ps as TokenService,Wd as Tooltip,Kd as TooltipContent,Bd as TooltipProvider,Hd as TooltipTrigger,Vo as TranslationLoader,tm as VideoEditor,am as VideoRenderer,ho as WizardBreadcrumb,fo as WizardButtons,go as WizardForm,po as WizardProgressBar,mo as WizardStepper,su as assets,Or as badgeVariants,_u as buildHierarchy,ul as buttonGroupVariants,Ua as buttonVariants,nm as calculateAspectRatio,Fa as cn,no as createCrudPage,$c as createCrudRoutingConfig,Dc as createRoutingHandlers,xn as createService,io as createSimpleSaveHandler,An as createSimpleService,Da as debounce,hn as deriveEmailField,mn as deriveNameField,pn as deriveUsernameField,Zu as detectVideoProvider,fu as emailService,zs as errorService,lm as extractImageFileName,Ju as extractVimeoId,Gu as extractYouTubeId,Su as filterAndPromoteOrphans,Pu as flattenTree,za as formatCurrency,mu as formatDate,Ma as formatDatetime,dm as formatFileSize,oo as generateCrudConfig,dn as getQualiexConfig,Ws as getSupabaseClient,La as handleExternalLink,Oa as i18n,Zl as inputGroupAddonVariants,td as inputGroupButtonVariants,nn as isDevEnvironment,om as isImageUrl,nu as logoSrc,em as normalizeVideoUrl,Xu as normalizeVimeoUrl,Qu as normalizeYouTubeUrl,Yu as parseIframeSrc,Cu as placeService,tn as qualiexApi,im as resizeKeepingAspect,fn as resolveFieldMappings,Td as searchbarVariants,Eo as setupQualiexCore,$a as slugify,iu as smallLogoSrc,Ic as toggleVariants,Lo as translationService,ja as trimTextFields,Zc as useActiveModules,In as useAuth,Di as useBaseForm,Iu as useCreateLeaderMutation,Au as useCreateMultipleLeadersMutation,Tu as useCreateSingleLeaderMutation,Tn as useCrud,Jc as useDebounce,pr as useFormField,hu as useI18nFormatters,Eu as useLeadershipApi,Uo as useLocale,Ku as useMediaUpload,Gc as useNavigation,gu as useOpenAIChat,Po as usePageMetadata,_o as usePageMetadataContext,Qc as usePageTitle,Yc as usePermissionQuery,Ki as useQualiexUsers,Ou as useRemoveLeaderMutation,xd as useRouteBreadcrumbs,Jd as useSidebar,lu as useSidebarResize,Lu as useSyncSubordinatesMutation,Ns as useTranslation,Ru as useUpdateLeaderMutation};
10
+ */var Bn=(Vn||(Vn=1,"production"===process.env.NODE_ENV?zn.exports=function(){if(jn)return $n;jn=1;var e=n,t="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},a=e.useState,r=e.useEffect,s=e.useLayoutEffect,i=e.useDebugValue;function o(e){var a=e.getSnapshot;e=e.value;try{var r=a();return!t(e,r)}catch(n){return!0}}var l="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var n=t(),l=a({inst:{value:n,getSnapshot:t}}),c=l[0].inst,d=l[1];return s(function(){c.value=n,c.getSnapshot=t,o(c)&&d({inst:c})},[e,n,t]),r(function(){return o(c)&&d({inst:c}),e(function(){o(c)&&d({inst:c})})},[e]),i(n),n};return $n.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:l,$n}():zn.exports=(Un||(Un=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!a(e,r)}catch(n){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var t=n,a="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useState,s=t.useEffect,i=t.useLayoutEffect,o=t.useDebugValue,l=!1,c=!1,d="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(n,d){l||void 0===t.startTransition||(l=!0);var u=d();if(!c){var m=d();a(u,m)||(c=!0)}var h=(m=r({inst:{value:u,getSnapshot:d}}))[0].inst,p=m[1];return i(function(){h.value=u,h.getSnapshot=d,e(h)&&p({inst:h})},[n,u,d]),s(function(){return e(h)&&p({inst:h}),n(function(){e(h)&&p({inst:h})})},[n]),o(u),u};Wn.useSyncExternalStore=void 0!==t.useSyncExternalStore?t.useSyncExternalStore:d,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Wn)),zn.exports);const Hn={t:(e,t)=>{return Rn(t)?t:"object"==typeof(a=t)&&null!==a&&Rn(t.defaultValue)?t.defaultValue:Array.isArray(e)?e[e.length-1]:e;var a},ready:!1},qn=()=>()=>{},Kn=(e,t={})=>{const{i18n:a}=t,{i18n:r,defaultNS:n}=i(Dn)||{},s=a||r||On;s&&!s.reportNamespaces&&(s.reportNamespaces=new Fn),s||Sn(s,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const m=o(()=>({...Mn,...s?.options?.react,...t}),[s,t]),{useSuspense:h,keyPrefix:p}=m,f=e||n||s?.options?.defaultNS,g=Rn(f)?[f]:f||["translation"],v=o(()=>g,g);s?.reportNamespaces?.addUsedNamespaces?.(v);const b=l(0),y=c(e=>{if(!s)return qn;const{bindI18n:t,bindI18nStore:a}=m,r=()=>{b.current+=1,e()};return t&&s.on(t,r),a&&s.store.on(a,r),()=>{t&&t.split(" ").forEach(e=>s.off(e,r)),a&&a.split(" ").forEach(e=>s.store.off(e,r))}},[s,m]),w=l(),x=c(()=>{if(!s)return Hn;const e=!(!s.isInitialized&&!s.initializedStoreOnce)&&v.every(e=>((e,t,a={})=>t.languages&&t.languages.length?t.hasLoadedNamespace(e,{lng:a.lng,precheck:(t,r)=>{if(a.bindI18n&&a.bindI18n.indexOf("languageChanging")>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!r(t.isLanguageChangingTo,e))return!1}}):(Sn(t,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:t.languages}),!0))(e,s,m)),a=t.lng||s.language,r=b.current,n=w.current;if(n&&n.ready===e&&n.lng===a&&n.keyPrefix===p&&n.revision===r)return n;const i={t:s.getFixedT(a,"fallback"===m.nsMode?v:v[0],p),ready:e,lng:a,keyPrefix:p,revision:r};return w.current=i,i},[s,v,p,m,t.lng]),[N,k]=d(0),{t:C,ready:S}=Bn.useSyncExternalStore(y,x,x);u(()=>{if(s&&!S&&!h){const e=()=>k(e=>e+1);t.lng?Pn(s,t.lng,v,e):_n(s,v,e)}},[s,t.lng,v,S,h,N]);const E=s||{},_=l(null),P=l(),R=e=>{const t=Object.getOwnPropertyDescriptors(e);t.__original&&delete t.__original;const a=Object.create(Object.getPrototypeOf(e),t);if(!Object.prototype.hasOwnProperty.call(a,"__original"))try{Object.defineProperty(a,"__original",{value:e,writable:!1,enumerable:!1,configurable:!1})}catch(r){}return a},T=o(()=>{const e=E,t=e?.language;let a=e;e&&(_.current&&_.current.__original===e?P.current!==t?(a=R(e),_.current=a,P.current=t):a=_.current:(a=R(e),_.current=a,P.current=t));const r=[C,a,S];return r.t=C,r.i18n=a,r.ready=S,r},[C,E,S,E.resolvedLanguage,E.language,E.languages]);if(s&&h&&!S)throw new Promise(e=>{const a=()=>e();t.lng?Pn(s,t.lng,v,a):_n(s,v,a)});return T};function Gn({i18n:e,defaultNS:t,children:a}){const r=o(()=>({i18n:e,defaultNS:t}),[e,t]);return m(Dn.Provider,{value:r},a)}const Xn=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Jn({multiple:a,options:r,value:n,onChange:s,getOptionValue:i,getOptionLabel:l,placeholder:c,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f,required:g,className:v,sortOptions:b,maxDisplayedBadges:y,popoverContainer:w,onOpen:x,onClose:N}){const{t:k}=Kn(),[C,S]=d(!1),[E,R]=d(""),A=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),I=o(()=>{if(!w)return;let e=w,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),r=a.overflowY||a.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,t++}}catch{}return e??void 0},[w]),M=o(()=>{const e=r.map(e=>({original:e,value:i(e),label:l(e)}));return b?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[r,i,l,b]),O=o(()=>{if(!E)return M;const e=Xn(E);return M.filter(t=>Xn(t.label).includes(e))},[M,E]),L=o(()=>M.filter(e=>A.includes(e.value)),[M,A]),D=(e,t)=>{t.preventDefault(),t.stopPropagation(),s&&s(a?A.filter(t=>t!==e):"")},F=y?L.slice(0,y):L,j=y&&L.length>y?L.length-y:0;return t("div",{className:sr("space-y-2",v),children:[u&&t(gr,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t(un,{open:C,onOpenChange:e=>{S(e),e?x?.():(R(""),N?.())},modal:!1,children:[e(mn,{asChild:!0,children:t(mr,{variant:"outline",role:"combobox","aria-expanded":C,disabled:f,className:sr("w-full justify-between min-h-10 h-auto",0===L.length&&"text-muted-foreground"),children:[0===L.length?t("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),c]}):a?t("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[F.map(a=>t(sn,{variant:"secondary",className:"gap-1 pr-1",children:[a.label,e("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:e=>{"Enter"===e.key&&D(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>D(a.value,e),children:e(_,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),j>0&&t(sn,{variant:"outline",className:"gap-1",children:["+",j]})]}):t("span",{className:"flex items-center gap-2",children:[m&&e(m,{className:"h-4 w-4"}),L[0]?.label]}),e(P,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e(hn,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:I,collisionBoundary:I,children:t(pn,{children:[e(gn,{placeholder:p,value:E,onChange:e=>R(e.target.value)}),e(vn,{children:0===r.length?e(bn,{children:h}):0===O.length?e(bn,{children:k("no_results")}):e(yn,{children:O.map(r=>t(xn,{value:r.value,onSelect:()=>(e=>{if(s)if(a){const t=A.includes(e)?A.filter(t=>t!==e):[...A,e];s(t)}else s(e),S(!1)})(r.value),className:"cursor-pointer",children:[e(T,{className:sr("mr-2 h-4 w-4",A.includes(r.value)?"opacity-100":"opacity-0")}),r.label]},r.value))})})]})})]})]})}function Qn({multiple:a=!1,options:r,items:n,value:s,onChange:i,onValueChange:o,getOptionValue:l=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:h,searchPlaceholder:p,disabled:f=!1,required:g=!1,isLoading:v=!1,error:b,className:y,sortOptions:w=!0,maxDisplayedBadges:x,popoverContainer:N,onOpen:k,onClose:C}){const{t:S}=Kn(),E=n||r||[],_=o||i,P=d||S("select_placeholder"),R=h||S("no_results"),T=p||S("search_placeholder");if(v)return t("div",{className:sr("space-y-2",y),children:[u&&t(gr,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(kn,{className:"h-10 w-full"})]});const A="string"==typeof b?b:b instanceof Error?b.message:b?"Erro ao carregar dados":void 0;return A?t("div",{className:sr("space-y-2",y),children:[u&&t(gr,{children:[u,g&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:A})]})]}):e(Jn,{multiple:a,options:E,value:s||(a?[]:""),onChange:_,getOptionValue:l,getOptionLabel:c,placeholder:P,label:u,icon:m,emptyMessage:R,searchPlaceholder:T,disabled:f,required:g,className:y,sortOptions:w,maxDisplayedBadges:x,popoverContainer:N,onOpen:k,onClose:C})}var Yn=Object.defineProperty;class Zn{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const a=(4-t.length%4)%4;return t+="=".repeat(a),t}static parseJwtPayload(e){try{const n=e.split(".");if(3!==n.length)return null;const s=n[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),t=atob(e),a=new Uint8Array(t.length);for(let n=0;n<t.length;n++)a[n]=t.charCodeAt(n);const r=new TextDecoder("utf-8").decode(a);return JSON.parse(r)}catch(t){try{const e=this.normalizeBase64Url(s),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(a){try{const e=this.normalizeBase64Url(s),t=atob(e);return JSON.parse(t)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,t){const a=[],r=[];try{t.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(t),s=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:r}}let i=!0;if(!s){const e="Access token decode falhou - será tentado novamente nas chamadas de API";a.push(e),i=!1}const o=Math.floor(Date.now()/1e3);if(s?.exp&&s.exp<o){const e="Access token expirado - pode precisar de refresh";a.push(e),i=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:a,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:a,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:r}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}((e,t,a)=>{t in e?Yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a})(Zn,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const es="qualiex_access_token",ts="qualiex_id_token",as="supabase_token",rs="oauth_state",ns="oauth_nonce",ss="selected_alias",is="manual_logout",os={setAccessToken:e=>localStorage.setItem(es,e),getAccessToken:()=>localStorage.getItem(es),setIdToken:e=>localStorage.setItem(ts,e),getIdToken:()=>localStorage.getItem(ts),getSupabaseToken:()=>localStorage.getItem(as),setOAuthState:e=>sessionStorage.setItem(rs,e),getOAuthState:()=>sessionStorage.getItem(rs),clearOAuthState:()=>sessionStorage.removeItem(rs),setOAuthNonce:e=>sessionStorage.setItem(ns,e),getOAuthNonce:()=>sessionStorage.getItem(ns),clearOAuthNonce:()=>sessionStorage.removeItem(ns),setSelectedAlias:e=>localStorage.setItem(ss,e),getSelectedAlias:()=>localStorage.getItem(ss),clearSelectedAlias:()=>localStorage.removeItem(ss),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!os.getAccessToken()||!os.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(as,e),os._clearValidationCache()},areAllTokensValid:()=>{const e=os.getAccessToken(),t=os.getIdToken();if(!e||!t)return!1;try{const a=Zn.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=os.getAccessToken(),a=os.getIdToken(),r=os.getSupabaseToken();return t&&os.isTokenExpired(t)&&(localStorage.removeItem(es),e=!0),a&&os.isTokenExpired(a)&&(localStorage.removeItem(ts),e=!0),r&&os.isTokenExpired(r)&&(localStorage.removeItem(as),e=!0),e},clearAll:()=>{localStorage.removeItem(es),localStorage.removeItem(ts),localStorage.removeItem(as),localStorage.removeItem(ss),localStorage.removeItem(is),sessionStorage.removeItem(rs),sessionStorage.removeItem(ns)},setManualLogout:()=>localStorage.setItem(is,"true"),isManualLogout:()=>"true"===localStorage.getItem(is),clearManualLogout:()=>localStorage.removeItem(is),isTokenExpired:e=>{try{return Zn.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{os._validationCache.isValid=!1,os._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=os.getSupabaseToken();if(!e)return!1;if(os.isTokenExpired(e))return os._clearValidationCache(),os._handleExpiredToken(),!1;const t=Date.now();return t-os._validationCache.timestamp<os._validationCache.cacheValidityMs?os._validationCache.isValid:(os._validationCache.isValid=!0,os._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>os.isSupabaseTokenValid()?os.getSupabaseToken():null,_handleExpiredToken:()=>{os.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!os.isSupabaseTokenValid())return null;const e=os.getSupabaseToken();if(!e)return null;try{const t=Zn.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,r=t.place_id||null,n=t.place_name||null;let s=t.company_id;if(!s&&a)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=t[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===a){s=e[7];break}}}return{alias:a,companyId:s,placeId:r,placeName:n,payload:t}}catch(t){return os._handleExpiredToken(),null}},getCompanyId:e=>{const t=os.getAccessToken();if(t)try{const a=Zn.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const t=r.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(n){}const a=os.extractTokenData();if(a?.companyId)return a.companyId;const r=os.getIdToken();if(r)try{const t=Zn.parseJwtPayload(r);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const t=r.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(n){}return null},getCurrentCompanyId:()=>{const e=os.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=os.getIdToken();if(!e)return[];try{const t=Zn.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=t[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&a.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return a}catch{return[]}}};var ls=Object.defineProperty,cs=(e,t,a)=>((e,t,a)=>t in e?ls(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const ds=new class{constructor(){cs(this,"errors",[]),cs(this,"toastCount",0),cs(this,"lastToastTime",0)}handleError(e,t=!0){const a="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:a,timestamp:Date.now(),count:1}),t&&this.shouldShowToast()){const e=this.getErrorTitle(a);C.error(e,{description:a})}}getErrorTitle(e){const t=e.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?"Sessão Expirada":t.includes("token")||t.includes("autenticação")?"Erro de Autenticação":t.includes("api")||t.includes("network")?"Erro de Conexão":"Erro"}success(e,t){C.success(e,{description:t})}shouldShowToast(){const e=Date.now();return e-this.lastToastTime>6e4&&(this.toastCount=0),this.toastCount<3&&(this.toastCount++,this.lastToastTime=e,!0)}getErrors(){return this.errors.slice(-50)}clearErrors(){this.errors=[]}};var us=Object.defineProperty,ms=(e,t,a)=>((e,t,a)=>t in e?us(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const hs=import.meta.env.VITE_SUPABASE_URL,ps=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,fs=class e{constructor(){ms(this,"client"),ms(this,"currentToken",null),ms(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:ps};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return _t(hs,ps,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:t,fetch:async(e,t)=>("string"==typeof e?e:e.url).includes("/auth/v1/user")?new Response(JSON.stringify({error:"blocked"}),{status:401,headers:{"Content-Type":"application/json"}}):fetch(e,t)}})}static getInstance(){return e.instance||(e.instance=new e),e.instance}getClient(){const e=os.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{const t=JSON.parse(atob(e.split(".")[1])),a=Math.floor(Date.now()/1e3);return t.exp>a}catch(t){return ds.handleError(t instanceof Error?t:"❌ Supabase - Error validating token",!1),!1}}};ms(fs,"instance");let gs=fs;function vs(){return gs.getInstance().getClient()}class bs{static async generateToken(e,t,a,r=!1){try{if(!r){const e=os.getSupabaseToken();if(e&&os.isSupabaseTokenValid())return e}const n=vs(),{data:s,error:i}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(a?.(),null):s?.access_token&&s.access_token?(os.setSupabaseToken(s.access_token),s.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&a?.(),null}}}var ys=Object.defineProperty,ws=(e,t,a)=>((e,t,a)=>t in e?ys(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);class xs{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=os.getAccessToken(),t=os.getSelectedAlias();if(!e||!t)return null;const a=await bs.generateToken(e,t,this.onLogoutCallback||void 0,!1);return a?(os.setSupabaseToken(a),a):null}catch(e){return null}finally{this.isRegenerating=!1}}}ws(xs,"isRegenerating",!1),ws(xs,"onLogoutCallback",null);class Ns{static handleError(e){if(!e)return!1;const t=e.message||e.toString();return!!this.isAuthenticationError(e,t)&&(os.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,t){if(401===e.status||401===e.statusCode)return!0;const a=t.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>a.includes(e))}static async wrapAsync(e){try{return await e}catch(t){if(!this.handleError(t))throw t;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}var ks=Object.defineProperty;class Cs{static async handleApiError(e){if(!e||this.isRetrying)return!1;const t=e.status||e.statusCode,a=e.message||e.toString();if(401===t||a.includes("401")||a.includes("Unauthorized")){this.isRetrying=!0;try{return await xs.attemptRegeneration()?(this.isRetrying=!1,!0):(Ns.handleError(e),this.isRetrying=!1,!1)}catch(r){return Ns.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=os.getAccessToken();return e?os.isTokenExpired(e)?{valid:!1,message:"Sua sessão expirou. Você será redirecionado para fazer login."}:{valid:!0}:{valid:!1,message:"Token OAuth não encontrado. Faça login novamente."}}}((e,t,a)=>{((e,t,a)=>{t in e?ks(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a})(e,t+"",a)})(Cs,"isRetrying",!1);var Ss=Object.defineProperty,Es=(e,t,a)=>((e,t,a)=>t in e?Ss(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const _s=new class{constructor(){Es(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const r=Cs.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=os.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const s=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{s.searchParams.append(e,t)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,t){try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let r=a;if(a.data)r=a.data;else{if(!Array.isArray(a))return ds.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=a}if(!Array.isArray(r))return ds.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(a){if(await Cs.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let r=a;if(a.data)r=a.data;else{if(!Array.isArray(a))return ds.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=a}return Array.isArray(r)?r.map(this.mapToQualiexUser):(ds.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return ds.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}const n=a instanceof Error?a.message:"Erro ao buscar usuários da API Qualiex";return ds.handleError(n,!0),[]}}async fetchUserById(e,t,a){try{return(await this.fetchUsers(t,a)).find(t=>t.userId===e)||null}catch(r){return ds.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,t){const a=await this.fetchUsers(e,t),r=new Map;return a.forEach(e=>{r.set(e.userId,e)}),r}async getUsers(e){const t=os.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId):[]}async getAllUsers(e){return this.getUsers(e)}},Ps={oauth:{authUrl:import.meta.env.VITE_OAUTH_AUTH_URL,clientId:import.meta.env.VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},Rs={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Ts={debounceDelay:500},As=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||import.meta.env.DEV},Is={crud:e=>[e],list:(e,t)=>[e,"list",t],detail:(e,t)=>[e,"detail",t]},Ms={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Os=()=>Ms,Ls={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Ds={success:{created:e=>`${e} criado com sucesso`,updated:e=>`${e} atualizado com sucesso`,deleted:e=>`${e} removido com sucesso`},error:{create:e=>`Erro ao criar ${e}`,update:e=>`Erro ao atualizar ${e}`,delete:e=>`Erro ao remover ${e}`,load:e=>`Erro ao carregar ${e}`}};function Fs(e,t){const a=Os(),r=t||a.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function js(e,t){const a=Os(),r=t||a.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function zs(e,t){const a=Os(),r=t||a.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function $s(e,t){return t&&t.length>0?t.map(e=>({idField:e.idField,nameField:e.nameField||Fs(e.idField),emailField:e.emailField||js(e.idField),usernameField:e.usernameField||zs(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Fs(e),emailField:js(e),usernameField:zs(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Us=new Map;class Vs{static async fetchQualiexUsers(e,t){const a=`${t}_${e}`,r=Us.get(a);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await _s.fetchUsers(e,t);return Us.set(a,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,t){const a=new Set;for(const r of e)for(const e of t){const t=r[e.idField];t&&"string"==typeof t&&""!==t.trim()&&a.add(t)}return a}static indexUsers(e){const t=new Map;for(const a of e)a.id&&t.set(a.id,a),a.userId&&t.set(a.userId,a);return t}static enrichEntity(e,t,a){const r={...e};for(const n of t){const t=e[n.idField];if(!t)continue;const s=a.get(t);if(s){if(n.nameField){r[n.nameField]||(r[n.nameField]=s.userName||s.displayName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=s.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=s.userName||null)}}}return r}static async enrichWithUserData(e,t){if(!Array.isArray(e)||0===e.length)return e;try{if(!os.areAllTokensValid())return e;const a=os.extractTokenData();if(!a)return e;const{alias:r,companyId:n}=a;if(!r||!n)return e;const s=$s(t.userIdFields,t.userFieldsMapping);if(0===this.extractUserIds(e,s).size)return e;const i=await this.fetchQualiexUsers(r,n),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,s,o))}catch(a){return ds.handleError(a instanceof Error?a:new Error(`[QualiexEnrichment.${t.entityName}] Erro crítico`),!1),e}}static async enrichWithResponsibleNames(e,t){return this.enrichWithUserData(e,{entityName:t.entityName,userIdFields:["id_user"],userFieldsMapping:[{idField:"id_user",nameField:"responsible_name"}]})}}const Ws=["responsible_name"],Bs=e=>Ws.includes(e);function Hs(e,t,a){const r="string"==typeof e?{tableName:e,searchFields:t||[],schemaName:a||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:s,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:c=!1}=r,d=()=>{if(!os.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return vs().schema(o).from(n)},u=(e,t,a,r)=>{let n=d().select(i||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,t])=>{void 0!==t&&""!==t&&(Array.isArray(t)?n=n.in(e,t):"object"==typeof t&&t&&"operator"in t?"not_null"===t.operator?n=n.not(e,"is",null):"is_null"===t.operator&&(n=n.is(e,null)):null!==t&&(n=n.eq(e,t)))}),n=((e,t)=>{if(t&&s.length>0){const a=s.map(e=>`${e}.ilike.%${t}%`).join(",");return e.or(a)}return e})(n,e);const o=t.includes(".");return o||Bs(t)||(n=n.order(t,{ascending:"asc"===a})),{query:n,isForeignKey:o}},m=async(e,t,a,n,s)=>{const i=$s(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===t||e.emailField===t||e.usernameField===t),o=t.includes(".");if(Bs(t)||o||i){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},i=await this.getAll(e);if(!i?.data?.length)return i;const c=await Vs.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let d;d=o?c.sort((e,r)=>{const n=t.split(".").reduce((e,t)=>e?.[t],e)||"",s=t.split(".").reduce((e,t)=>e?.[t],r)||"",i=String(n).localeCompare(String(s),"pt-BR");return"asc"===a?i:-i}):((e,t,a)=>[...e].sort((e,r)=>{const n=e[t]||"",s=r[t]||"",i=n.localeCompare(s,"pt-BR",{sensitivity:"base"});return"asc"===a?i:-i}))(c,t,a);const u=((e,t=1,a=25)=>{const r=(t-1)*a,n=r+a,s=e.slice(r,n);return{data:s,pagination:{currentPage:t,totalPages:Math.ceil(e.length/a),totalItems:s.length,totalCount:e.length,itemsPerPage:a,hasNextPage:n<e.length,hasPreviousPage:t>1}}})(d,n,s);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalCount,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await Vs.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})};return{async getAll(e={}){const{search:t,sortField:a,sortDirection:s,page:i,limit:o,additionalFilters:d}=(e=>{const{search:t="",sortField:a="updated_at",sortDirection:r="desc",page:n=1,limit:s=25,...i}=e;return{search:t,sortField:a,sortDirection:r,page:n,limit:s,additionalFilters:i}})(e),{query:h}=u(t,a,s,d),p=((e,t,a)=>{const r=(t-1)*a,n=r+a-1;return e.range(r,n)})(h,i,o),{data:f,error:g,count:v}=await p;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let b=((e,t,a,r)=>{const n=Math.ceil((t||0)/r);return{data:e,currentPage:a,totalPages:n,totalItems:t||0,itemsPerPage:r,hasNextPage:a<n,hasPreviousPage:a>1}})(f||[],v,i,o);if((e=>{if(!c||!l||0===e.length)return!1;const t=$s(r.userIdFields,r.userFieldsMapping);return e.some(e=>t.some(t=>e[t.idField]))})(b.data)){const e=await m(b.data,a,s,i,o);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:t,error:a}=await d().select(i||"*").eq("id",e).maybeSingle();if(a)throw new Error(`Error fetching ${n}: ${a.message}`);return t},async create(e){const t=ir(e),a=Object.entries(t).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),{data:r,error:s}=await d().insert(a).select().single();if(s)throw new Error(`Error creating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,t){const a={...ir(t),updated_at:(new Date).toISOString()},{data:r,error:s}=await d().update(a).eq("id",e).select().single();if(s)throw new Error(`Error updating ${n}: ${s.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},async delete(e){const t={is_removed:!0,updated_at:(new Date).toISOString()},{error:a}=await d().update(t).eq("id",e);if(a)throw new Error(`Error soft deleting ${n}: ${a.message}`)}}}const qs=()=>{os.clearManualLogout()},Ks=e=>e?.placeId||null,Gs=e=>e?.placeName||null,Xs=e=>({placeId:Ks(e),placeName:Gs(e)}),Js=class{static async initialize(){try{if(!os.hasAllTokens()||!os.areAllTokensValid())return os.clearExpiredTokens(),{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};const t=os.getAccessToken(),a=os.getIdToken();qs();const r=this.extractUserFromIdToken(a),n=this.extractCompaniesFromIdToken(a),s=this.extractAliasFromAccessToken(t),i=os.extractTokenData(),o=i?.alias;let l=null;if(o&&n.some(e=>e.alias===o))l=o;else{const e=os.getSelectedAlias(),t=e&&n.some(t=>t.alias===e);l=t?e:s||n[0]?.alias||null}!os.isSupabaseTokenValid()&&l&&await xs.attemptRegeneration();let c=null;if(l){const e=os.getCompanyId(l),t=n.find(e=>e.alias===l);t&&(c={id:e||t.id,name:t.name,alias:t.alias})}let d=null,u=null;if(r?.id&&l){const t=os.getCompanyId(l);if(t)try{const e=(await _s.fetchActiveUsersMap(l,t)).get(r.id);if(e){const t=Xs(e);d=t.placeId,u=t.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:n,selectedUnit:c,userId:r?.id||null,userAlias:r?.id||null,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}}catch(e){return{isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null}}}static async loginDev(){try{const e=vs(),{data:t,error:a}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(a)return!1;if(!t?.access_token||!t?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=os.generateOAuthState();os.setOAuthState(e);const t=os.generateOAuthNonce();os.setOAuthNonce(t);const a=`${window.location.origin}/callback`,r=new URL(Ps.oauth.authUrl);r.searchParams.set("client_id",Ps.oauth.clientId),r.searchParams.set("response_type",Ps.oauth.responseType),r.searchParams.set("scope",Ps.oauth.scope),r.searchParams.set("redirect_uri",a),r.searchParams.set("state",e),r.searchParams.set("nonce",t),r.searchParams.set("response_mode","fragment"),As(),window.location.href=r.toString()}static async processCallback(){try{if(os.hasAllTokens()){if(!os.getValidSupabaseToken()){os.getAccessToken();await xs.attemptRegeneration()}return!0}const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),t=new URLSearchParams(window.location.search),a=a=>e.get(a)||t.get(a),r=a("access_token"),n=a("id_token"),s=a("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(!r||!n)throw new Error("Tokens não encontrados na URL de callback");os.setAccessToken(r),os.setIdToken(n),qs();const i=this.extractAliasFromAccessToken(r);if(i)os.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(n);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");os.setSelectedAlias(e[0].alias)}if(!await xs.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return os.clearOAuthState(),os.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){os.setManualLogout(),os.clearAll(),window.location.href="/login"}static decodeToken(e){return Zn.parseJwtPayload(e)}static extractUserFromIdToken(e){const t=this.decodeToken(e);return t?{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier}:null}static extractCompaniesFromIdToken(e){const t=this.decodeToken(e);if(!t)return[];const a=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const r=t[e].split(";");if(r.length>=4)a.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=t[e].split("|");r&&n&&a.push({id:"",alias:r.trim(),name:n.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}};xs.setLogoutCallback(()=>{Js.logout()});let Qs=Js;const Ys=s(void 0),Zs=({children:t})=>{const[a,r]=d({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null});let n=null;try{n=Pt()}catch{}const[s,i]=d(!1),[l,m]=d(0),h=c(e=>{r(t=>({...t,...e}))},[]),p=c(e=>{r(t=>({...t,isLoading:e}))},[]),f=c(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=c(async e=>{try{p(!0);const r=os.getAccessToken();if(!r)return;const s=await bs.generateToken(r,e.alias,void 0,!0);if(!s)return;os.setSupabaseToken(s),os.setSelectedAlias(e.alias);const i=os.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||os.getCompanyId(e.alias),c={id:l||e.id,name:e.name,alias:o};let d=null,u=null;if(a.user?.id&&o&&l)try{const e=(await _s.fetchActiveUsersMap(o,l)).get(a.user.id);if(e){const t=Xs(e);d=t.placeId,u=t.placeName}}catch(t){}h({alias:o,selectedUnit:c,placeId:d,placeName:u,activePlaceId:d,activePlaceName:u}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(t){}finally{p(!1)}},[h,n,p,a.user]),v=c(async()=>await Qs.processCallback(),[]),b=c(async()=>{Qs.logout(),f(),n&&await n.clear()},[f,n]),y=c(e=>{i(e)},[]),w=c(()=>{m(e=>e+1)},[]),x=c(()=>{m(e=>e+1)},[]);u(()=>{if(!a.isAuthenticated)return;let e=!0;const t=setInterval(()=>{e&&(os.areAllTokensValid()||e&&b())},6e5);return()=>{e=!1,clearInterval(t)}},[a.isAuthenticated,b]),u(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const t=await Qs.initialize();if(!e)return;t&&t.isAuthenticated?h({user:t.user,companies:t.companies,alias:t.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:t.selectedUnit,userId:t.userId,userAlias:t.userAlias,placeId:t.placeId,placeName:t.placeName,activePlaceId:t.activePlaceId,activePlaceName:t.activePlaceName}):e&&p(!1)}catch(t){e&&(Ns.handleError(t),p(!1))}})(),()=>{e=!1}},[h,p,b]);const N=o(()=>({...a,logout:b,processCallback:v,switchUnit:g,availableUnits:a.companies,isSearchVisible:s,setSearchVisible:y,clearSearch:w,refreshData:x}),[a.user,a.companies,a.alias,a.isAuthenticated,a.isLoading,a.selectedUnit,a.userId,a.userAlias,a.placeId,a.placeName,a.activePlaceId,a.activePlaceName,b,v,g,s,y,w,x]);return e(Ys.Provider,{value:N,children:t})},ei=()=>{const e=i(Ys);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function ti({queryKey:e,service:t,entityName:a,searchFields:r,additionalFilters:n={},onSuccess:s}){const[i,l]=Mt(),u=Pt(),{alias:m,userId:h,isAuthenticated:p}=ei(),f=c(t=>{const a=`${e}_${t}`,r=i.get(a);return r||(i.get(t)||"")},[i,e]),g=f("search"),v=f("sortField")||Rs.sorting.defaultField,b=f("sortDirection")||Rs.sorting.defaultDirection,y=parseInt(f("page")||"1"),w=parseInt(f("limit")||String(Rs.pagination.defaultPageSize)),x=g,N=o(()=>({search:x,sortField:v,sortDirection:b,page:y,limit:w,...n}),[x,v,b,y,w,n]),k=c(()=>t.getAll(N),[t,N]),S=Rt({queryKey:[e,m,h,N],queryFn:k,enabled:!!m&&p});if(!S)throw new Error(`useCrud: Query initialization failed for "${a}". Ensure QueryClientProvider is configured in your app root.`);const E=Tt({mutationFn:t.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Ds.success.created(a)),s?.()},onError:e=>{C.error(`${Ds.error.create(a)}: ${e.message}`)}}),_=Tt({mutationFn:({id:e,data:a})=>t.update(e,a),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Ds.success.updated(a)),s?.()},onError:e=>{C.error(`${Ds.error.update(a)}: ${e.message}`)}}),P=Tt({mutationFn:t.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Ds.success.deleted(a))},onError:e=>{C.error(`${Ds.error.delete(a)}: ${e.message}`)}}),R=c(t=>{const a={...Object.fromEntries(i)};Object.entries(t).forEach(([t,r])=>{const n=`${e}_${t}`;""===r||0===r?delete a[n]:a[n]=String(r)}),delete a.sortField,delete a.sortDirection,l(a)},[i,l,e]),T=c(e=>{R({search:e,page:1})},[R]),A=c(e=>{R({sortField:e,sortDirection:v===e&&"asc"===b?"desc":"asc",page:1})},[v,b,R]),I=c(e=>{R({page:e})},[R]),M=c(e=>{R({limit:e,page:1})},[R]),O=c(()=>{const t=Object.fromEntries(i),a=`${e}_`,r=Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith(a)));l(r)},[l,i,e]),[L,D]=d([]),F=c(e=>{D(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),j=c(()=>{const e=S?.data?.data.map(e=>e.id)||[];D(t=>t.length===e.length?[]:e)},[S?.data?.data]),z=c(()=>{D([])},[]),$=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,S?.data?.data]),U=Tt({mutationFn:async e=>{await Promise.all(e.map(e=>t.delete(e)))},onSuccess:(t,r)=>{u.invalidateQueries({queryKey:[e]}),C.success(`${r.length} ${a}(s) deletado(s) com sucesso`),z()},onError:e=>{C.error(`Erro ao deletar itens: ${e.message}`)}}),V=c((e,t)=>{const a=t?t(e):e;e.id?_.mutate({id:e.id,data:a}):E.mutate({...a,alias:m})},[m,E,_]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||Rs.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:E?.isPending??!1,isUpdating:_?.isPending??!1,isDeleting:P?.isPending??!1,error:S?.error||null,searchTerm:g,sortField:v,sortDirection:b,currentPage:y,itemsPerPage:w,queryKey:e,createEntity:E.mutate,updateEntity:(e,t)=>_.mutate({id:e,data:t}),deleteEntity:P.mutate,save:V,handleSearch:T,handleSort:A,handlePageChange:I,handleItemsPerPageChange:M,clearFilters:O,refetch:S.refetch,selectedIds:L,selectItem:F,selectAll:j,clearSelection:z,isAllSelected:$,bulkDelete:e=>U.mutateAsync(e),isBulkDeleting:U.isPending}}function ai(e){const t=Hs({tableName:e.tableName,searchFields:e.searchFields||["title"],selectFields:e.selectFields,schemaName:e.schemaName||"central",entityName:e.entityName,enableQualiexEnrichment:e.enableQualiexEnrichment||!0,userIdFields:e.userIdFields,userFieldsMapping:e.userFieldsMapping});return{service:t,useCrudHook:(a,r)=>ti({queryKey:e.tableName,service:{...t,getAll:async(e={})=>await t.getAll({...e})},entityName:e.entityName,additionalFilters:a,onSuccess:r})}}const ri=r.forwardRef(({className:t,...a},r)=>e("table",{ref:r,className:sr("w-full caption-bottom text-sm table-fixed",t),...a}));ri.displayName="Table";const ni=r.forwardRef(({className:t,...a},r)=>e("thead",{ref:r,className:sr("[&_tr]:border-b sticky top-0 z-[1] bg-background",t),...a}));ni.displayName="TableHeader";const si=r.forwardRef(({className:t,...a},r)=>e("tbody",{ref:r,className:sr("[&_tr:last-child]:border-0",t),...a}));si.displayName="TableBody";const ii=r.forwardRef(({className:t,...a},r)=>e("tfoot",{ref:r,className:sr("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...a}));ii.displayName="TableFooter";const oi=r.forwardRef(({className:t,...a},r)=>e("tr",{ref:r,className:sr("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",t),...a}));oi.displayName="TableRow";const li=r.forwardRef(({className:t,...a},r)=>e("th",{ref:r,className:sr("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",t),...a}));li.displayName="TableHead";const ci=r.forwardRef(({className:t,...a},r)=>e("td",{ref:r,className:sr("px-4 py-3 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",t),...a}));ci.displayName="TableCell";const di=r.forwardRef(({className:t,...a},r)=>e("caption",{ref:r,className:sr("mt-4 text-sm text-muted-foreground",t),...a}));function ui({rows:a=5,columns:r=4}){return e("div",{className:"w-full",children:t("div",{className:"rounded-md border",children:[e("div",{className:"border-b bg-muted/50 px-4 py-3",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((t,a)=>e(kn,{className:"h-4 w-24"},a))})}),e("div",{children:Array.from({length:a}).map((t,a)=>e("div",{className:"border-b px-4 py-3 last:border-0",children:e("div",{className:"flex space-x-4",children:Array.from({length:r}).map((t,a)=>e(kn,{className:"h-4 w-20"},a))})},a))})]})})}function mi({count:a=3}){return e("div",{className:"space-y-4",children:Array.from({length:a}).map((a,r)=>t(vr,{children:[t(br,{children:[e(kn,{className:"h-4 w-3/4"}),e(kn,{className:"h-3 w-1/2"})]}),e(xr,{children:t("div",{className:"space-y-2",children:[e(kn,{className:"h-3 w-full"}),e(kn,{className:"h-3 w-2/3"})]})})]},r))})}function hi({fields:a=4}){return t("div",{className:"space-y-4",children:[Array.from({length:a}).map((a,r)=>t("div",{className:"space-y-2",children:[e(kn,{className:"h-4 w-24"}),e(kn,{className:"h-10 w-full"})]},r)),t("div",{className:"flex justify-end space-x-2 pt-4",children:[e(kn,{className:"h-10 w-20"}),e(kn,{className:"h-10 w-20"})]})]})}function pi(){return t("div",{className:"flex items-center justify-between p-4 border-b",children:[t("div",{className:"flex items-center space-x-3",children:[e(kn,{className:"h-8 w-8 rounded-full"}),e(kn,{className:"h-6 w-32"})]}),t("div",{className:"flex items-center space-x-2",children:[e(kn,{className:"h-8 w-8"}),e(kn,{className:"h-8 w-24"})]})]})}function fi(){return e("div",{className:"w-64 border-r bg-muted/10",children:t("div",{className:"p-4",children:[e(kn,{className:"h-8 w-32 mb-6"}),e("div",{className:"space-y-2",children:Array.from({length:6}).map((a,r)=>t("div",{className:"flex items-center space-x-3 p-2",children:[e(kn,{className:"h-4 w-4"}),e(kn,{className:"h-4 w-20"})]},r))})]})})}di.displayName="TableCaption";const gi={default:z,search:j,error:F};function vi({icon:a,title:r,description:n,action:s,className:i,variant:o="default"}){const l=a?()=>a:gi[o];return t("div",{className:sr("flex flex-col items-center justify-center py-12 px-4 text-center",i),children:[e("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e(l,{className:"h-8 w-8 text-muted-foreground"})}),e("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&e("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),s&&e(mr,{onClick:s.onClick,variant:"outline",children:s.label})]})}const bi=Ft.Provider,yi=Ft.Root,wi=Ft.Trigger,xi=r.forwardRef(({className:t,sideOffset:a=4,...r},n)=>e(Ft.Content,{ref:n,sideOffset:a,className:sr("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r}));function Ni({children:a,className:n}){const s=r.useRef(null),[i,o]=r.useState(!1);r.useEffect(()=>{const e=()=>{const e=s.current;e&&o(e.scrollWidth>e.clientWidth)};e();const t=new ResizeObserver(e);return s.current&&t.observe(s.current),()=>t.disconnect()},[a]);const l=e("div",{ref:s,className:`truncate w-full max-w-full ${n||""}`,children:a});return i?e(bi,{delayDuration:300,children:t(yi,{children:[e(wi,{asChild:!0,children:l}),e(xi,{side:"top",className:"max-w-[400px] break-words",children:a})]})}):l}xi.displayName=Ft.Content.displayName;const ki=r.forwardRef(({direction:t,onMouseDown:a,isDragging:r,className:n},s)=>{const i="horizontal"===t;return e("div",{ref:s,onMouseDown:a,className:sr("absolute z-20 select-none touch-none","transition-colors duration-150",i&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!i&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:e("div",{className:sr("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",i?"h-6 w-0.5":"w-6 h-0.5")})})});ki.displayName="TableResizeHandle";const Ci=jt.Root,Si=jt.Trigger,Ei=jt.Group,_i=jt.Portal,Pi=jt.Sub,Ri=jt.RadioGroup,Ti=r.forwardRef(({className:a,inset:r,children:n,...s},i)=>t(jt.SubTrigger,{ref:i,className:sr("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",a),...s,children:[n,e($,{className:"ml-auto h-4 w-4"})]}));Ti.displayName=jt.SubTrigger.displayName;const Ai=r.forwardRef(({className:t,...a},r)=>e(jt.SubContent,{ref:r,className:sr("z-50 min-w-[8rem] overflow-hidden border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a}));Ai.displayName=jt.SubContent.displayName;const Ii=r.forwardRef(({className:t,sideOffset:a=4,...r},n)=>e(jt.Portal,{children:e(jt.Content,{ref:n,sideOffset:a,className:sr("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})}));Ii.displayName=jt.Content.displayName;const Mi=r.forwardRef(({className:t,inset:a,...r},n)=>e(jt.Item,{ref:n,className:sr("relative flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a&&"pl-8",t),...r}));Mi.displayName=jt.Item.displayName;const Oi=r.forwardRef(({className:a,children:r,checked:n,...s},i)=>t(jt.CheckboxItem,{ref:i,className:sr("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(jt.ItemIndicator,{children:e(T,{className:"h-4 w-4"})})}),r]}));Oi.displayName=jt.CheckboxItem.displayName;const Li=r.forwardRef(({className:a,children:r,...n},s)=>t(jt.RadioItem,{ref:s,className:sr("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(jt.ItemIndicator,{children:e(U,{className:"h-2 w-2 fill-current"})})}),r]}));Li.displayName=jt.RadioItem.displayName;const Di=r.forwardRef(({className:t,inset:a,...r},n)=>e(jt.Label,{ref:n,className:sr("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...r}));Di.displayName=jt.Label.displayName;const Fi=r.forwardRef(({className:t,...a},r)=>e(jt.Separator,{ref:r,className:sr("-mx-1 my-1 h-px bg-muted",t),...a}));Fi.displayName=jt.Separator.displayName;const ji=({className:t,...a})=>e("span",{className:sr("ml-auto text-xs tracking-widest opacity-60",t),...a});ji.displayName="DropdownMenuShortcut";const zi=zt.Root,$i=zt.Trigger,Ui=zt.Group,Vi=zt.Portal,Wi=zt.Sub,Bi=zt.RadioGroup,Hi=r.forwardRef(({className:a,inset:r,children:n,...s},i)=>t(zt.SubTrigger,{ref:i,className:sr("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",a),...s,children:[n,e($,{className:"ml-auto h-4 w-4"})]}));Hi.displayName=zt.SubTrigger.displayName;const qi=r.forwardRef(({className:t,...a},r)=>e(zt.SubContent,{ref:r,className:sr("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a}));qi.displayName=zt.SubContent.displayName;const Ki=r.forwardRef(({className:t,...a},r)=>e(zt.Portal,{children:e(zt.Content,{ref:r,className:sr("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})}));Ki.displayName=zt.Content.displayName;const Gi=r.forwardRef(({className:t,inset:a,...r},n)=>e(zt.Item,{ref:n,className:sr("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a&&"pl-8",t),...r}));Gi.displayName=zt.Item.displayName;const Xi=r.forwardRef(({className:a,children:r,checked:n,...s},i)=>t(zt.CheckboxItem,{ref:i,className:sr("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(zt.ItemIndicator,{children:e(T,{className:"h-4 w-4"})})}),r]}));Xi.displayName=zt.CheckboxItem.displayName;const Ji=r.forwardRef(({className:a,children:r,...n},s)=>t(zt.RadioItem,{ref:s,className:sr("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(zt.ItemIndicator,{children:e(U,{className:"h-2 w-2 fill-current"})})}),r]}));Ji.displayName=zt.RadioItem.displayName;const Qi=r.forwardRef(({className:t,inset:a,...r},n)=>e(zt.Label,{ref:n,className:sr("px-2 py-1.5 text-sm font-semibold text-foreground",a&&"pl-8",t),...r}));Qi.displayName=zt.Label.displayName;const Yi=r.forwardRef(({className:t,...a},r)=>e(zt.Separator,{ref:r,className:sr("-mx-1 my-1 h-px bg-border",t),...a}));Yi.displayName=zt.Separator.displayName;const Zi=({className:t,...a})=>e("span",{className:sr("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});Zi.displayName="ContextMenuShortcut";const eo=({onEdit:r,onDelete:n,onToggleStatus:s,isActive:i=!0,canDelete:o=!0,customActions:l=[],renderAs:c})=>{const{t:d}=Kn(),u=[];if(r){const e={icon:V,label:d("edit"),onClick:r};u.push(e)}if(l.forEach(e=>{u.push(e)}),s){const e={icon:i?W:B,label:d(i?"deactivate":"activate"),onClick:s};u.push(e)}if(o&&n){const e={icon:H,label:d("delete"),onClick:n,destructive:!0};u.push(e)}const m="dropdown"===c?Mi:Gi;return e(a,{children:u.map((a,r)=>t(m,{onClick:a.onClick,className:sr("whitespace-normal cursor-pointer",a.destructive&&"text-destructive focus:text-destructive"),children:[e(a.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),a.label]},r))})},to=({onEdit:a,onDelete:r,canDelete:n=!0,onToggleStatus:s,isActive:i=!0,customActions:o=[]})=>t(Ci,{children:[e(Si,{asChild:!0,children:e(mr,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e(E,{size:12})})}),e(Ii,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:e(eo,{onEdit:a?e=>{e?.stopPropagation(),a?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:s?e=>{e?.stopPropagation(),s?.()}:void 0,isActive:i,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),ao=150;function ro({columns:e,storageKey:t,onResize:a,enabled:r=!0}){const[n,s]=d(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,t)=>(e[t.key]=t.defaultWidth??ao,e),{});if(t){const e=localStorage.getItem(t);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,t)=>(e[t.key]=t.defaultWidth??ao,e),{})}),[i,o]=d(!1),[m,h]=d(null),p=l(0),f=l(0),g=c((e,t)=>{r&&(t.preventDefault(),t.stopPropagation(),o(!0),h(e),p.current=t.clientX,f.current=n[e]??ao)},[r,n]);u(()=>{if(!i||!m)return;const r=e.find(e=>e.key===m),n=r?.minWidth??60,l=r?.maxWidth??500,c=e=>{const t=e.clientX-p.current,r=Math.max(n,Math.min(l,f.current+t));s(e=>{const t={...e,[m]:r};return a?.(t),t})},d=()=>{o(!1),h(null),t&&s(e=>(localStorage.setItem(t,JSON.stringify(e)),e))};return document.addEventListener("mousemove",c),document.addEventListener("mouseup",d),()=>{document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",d)}},[i,m,e,t,a]),u(()=>{i?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[i]);const v=c(()=>{const r=e.reduce((e,t)=>(e[t.key]=t.defaultWidth??ao,e),{});s(r),t&&localStorage.removeItem(t),a?.(r)},[e,t,a]);return{columnWidths:n,isDragging:i,activeColumn:m,handleMouseDown:g,resetWidths:v}}function no({rowIds:e,defaultHeight:t=48,minHeight:a=32,maxHeight:r=120,storageKey:n,onResize:s,enabled:i=!0}){const[o,m]=d(()=>{if(!i||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[h,p]=d(!1),[f,g]=d(null),v=l(0),b=l(0),y=c(e=>o[e]??t,[o,t]),w=c((e,a)=>{i&&(a.preventDefault(),a.stopPropagation(),p(!0),g(e),v.current=a.clientY,b.current=o[e]??t)},[i,o,t]);u(()=>{if(!h||!f)return;const e=e=>{const t=e.clientY-v.current,n=Math.max(a,Math.min(r,b.current+t));m(e=>{const t={...e,[f]:n};return s?.(t),t})},t=()=>{p(!1),g(null),n&&m(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[h,f,a,r,n,s]),u(()=>{h?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h]);const x=c(()=>{m({}),n&&localStorage.removeItem(n),s?.({})},[n,s]);return{rowHeights:o,isDragging:h,activeRow:f,handleMouseDown:w,resetHeights:x,getRowHeight:y}}const so=h(({checked:t,onCheckedChange:a})=>e(an,{checked:t,onCheckedChange:a}),(e,t)=>e.checked===t.checked),io=({manager:a,columns:r,onEdit:n,onView:s,onToggleStatus:i,onDelete:l,renderActions:c,customRowActions:m,enableBulkActions:h=!1,onNew:p,newButtonLabel:f,showNewButton:g=!0,customActions:v=[],hideActionBar:b=!1,enableColumnResize:y=!1,enableRowResize:w=!1,resizeStorageKey:x})=>{const{t:N}=Kn(),{setSearchVisible:k}=ei(),[C,S]=d(!1);u(()=>(k(!0),()=>k(!1)),[k]),u(()=>{const e=()=>S(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const{columnWidths:E,isDragging:_,activeColumn:P,handleMouseDown:R}=ro({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:x?`${x}-columns`:void 0,enabled:y}),{isDragging:T,activeRow:A,handleMouseDown:I,getRowHeight:M}=no({rowIds:a.entities.map(e=>e.id),storageKey:x?`${x}-rows`:void 0,enabled:w}),O=o(()=>(()=>{if(y)return r.map(e=>{const t=E[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:t,style:{width:`${t}px`}}});let e=0;const t=r.map(t=>{if(t.width)return e+=t.width,{...t,calculatedWidth:t.width,isFixed:!0};{const a=t.minWidth||120,r=t.weight||1;return e+=a,{...t,calculatedWidth:a,weight:r,isFixed:!1}}});return e+=50,t.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[r,y,E]),L=!b&&(p||v.length>0);return C?a.isLoading?e(mi,{count:3}):0===a.entities.length?e(vi,{title:N("empty_title"),description:N("empty_description"),variant:"search"}):t("div",{className:"flex flex-col h-full",children:[L&&e("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:t("div",{className:"flex items-center gap-2",children:[p&&g&&t(mr,{onClick:p,children:[e(q,{size:16,className:"mr-2"}),f||N("new")]}),v.map((a,r)=>{const n=a.icon;return t(mr,{onClick:a.action,variant:a.variant||"outline",children:[n&&e(n,{size:16,className:"mr-2"}),a.label]},r)})]})}),e("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:a.entities.map(o=>t(zi,{children:[e($i,{asChild:!0,children:e(vr,{className:sr("overflow-hidden cursor-pointer hover:bg-muted/50",h&&a.selectedIds.includes(o.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?a.selectItem(o.id):n?.(o)},children:e(xr,{className:"p-4",children:t("div",{className:"flex items-start gap-3",children:[h&&e("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e(so,{checked:a.selectedIds.includes(o.id),onCheckedChange:()=>a.selectItem(o.id)})}),t("div",{className:"flex-1",children:[r.map(a=>t("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[t("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[a.header,":"]}),e("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:a.render?a.render(o):String(o[a.key]??"")})]},String(a.key))),(n||s||c)&&e("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(o):e(to,{onEdit:n?()=>{n(o)}:void 0,onDelete:l?()=>l(o):void 0,onToggleStatus:i?()=>i(o):void 0,isActive:o.is_actived,customActions:m?m(o):[]})})]})]})})})}),e(Ki,{className:"w-[160px]",children:e(eo,{onEdit:n?()=>n(o):void 0,onDelete:l?()=>l(o):void 0,onToggleStatus:i?()=>i(o):void 0,isActive:o.is_actived,canDelete:!!l,customActions:m?m(o):[],renderAs:"context"})})]},o.id))})]}):t("div",{className:"flex flex-col h-full",children:[L&&e("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:t("div",{className:"flex items-center gap-2",children:[p&&g&&t(mr,{onClick:p,children:[e(q,{size:16,className:"mr-2"}),f||N("new")]}),v.map((a,r)=>{const n=a.icon;return t(mr,{onClick:a.action,variant:a.variant||"outline",children:[n&&e(n,{size:16,className:"mr-2"}),a.label]},r)})]})}),a.isLoading?e(ui,{rows:5,columns:r.length}):e("div",{className:"flex flex-col h-full overflow-hidden",children:e("div",{className:"flex-1 overflow-auto",children:t(ri,{className:"table-auto",children:[t("colgroup",{children:[h&&e("col",{style:{width:"50px"}}),O.map((t,a)=>e("col",{style:t.style},a)),e("col",{style:{width:"50px"}})]}),e(ni,{children:t(oi,{children:[h&&e(li,{className:"w-[50px]",children:e(so,{checked:a.isAllSelected,onCheckedChange:a.selectAll})}),r.map(r=>{const n=y&&!1!==r.resizable,s=P===String(r.key);return t(li,{className:sr(r.className,r.sortable&&"cursor-pointer hover:bg-muted/50","relative"),onClick:r.sortable?()=>a.handleSort(String(r.key)):void 0,children:[t("div",{className:"flex items-center "+(r.className?.includes("text-center")?"justify-center":""),children:[r.header,r.sortable&&(i=String(r.key),a.sortField!==i?e(K,{size:14,className:"ml-1 opacity-50"}):"asc"===a.sortDirection?e(G,{size:14,className:"ml-1"}):e(X,{size:14,className:"ml-1"}))]}),n&&e(ki,{direction:"horizontal",onMouseDown:e=>R(String(r.key),e),isDragging:s})]},String(r.key));var i}),e(li,{className:"w-[50px] text-center",children:N("actions")})]})}),e(si,{children:0===a.entities.length?e(oi,{children:e(ci,{colSpan:h?r.length+2:r.length+1,className:"h-32",children:e(vi,{title:N("empty_title"),description:N("empty_description"),variant:"search"})})}):a.entities.map(s=>t(zi,{children:[e($i,{asChild:!0,children:t(oi,{className:sr("cursor-pointer hover:bg-muted/50",h&&a.selectedIds.includes(s.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),h?a.selectItem(s.id):n?.(s)},children:[h&&e(ci,{onClick:e=>e.stopPropagation(),children:e(so,{checked:a.selectedIds.includes(s.id),onCheckedChange:()=>a.selectItem(s.id)})}),r.map(t=>e(ci,{className:t.className,children:e(Ni,{children:t.render?t.render(s):String(s[t.key]??"")})},String(t.key))),e(ci,{className:"text-center",children:c?c(s):e(to,{onEdit:n?()=>n(s):void 0,onDelete:l?()=>l(s):void 0,onToggleStatus:i?()=>i(s):void 0,isActive:s.is_actived,customActions:m?m(s):[]})})]})}),e(Ki,{className:"w-[160px]",children:e(eo,{onEdit:n?()=>n(s):void 0,onDelete:l?()=>l(s):void 0,onToggleStatus:i?()=>i(s):void 0,isActive:s.is_actived,canDelete:!!l,customActions:m?m(s):[],renderAs:"context"})})]},s.id))})]})})})]})};function oo(e,t,a,r){const[n,s]=d({}),[i,l]=d({}),c=o(()=>e,[e]),m=e=>e instanceof Date&&!isNaN(e.getTime()),h=e=>{if(void 0!==e.defaultValue)return e.defaultValue;switch(e.type){case"multiselect":return[];case"checkbox":return!1;case"number":return 0;case"date":default:return"";case"group":return{}}},p=(e,t)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(t)}catch(a){return h(e)}},f=(e,t,a)=>{if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(t,a);if(e)return e}catch(r){}}};u(()=>{if(!r)return;const e=t=>{const a=[];return t.forEach(t=>{a.push(t),t.fields&&a.push(...e(t.fields))}),a},n=e(c),i={};n.forEach(e=>{let a;if(t&&void 0!==t[e.name]){if(a=t[e.name],null==a&&(a=""),"date"===e.type&&a)if("string"==typeof a){const e=new Date(a);m(e)&&(a=e.toISOString().split("T")[0])}else m(a)&&(a=a.toISOString().split("T")[0])}else a=h(e);i[e.name]=a}),n.forEach(e=>{const t=p(e,i);void 0!==t&&(i[e.name]=t)}),t&&Object.keys(t).forEach(e=>{n.find(t=>t.name===e)||void 0===t[e]||(i[e]=t[e])}),s(i),l({}),a&&a(i)},[c,t,a,r]);const g=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...g(e.fields))}),t},v=()=>{const e=g(c),t={};return e.forEach(e=>{const a=f(e,n[e.name],n);a&&(t[e.name]=a)}),l(t),0===Object.keys(t).length};return{formData:n,errors:i,updateField:(e,t)=>{s(r=>{const n={...r,[e]:t},s=((e,t)=>{let a={...t};const r=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...r(e.fields))}),t};return r(c).filter(t=>t.dependsOn===e).forEach(e=>{const t=p(e,a);void 0!==t&&(a={...a,[e.name]:t})}),a})(e,n);return a&&a(s),s}),i[e]&&l(t=>{const a={...t};return delete a[e],a});const r=g(c).find(t=>t.name===e);if(r){const a=f(r,t,n);a&&l(t=>({...t,[e]:a}))}},validateForm:v,handleSubmit:e=>t=>{t&&(t.preventDefault(),t.stopPropagation()),v()&&e(n)}}}const lo=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],co=({value:a="#3b82f6",onChange:r,label:n})=>t("div",{className:"space-y-2",children:[n&&e(gr,{children:n}),t(un,{children:[e(mn,{asChild:!0,children:t(mr,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:a}}),a]})}),e(hn,{className:"w-64",children:t("div",{className:"space-y-3",children:[t("div",{children:[e(gr,{htmlFor:"color-input",children:"Cor personalizada"}),e(pr,{id:"color-input",type:"color",value:a,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),t("div",{children:[e(gr,{children:"Cores predefinidas"}),e("div",{className:"grid grid-cols-5 gap-2 mt-2",children:lo.map(t=>e("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:t},onClick:()=>r?.(t),"aria-label":`Selecionar cor ${t}`},t))})]})]})})]})]}),uo=r.forwardRef(({className:a,children:r,...n},s)=>t($t.Root,{ref:s,className:sr("relative overflow-hidden",a),...n,children:[e($t.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),e(mo,{}),e($t.Corner,{})]}));uo.displayName=$t.Root.displayName;const mo=r.forwardRef(({className:t,orientation:a="vertical",...r},n)=>e($t.ScrollAreaScrollbar,{ref:n,orientation:a,className:sr("flex touch-none select-none transition-colors","vertical"===a&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===a&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...r,children:e($t.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));mo.displayName=$t.ScrollAreaScrollbar.displayName;const ho={Star:$e,Heart:ze,Home:je,User:Fe,Settings:De,Mail:Le,Phone:Oe,Calendar:Me,MapPin:Ie,Camera:Ae,Image:Te,Music:Re,Video:Pe,Book:_e,Bookmark:Ee,Search:j,Filter:Se,Edit:V,Trash2:H,Plus:q,Minus:Ce,Check:T,X:_,ChevronDown:P,ChevronUp:R,ChevronLeft:ke,ChevronRight:$,ArrowUp:G,ArrowDown:X,ArrowLeft:Ne,ArrowRight:xe,Clock:we,Bell:ye,AlertCircle:F,Info:be,HelpCircle:ve,Download:ge,Upload:fe,Share:pe,Copy:he,Save:me,FileText:ue,Folder:de,FolderOpen:ce,Archive:le,Lock:oe,Unlock:ie,Eye:se,EyeOff:ne,Shield:re,Key:ae,Zap:te,Flame:ee,Sparkles:Z,Award:Y,Trophy:Q,Target:J},po=({value:a="Star",onChange:r,label:n})=>{const{t:s}=Kn(),[i,o]=d(""),l=Object.entries(ho).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),c=ho[a]||$e;return t("div",{className:"space-y-2",children:[n&&e(gr,{children:n}),t(un,{children:[e(mn,{asChild:!0,children:t(mr,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e(c,{className:"h-4 w-4 mr-2"}),a]})}),e(hn,{className:"w-80",children:t("div",{className:"space-y-3",children:[t("div",{children:[e(gr,{htmlFor:"icon-search",children:s("search")}),e(pr,{id:"icon-search",placeholder:s("search"),value:i,onChange:e=>o(e.target.value)})]}),e(uo,{className:"h-48",children:e("div",{className:"grid grid-cols-6 gap-2",children:l.map(([t,n])=>e("button",{className:"p-2 rounded border-2 hover:border-primary "+(a===t?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(t),title:t,children:e(n,{className:"h-4 w-4"})},t))})})]})})]})]})},fo=r.forwardRef(({className:t,...a},r)=>e(Ut.Root,{className:sr("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...a,ref:r,children:e(Ut.Thumb,{className:sr("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));fo.displayName=Ut.Root.displayName;const go=(e={})=>{const{user:t,alias:a}=ei(),{enabled:r=!0}=e;return Rt({queryKey:["qualiex-users",a],queryFn:()=>_s.getUsers(a),enabled:r&&!!a&&!!t,retry:2,retryDelay:1e3})},vo=({value:t,onChange:a,multiple:r=!1,label:n,required:s,placeholder:i,icon:l,maxDisplayedBadges:d,className:u,disabled:m,enabled:h,displayFormat:p="name",customDisplayFn:f,filterFn:g,sortOptions:v=!0,popoverContainer:b,onOpen:y,onClose:w})=>{const{t:x}=Kn(),{data:N=[],isLoading:k,error:C}=go({enabled:h}),S=o(()=>g?N.filter(g):N,[N,g]),E=c(e=>{if("custom"===p&&f)return f(e);const t=e.userName||e.displayName||"";switch(p){case"name-email":return e.userEmail?`${t} (${e.userEmail})`:t;case"name-role":return e.roleName?`${t} - ${e.roleName}`:t;default:return t}},[p,f]);return e(Qn,{multiple:r,value:t??(r?[]:""),onChange:a,options:S,isLoading:k,error:C,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:E,placeholder:i||x("search_placeholder"),searchPlaceholder:x("search_placeholder"),emptyMessage:x("no_results"),label:n,required:s,icon:l,maxDisplayedBadges:d,disabled:m,className:u,sortOptions:v,popoverContainer:b,onOpen:y,onClose:w})};function bo({title:a,sections:r,initialData:s,onSubmit:i,onCancel:u,open:m,submitButtonText:h,isLoading:p=!1,usersData:f}){const{t:g}=Kn(),[v,b]=d(r?.[0]?.id||""),y=l(null),[w,x]=d(null),N=c(e=>{y.current=e,x(e)},[]),k=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:C,errors:S,updateField:E,handleSubmit:_}=oo(k,s,void 0,m),P=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(C):e.disabled||!1})):[],[r,C]),R=o(()=>{const e=P.find(e=>e.id===v);if(e&&!e.disabled)return v;const t=P.find(e=>!e.disabled);return t?.id||v},[P,v]);n.useEffect(()=>{R!==v&&b(R)},[R,v]);const T=P.find(e=>e.id===R),A=a=>{const r=(a.computedValue,C[a.name]),n=void 0!==r?r:"",s=S[a.name];switch(a.type){case"group":const r="horizontal"===a.layout,i=r?`flex gap-3 w-full ${a.className||""}`:"space-y-3",o=r?sr("space-y-2 w-full",a.wrapperClassName):sr("space-y-2",a.className,a.wrapperClassName);return t("div",{className:o,children:[a.label,e("div",{className:i,children:a.fields?.map(e=>A(e))})]},a.name);case"user-select":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(vo,{value:n||"",onChange:e=>E(a.name,e),placeholder:a.placeholder,disabled:a.disabled,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"textarea":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(rn,{id:a.name,value:n||"",onChange:e=>{E(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,rows:a.rows,maxLength:a.maxLength,className:`${s?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"select":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t(qr,{value:String(n),onValueChange:e=>{E(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,children:[e(Xr,{className:`${s?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,children:e(Gr,{placeholder:a.placeholder})}),e(Yr,{children:a.options?.map(t=>e(en,{value:t.value,children:t.label},t.value))})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"multiselect":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Qn,{options:a.options||[],value:Array.isArray(n)?n:[],onChange:e=>E(a.name,e),placeholder:a.placeholder,disabled:a.disabled,error:s,popoverContainer:w,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"date":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{id:a.name,type:"date",value:String(n),onChange:e=>E(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,className:sr("w-full",s?"border-destructive":"",a.disabled?"bg-muted cursor-not-allowed":"")}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"color":return t("div",{children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{id:a.name,type:"color",value:n||a.defaultValue||"#000000",onChange:e=>E(a.name,e.target.value),className:"h-10"}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},a.name);case"color-picker":return t("div",{children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(co,{value:n||a.defaultValue||"#3b82f6",onChange:e=>E(a.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},a.name);case"icon-picker":return t("div",{children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(po,{value:n||a.defaultValue||"Star",onChange:e=>E(a.name,e)}),s&&e("p",{className:"text-sm text-destructive mt-1",children:s})]},a.name);case"custom":if(!a.component)return null;const l=a.component,c="function"==typeof a.componentProps?a.componentProps(C):a.componentProps||{};return t("div",{className:`space-y-2 ${a.className||""}`,children:[a.label&&t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(l,{value:n,onChange:e=>{E(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,error:s,popoverContainer:w,...c}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"number":return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{id:a.name,type:"number",value:null!=n?String(n):"",onChange:e=>{const t=e.target.value,r=""===t?null:Number(t);E(a.name,r)},placeholder:a.placeholder,disabled:a.disabled,className:`${s?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,min:a.min,step:a.step||"1"}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"checkbox":return t("div",{className:`flex items-center space-x-2 ${a.className||""}`,children:[e(an,{id:a.name,checked:!!n,onCheckedChange:e=>E(a.name,e),disabled:a.disabled}),t(gr,{htmlFor:a.name,className:"cursor-pointer",children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"switch":return t("div",{className:`flex items-center justify-between space-x-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(fo,{id:a.name,checked:!!n,onCheckedChange:e=>E(a.name,e),disabled:a.disabled}),s&&e("p",{className:"text-sm text-destructive mt-2",children:s})]},a.name);default:return t("div",{className:`space-y-2 ${a.className||""}`,children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{id:a.name,type:"text",value:n||"",onChange:e=>{E(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${s?"border-destructive":""} ${a.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:a.disabled}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name)}},I=c(()=>{if(!T)return null;if(T.disabled)return t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e("div",{className:"rounded-full bg-muted p-3 mb-4",children:e("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e("p",{className:"text-muted-foreground max-w-sm",children:'Complete as informações obrigatórias na seção "Informações Gerais" para acessar esta seção.'})]});if(T.component){const t=T.component;return e(t,{formData:C,updateField:E,errors:S,users:f,disabled:T.disabled})}return e("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.fields.map(A)})},[T,C,E,S,f,A]),M=t("div",{className:"flex flex-col max-h-[80vh]",children:[P.length>1&&e("div",{className:"flex-shrink-0 p-4 border-b",children:e("div",{className:"flex space-x-2",children:P.map(t=>e(mr,{variant:R===t.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const t=P.find(t=>t.id===e);t&&!t.disabled&&b(e)})(t.id),disabled:t.disabled,className:t.disabled?"opacity-50 cursor-not-allowed":"",children:t.title},t.id))})}),e("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:p?e("div",{className:"flex items-center justify-center py-12",children:e("div",{className:"text-muted-foreground",children:g("loading")})}):t("form",{onSubmit:_(i),className:"space-y-3 md:space-y-4",children:[I(),t("div",{className:"flex justify-end space-x-2 pt-4",children:[e(mr,{type:"button",variant:"outline",onClick:u,children:g("cancel")}),e(mr,{type:"submit",disabled:p,children:h||g("save")})]})]})})]});return e(Cr,{open:m,onOpenChange:e=>{!1===e&&!0===m&&u()},children:t(Tr,{ref:N,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[t(Ar,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e(Or,{children:a}),e(Lr,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),M]})})}function yo({currentPage:r,totalPages:n,totalItems:s,itemsPerPage:i,onPageChange:o,onItemsPerPageChange:l,variant:c="full"}){const d=(r-1)*i+1,u=Math.min(r*i,s);return t("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e("div",{className:"flex items-center gap-2",children:"full"===c&&t(a,{children:[e("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),t(qr,{value:String(i),onValueChange:e=>l(Number(e)),children:[e(Xr,{className:"h-8 w-[70px]",children:e(Gr,{})}),t(Yr,{children:[e(en,{value:"10",children:"10"}),e(en,{value:"25",children:"25"}),e(en,{value:"50",children:"50"}),e(en,{value:"100",children:"100"})]})]})]})}),t("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[d,"-",u," de ",s," itens"]}),t("div",{className:"flex items-center gap-1",children:[e(mr,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===r,className:"h-8 w-8 p-0",children:e(Ue,{size:16})}),e(mr,{variant:"outline",size:"sm",onClick:()=>o(r-1),disabled:1===r,className:"h-8 w-8 p-0",children:e(ke,{size:16})}),t("div",{className:"flex items-center gap-1 px-2",children:[e("span",{className:"text-sm font-medium",children:r}),e("span",{className:"text-sm text-muted-foreground",children:"de"}),e("span",{className:"text-sm font-medium",children:n})]}),e(mr,{variant:"outline",size:"sm",onClick:()=>o(r+1),disabled:r===n,className:"h-8 w-8 p-0",children:e($,{size:16})}),e(mr,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:r===n,className:"h-8 w-8 p-0",children:e(Ve,{size:16})})]})]})}function wo({manager:t}){return e(yo,{currentPage:t.pagination.currentPage,totalPages:t.pagination.totalPages,totalItems:t.pagination.totalItems,itemsPerPage:t.pagination.itemsPerPage,onPageChange:t.handlePageChange,onItemsPerPageChange:t.handleItemsPerPageChange,variant:"full"})}const xo=({selectedCount:a,onClearSelection:r,onBulkDelete:n,customActions:s=[],isLoading:i=!1})=>{const{t:o}=Kn();return t("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[t("div",{className:"flex items-center gap-3",children:[e("span",{className:"text-sm font-medium",children:o("selected_count",{count:a})}),t(mr,{variant:"ghost",size:"sm",onClick:r,className:"h-7 px-2",children:[e(_,{size:14,className:"mr-1"}),o("clear")]})]}),t("div",{className:"flex items-center gap-2",children:[s.map((a,r)=>{const n=a.icon;return t(mr,{variant:a.variant||"outline",size:"sm",onClick:()=>a.action([]),disabled:i,className:"h-7",children:[n&&e(n,{size:14,className:"mr-1"}),a.label]},r)}),n&&t(mr,{variant:"destructive",size:"sm",onClick:n,disabled:i,className:"h-7",children:[e(H,{size:14,className:"mr-1"}),o("delete")]})]})]})},No={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},ko={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Co={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function So({children:t,direction:a="column",gap:r="md",align:n="stretch",justify:s="start",wrap:i=!1,className:o}){return e("div",{className:sr("flex","column"===a?"flex-col":"flex-row",No[r],ko[n],Co[s],i&&"flex-wrap",o),children:t})}function Eo({manager:r,filters:n,inline:s=!1}){const{t:i}=Kn(),{isSearchVisible:o}=ei(),l=r.searchTerm,c=t(a,{children:[n.some(e=>"search"===e.type)&&!o&&t("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(pr,{placeholder:i("search"),value:r.searchTerm,onChange:e=>r.handleSearch(e.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((a,r)=>t("select",{value:a.value||"",onChange:e=>a.onChange?.(e.target.value),className:"h-10 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[a.placeholder&&e("option",{value:"",children:a.placeholder}),a.options.map(t=>e("option",{value:t.value,children:t.label},t.value))]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((t,a)=>{const r=t.component;return e("div",{className:s?"":"w-full sm:w-auto",children:e(r,{...t.props})},`custom-${a}`)}),l&&t(mr,{variant:"outline",onClick:r.clearFilters,className:"whitespace-nowrap",children:[e(_,{className:"h-4 w-4 mr-2"}),i("clear")]})]});return s?e("div",{className:"flex items-center gap-2",children:c}):e(So,{direction:"column",gap:"md",className:"mb-6",children:e(So,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:c})})}function _o({manager:a,config:r,formSections:n,onSave:s,onToggleStatus:i,defaultSort:o}){a&&a.queryKey;const{t:l}=Kn(),{setSearchVisible:c}=ei(),[m,h]=Mt(),[p,f]=d(!1),[g,v]=d(null),[b,y]=d({isOpen:!1,entityId:null,entityName:""}),[w,x]=d({isOpen:!1,count:0});u(()=>(c(!0),()=>{c(!1)}),[c]),u(()=>{if(o&&a){const e=`${a.queryKey}_sortField`,t=`${a.queryKey}_sortDirection`;if(!m.has(e)&&!m.has(t)){const a=Object.fromEntries(m);a[e]=o.column,a[t]=o.direction,h(a)}}},[]);const N=()=>{y({isOpen:!1,entityId:null,entityName:""})};return t("div",{className:"flex-1 flex flex-col h-full",children:[r.enableBulkActions&&a.selectedIds.length>0&&e(xo,{selectedCount:a.selectedIds.length,onClearSelection:a.clearSelection,onBulkDelete:r.bulkActions&&r.bulkActions.length>0?void 0:()=>{x({isOpen:!0,count:a.selectedIds.length})},customActions:r.bulkActions,isLoading:a.isBulkDeleting}),t("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[t("div",{className:"flex items-center gap-2",children:[t(mr,{onClick:()=>{r.onNew?r.onNew():(v(null),f(!0))},children:[e(q,{size:16,className:"mr-2"}),l("new")]}),r.customActions?.map((a,r)=>t(mr,{onClick:a.action,variant:a.variant||"outline",children:[a.icon&&e(a.icon,{size:16,className:"mr-2"}),a.label]},r))]}),r.filters&&r.filters.length>0&&e("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e(Eo,{manager:a,filters:r.filters,inline:!0})})]}),e("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?e("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(a.entities,a)}):e(io,{manager:a,columns:r.columns,onEdit:e=>{r.onEdit?r.onEdit(e):(v(e),f(!0))},onDelete:e=>{y({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:i,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions})}),e("div",{className:"flex-shrink-0 border-t bg-background",children:e(wo,{manager:a})}),!r.useCustomRouting&&e(bo,{open:p,title:g?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:g||void 0,onSubmit:e=>{s(e),f(!1),v(null)},onCancel:()=>{f(!1),v(null)},isLoading:a.isLoading,submitButtonText:l(g?"update":"create")}),e(Cr,{open:b.isOpen,onOpenChange:N,children:t(Tr,{size:"sm",children:[e(Ar,{showSeparator:!0,children:e(Or,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:t("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:b.entityName}),". Esta ação não pode ser desfeita."]})}),t(Mr,{children:[e(mr,{variant:"outline",onClick:N,children:"Cancelar"}),e(mr,{variant:"destructive",onClick:()=>{b.entityId&&(a.deleteEntity(b.entityId),y({isOpen:!1,entityId:null,entityName:""}))},disabled:a.isDeleting,children:a.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),e(Cr,{open:w.isOpen,onOpenChange:()=>x({isOpen:!1,count:0}),children:t(Tr,{size:"sm",children:[e(Ar,{showSeparator:!0,children:e(Or,{children:"Você tem certeza absoluta?"})}),e("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:t("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",e("strong",{children:w.count})," ",1===w.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),t(Mr,{children:[e(mr,{variant:"outline",onClick:()=>x({isOpen:!1,count:0}),children:"Cancelar"}),e(mr,{variant:"destructive",onClick:()=>{a.bulkDelete?.(a.selectedIds),x({isOpen:!1,count:0})},disabled:a.isBulkDeleting,children:a.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Po(t){return({manager:a})=>{const{manager:r,config:n,onSave:s,onEdit:i,onToggleStatus:o}=t,l=a??r,c={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:i||n.onEdit};return e(_o,{manager:l,config:c,formSections:n.formSections,onSave:s,onToggleStatus:o,defaultSort:n.defaultSort})}}function Ro(e,t,a){return r=>{if(r.id){const t=a(r);e.updateEntity(r.id,t)}else{const a=t(r);e.createEntity(a)}}}function To(e,t,a={}){const r=[];return Object.keys(t).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const a=t[e],n={key:e,header:Io(e),label:Io(e),...Ao(e,a),sortable:!0,searchable:"string"==typeof a};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...a}}function Ao(e,t){const a=e.toLowerCase();return a.includes("email")?{type:"email",required:!0}:a.includes("phone")||a.includes("tel")?{type:"tel"}:a.includes("description")||a.includes("content")||a.includes("notes")?{type:"textarea"}:a.includes("status")||a.includes("type")||a.includes("category")?{type:"select",options:[]}:"boolean"==typeof t?{type:"boolean"}:"number"==typeof t?{type:"number"}:t instanceof Date?{type:"date"}:{type:"text"}}function Io(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Mo=r.forwardRef(({className:t,value:a,...r},n)=>e(Vt.Root,{ref:n,className:sr("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...r,children:e(Vt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(a||0)}%)`}})}));function Oo({steps:a,currentStepIndex:r,onStepClick:n,className:s}){return e("div",{className:sr("flex items-center justify-between mb-6",s),children:a.map((r,s)=>t("div",{className:"flex items-center flex-1",children:[e("div",{className:sr("flex items-center justify-center w-10 h-10 rounded-full border-2 transition-colors font-medium",r.isActive&&"border-primary bg-primary text-primary-foreground",r.isCompleted&&"border-primary bg-primary text-primary-foreground",!r.isActive&&!r.isCompleted&&"border-muted-foreground/30 text-muted-foreground bg-background",n&&!r.isDisabled&&"cursor-pointer hover:border-primary/50",r.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>n&&!r.isDisabled&&n(s),role:n&&!r.isDisabled?"button":void 0,tabIndex:n&&!r.isDisabled?0:void 0,"aria-label":`${r.label} - ${r.isCompleted?"Completo":r.isActive?"Atual":"Pendente"}`,children:r.isCompleted?e(T,{className:"w-5 h-5"}):s+1}),s<a.length-1&&e("div",{className:sr("flex-1 h-0.5 mx-2 transition-colors",r.isCompleted?"bg-primary":"bg-muted-foreground/30"),"aria-hidden":"true"})]},r.id))})}function Lo({steps:a,currentStepIndex:r,onStepClick:n,className:s}){return e("div",{className:sr("flex items-center gap-2 mb-6 overflow-x-auto",s),children:a.map((r,s)=>t("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[t("div",{className:sr("flex items-center gap-2 px-3 py-2 rounded-md transition-colors",r.isActive&&"bg-primary text-primary-foreground font-medium",r.isCompleted&&"bg-primary/10 text-primary",!r.isActive&&!r.isCompleted&&"bg-muted text-muted-foreground",n&&!r.isDisabled&&"cursor-pointer hover:bg-primary/20",r.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>n&&!r.isDisabled&&n(s),role:n&&!r.isDisabled?"button":void 0,tabIndex:n&&!r.isDisabled?0:void 0,"aria-label":`${r.label} - ${r.isCompleted?"Completo":r.isActive?"Atual":"Pendente"}`,children:[e("span",{className:"text-sm font-medium",children:s+1}),e("span",{className:"text-sm",children:r.label}),r.isCompleted&&e(T,{className:"w-4 h-4 ml-1"})]}),s<a.length-1&&e("span",{className:"text-muted-foreground","aria-hidden":"true",children:"/"})]},r.id))})}function Do({steps:a,currentStepIndex:r,className:n}){const s=a[r],i=(r+1)/a.length*100;return t("div",{className:sr("mb-6 space-y-2",n),children:[t("div",{className:"flex items-center justify-between text-sm",children:[t("span",{className:"text-muted-foreground",children:["Etapa ",r+1," de ",a.length]}),e("span",{className:"font-medium",children:s?.label})]}),e(Mo,{value:i,className:"h-2"})]})}function Fo({isFirstStep:r,isLastStep:n,canGoNext:s,canGoPrevious:i,isLoading:o,onPrevious:l,onNext:c,onSubmit:d,previousButtonText:u,nextButtonText:m,submitButtonText:h}){const{t:p}=Kn();return t(a,{children:[e("div",{children:i&&!r&&e(mr,{type:"button",variant:"outline",onClick:l,disabled:o,children:u||p("previous")})}),t("div",{className:"flex gap-2",children:[s&&!n&&e(mr,{type:"button",onClick:c,disabled:o,children:m||p("next")}),n&&e(mr,{type:"button",onClick:d,disabled:o,children:o?p("saving"):h||p("save")})]})]})}function jo({title:a,sections:r,initialData:s,onSubmit:i,onCancel:u,open:m,submitButtonText:h,isLoading:p=!1,usersData:f,showProgressIndicator:g=!0,progressType:v="stepper",validateOnNext:b=!0,allowSkipSections:y=!1,previousButtonText:w,nextButtonText:x,onStepChange:N,onStepValidationFail:k,renderProgressIndicator:C,renderButtons:S,currentStepIndex:E,onCurrentStepChange:_}){const[P,R]=d(0),T=E??P,A=_??R,I=l(null),[M,O]=d(null),L=c(e=>{I.current=e,O(e)},[]),D=o(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:F,errors:j,updateField:z,handleSubmit:$}=oo(D,s,void 0,m);n.useEffect(()=>{m&&A(0)},[m,A]);const U=c(()=>{const e=r[T];if(!e)return!0;const t=e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e),a={};let n=!0;return t.forEach(e=>{const t=F[e.name];if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length)&&(a[e.name]=`${e.label} é obrigatório`,n=!1),e.validation&&"function"==typeof e.validation){const r=e.validation(t,F);r&&(a[e.name]=r,n=!1)}}),!n&&k&&k(T,a),n},[r,T,F,k]),V=c(()=>{if(b&&!U())return;const e=T+1;e<r.length&&(A(e),N?.(e,r[e].id))},[T,r,b,U,A,N]),W=c(()=>{const e=T-1;e>=0&&(A(e),N?.(e,r[e].id))},[T,r,A,N]),B=c(()=>{let e=!0;for(let t=0;t<r.length;t++){r[t].fields.flatMap(e=>"group"===e.type?e.fields||[]:e).forEach(t=>{const a=F[t.name];t.required&&(""===a||null==a||Array.isArray(a)&&0===a.length)&&(e=!1)})}e&&$(i)()},[r,F,$,i]),H=o(()=>r.map((e,t)=>({index:t,id:e.id,label:e.label||e.id,isActive:t===T,isCompleted:t<T,isDisabled:e.disabled||!1})),[r,T]),q=0===T,K=T===r.length-1,G=o(()=>{if(!g)return null;if(C)return C(T,r.length,r);const t=y?e=>{A(e),N?.(e,r[e].id)}:void 0;switch(v){case"breadcrumb":return e(Lo,{steps:H,currentStepIndex:T,onStepClick:t});case"progressbar":return e(Do,{steps:H,currentStepIndex:T});default:return e(Oo,{steps:H,currentStepIndex:T,onStepClick:t})}},[g,C,v,H,T,r,y,A,N]),X=o(()=>{const t={isFirstStep:q,isLastStep:K,canGoNext:T<r.length-1,canGoPrevious:T>0,isLoading:p,onPrevious:W,onNext:V,onSubmit:B,previousButtonText:w,nextButtonText:x,submitButtonText:h};return S?S(t):e(Fo,{...t})},[q,K,T,r.length,p,W,V,B,w,x,h,S]),J=a=>{const r=(a.computedValue,F[a.name]),n=void 0!==r?r:"",s=j[a.name];switch(a.type){case"group":return t("div",{className:"space-y-2",children:[a.label&&e(gr,{className:"text-sm font-medium",children:a.label}),e("div",{className:sr("grid gap-4",1===a.columns&&"grid-cols-1",2===a.columns&&"grid-cols-1 md:grid-cols-2",3===a.columns&&"grid-cols-1 md:grid-cols-3",4===a.columns&&"grid-cols-1 md:grid-cols-4",!a.columns&&"grid-cols-1"),children:a.fields?.map(e=>J(e))})]},a.name);case"number":return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{id:a.name,type:"number",value:n,onChange:e=>z(a.name,""===e.target.value?"":Number(e.target.value)),placeholder:a.placeholder,disabled:a.disabled||void 0!==a.computedValue,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"textarea":return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(rn,{id:a.name,value:n,onChange:e=>z(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,rows:a.rows||3,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"select":return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),t(qr,{value:n,onValueChange:e=>z(a.name,e),children:[e(Xr,{className:s?"border-destructive":"",children:e(Gr,{placeholder:a.placeholder||`Selecione ${a.label}`})}),e(Yr,{children:a.options?.map(t=>e(en,{value:String(t.value),children:t.label},t.value))})]}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"multiselect":return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(Qn,{options:a.options||[],value:Array.isArray(n)?n:[],onChange:e=>z(a.name,e),placeholder:a.placeholder,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"color":case"color-picker":return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(co,{value:n,onChange:e=>z(a.name,e),label:""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"icon-picker":return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(po,{value:n,onChange:e=>z(a.name,e),label:""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"user-select":return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(vo,{value:n,onChange:e=>z(a.name,e),placeholder:a.placeholder,disabled:a.disabled}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name);case"custom":return a.render?t("div",{className:"space-y-2",children:[a.label&&t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),a.render({value:n,onChange:e=>z(a.name,e),error:s,disabled:a.disabled}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name):null;default:return t("div",{className:"space-y-2",children:[t(gr,{htmlFor:a.name,children:[a.label,a.required&&e("span",{className:"text-destructive ml-1",children:"*"})]}),e(pr,{id:a.name,type:a.type||"text",value:n,onChange:e=>z(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled||void 0!==a.computedValue,className:s?"border-destructive":""}),s&&e("p",{className:"text-sm text-destructive",children:s})]},a.name)}},Q=r[T];return e(Cr,{open:m,onOpenChange:u,children:t(Tr,{ref:L,className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e(Ar,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:e(Or,{className:"text-white",children:a})}),G,e("div",{className:"space-y-4 py-4",children:Q?.fields.map(e=>J(e))}),e("div",{className:"flex justify-between pt-4 border-t",children:X})]})})}Mo.displayName=Vt.Root.displayName;const zo=({children:r})=>{const{isAuthenticated:s,isLoading:i}=ei();if(n.useEffect(()=>{if(!s)return;const e=()=>{os.areAllTokensValid()||Qs.logout()};e();const t=setInterval(e,3e5);return()=>clearInterval(t)},[s]),n.useEffect(()=>{if(i)return;if(s)return;if(os.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),t=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,a=new URLSearchParams(t);if(e.has("access_token")||a.has("access_token"))return;const r=As();(async()=>{r?await Qs.loginDev():Qs.loginProd()})()},[s,i]),i)return e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(vr,{className:"w-full max-w-md",children:[e(br,{className:"text-center",children:e(yr,{className:"text-xl font-semibold",children:"Carregando..."})}),t(xr,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){const a=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return e("div",a?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(vr,{className:"w-full max-w-md",children:[e(br,{className:"text-center",children:e(yr,{className:"text-xl font-semibold",children:"Processando..."})}),t(xr,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(vr,{className:"w-full max-w-md",children:[e(br,{className:"text-center",children:e(yr,{className:"text-xl font-semibold",children:"Iniciando..."})}),t(xr,{className:"text-center",children:[e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e("p",{className:"text-muted-foreground",children:As()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e(a,{children:r})},$o=b("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Uo=r.forwardRef(({className:t,variant:a,...r},n)=>e("div",{ref:n,role:"alert",className:sr($o({variant:a}),t),...r}));Uo.displayName="Alert";const Vo=r.forwardRef(({className:t,...a},r)=>e("h5",{ref:r,className:sr("mb-1 font-medium leading-none tracking-tight",t),...a}));Vo.displayName="AlertTitle";const Wo=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("text-sm [&_p]:leading-relaxed",t),...a}));Wo.displayName="AlertDescription";const Bo=()=>{const{processCallback:r}=ei(),[n,s]=d(null),[i,o]=d(!1);u(()=>{(async()=>{try{if(await r()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");e?(localStorage.removeItem("auth_return_url"),window.location.href=e):window.location.href="/"}else s("Falha na autenticação. Tente novamente.")}catch(e){s(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[r]);const l=async()=>{o(!0),s(null);try{await r()||s("Falha na autenticação. Tente novamente.")}catch(e){s(e?.message||"Erro ao tentar novamente.")}finally{o(!1)}},c=()=>{window.location.href="/"};return e("div",n?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(vr,{className:"w-full max-w-md",children:[e(br,{className:"text-center",children:t(yr,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e(F,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),t(xr,{className:"space-y-4",children:[e(Uo,{variant:"destructive",children:e(Wo,{children:n})}),e("div",{className:"text-sm text-muted-foreground",children:e("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),t("div",{className:"flex gap-2",children:[e(mr,{onClick:l,disabled:i,className:"flex-1",children:t(a,i?{children:[e(ln,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[e(We,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e(mr,{onClick:c,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(vr,{className:"w-full max-w-md",children:[e(br,{className:"text-center",children:e(yr,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),t(xr,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(ln,{size:"lg"})}),e("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},Ho=()=>e("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(vr,{className:"w-full max-w-md",children:[e(br,{className:"text-center",children:e(yr,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),t(xr,{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e(mr,{onClick:async()=>{As()?await Qs.loginDev():Qs.loginProd()},className:"w-full",size:"lg",children:As()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),qo=s(void 0);function Ko({children:t,actions:a}){const[r,n]=d({}),[s,i]=d(a);return u(()=>{i(a)},[a]),e(qo.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:s,setHeaderActions:i},children:t})}function Go(){const e=i(qo);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Xo(e){const{setMetadata:t,clearMetadata:a}=Go();u(()=>(t(e),()=>a()),[e.title,e.subtitle,t,a])}function Jo(e){return{queryClient:e.queryClient||new At({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}const Qo=import.meta.env.VITE_SUPABASE_URL,Yo=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;let Zo=null;var el=Object.defineProperty,tl=(e,t,a)=>((e,t,a)=>t in e?el(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const al=new class{constructor(){tl(this,"cache",{}),tl(this,"cacheTimestamps",new Map),tl(this,"CACHE_TTL",3e5),tl(this,"loadingPromises",new Map)}isCacheValid(e){const t=this.cacheTimestamps.get(e);return!!t&&Date.now()-t<this.CACHE_TTL}async loadTranslations(e){if(this.isCacheValid(e))return this.cache[e]||{};const t=this.loadingPromises.get(e);if(t)return t;const a=this.fetchTranslations(e);this.loadingPromises.set(e,a);try{return await a}finally{this.loadingPromises.delete(e)}}async fetchTranslations(e){try{const t=(!Zo&&Qo&&Yo&&(Zo=_t(Qo,Yo,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1}})),Zo),{data:a,error:r}=await t.schema("common").from("translations").select("key, pt, en, es").eq("is_removed",!1);if(r)return"42501"===r.code||"PGRST301"===r.code||r.message?.includes("permission denied")||r.message?.includes("No suitable key"),{};const n={};return a?.forEach(t=>{let a;a="pt-BR"===e?t.pt:"en-US"===e?t.en||t.pt:"es-ES"===e&&t.es||t.pt,a&&(n[t.key]=a)}),this.cache[e]=n,this.cacheTimestamps.set(e,Date.now()),n}catch(t){return{}}}async upsertTranslation(e,t,a,r){const n=vs(),{error:s}=await n.schema("common").from("translations").upsert({key:e,pt:t,en:a,es:r},{onConflict:"key"});if(s)throw s;this.clearCache()}async bulkUpsertTranslations(e){const t=vs(),{error:a}=await t.schema("common").from("translations").upsert(e.map(e=>({key:e.key,pt:e.pt,en:e.en,es:e.es})),{onConflict:"key"});if(a)throw a;this.clearCache()}clearCache(){this.cache={},this.cacheTimestamps.clear()}clearCacheForLocale(e){delete this.cache[e],this.cacheTimestamps.delete(e)}};var rl=Object.defineProperty,nl=(e,t,a)=>((e,t,a)=>t in e?rl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const sl="true"===import.meta.env.VITE_I18N_DEBUG_MODE;rr.use(new class{constructor(e=!1){nl(this,"type","backend"),nl(this,"isDebugMode"),nl(this,"cache",new Map),nl(this,"loadingPromises",new Map),this.isDebugMode=e}read(e,t,a){if(this.cache.has(e))return void a(null,this.cache.get(e));if(this.loadingPromises.has(e))return void this.loadingPromises.get(e).then(()=>{a(null,this.cache.get(e)||{})});const r=al.loadTranslations(e).then(t=>{if(this.isDebugMode){const a={};Object.keys(t).forEach(e=>{a[e]=`[${e} ✅]`}),this.cache.set(e,a)}else this.cache.set(e,t)}).catch(t=>{this.cache.set(e,{})}).finally(()=>{this.loadingPromises.delete(e)});this.loadingPromises.set(e,r),r.then(()=>{a(null,this.cache.get(e)||{})})}create(e,t,a,r){}}(sl)).use(Ln).init({fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:(e,t)=>sl?`[${e} ❌]`:`[⚠️ ${e}]`});const il=new class{async getUserPreferences(e,t){if(!os.areAllTokensValid())return null;const a=vs();try{const{data:r,error:n}=await a.schema("common").from("user_preferences").select("*").eq("id_user",e).eq("alias",t).maybeSingle();if(n)return"PGRST116"===n.code?this.createDefaultPreferences(e,t):("42501"===n.code||"PGRST301"===n.code||n.message?.includes("permission denied"),null);if(!r)return this.createDefaultPreferences(e,t);const s=r;return{locale:s.locale,timezone:s.timezone,datetimeFormat:s.datetime_format}}catch(r){return null}}async createDefaultPreferences(e,t){const a=vs(),r={id_user:e,locale:"pt-BR",timezone:"America/Sao_Paulo",datetime_format:"dd/MM/yyyy HH:mm",alias:t};try{const{data:e,error:t}=await a.schema("common").from("user_preferences").insert(r).select().single();if(t)throw t;const n=e;return{locale:n.locale,timezone:n.timezone,datetimeFormat:n.datetime_format}}catch(n){throw n}}async updatePreferences(e,t,a){const r=vs();try{const{error:n}=await r.schema("common").from("user_preferences").update(a).eq("id_user",e).eq("alias",t);if(n)throw n}catch(n){throw n}}},ol=s(void 0),ll=({children:t})=>{const{user:a,alias:r}=ei(),[n,s]=d({locale:"pt-BR",timezone:"America/Sao_Paulo",datetimeFormat:"dd/MM/yyyy HH:mm"}),[i,o]=d(!0);u(()=>{(async()=>{if(a?.id&&r)try{const e=await il.getUserPreferences(a.id,r);e&&(s({locale:e.locale,timezone:e.timezone,datetimeFormat:e.datetimeFormat}),await rr.changeLanguage(e.locale),localStorage.setItem("i18nextLng",e.locale))}catch(e){}finally{o(!1)}else o(!1)})()},[a?.id,r]);const l=c(async e=>{if(a?.id&&r)try{await il.updatePreferences(a.id,r,{locale:e}),s(t=>({...t,locale:e})),await rr.changeLanguage(e),localStorage.setItem("i18nextLng",e)}catch(t){throw t}},[a?.id,r]),m=c(async e=>{if(a?.id&&r)try{await il.updatePreferences(a.id,r,{timezone:e}),s(t=>({...t,timezone:e}))}catch(t){throw t}},[a?.id,r]),h=c(async e=>{if(a?.id&&r)try{await il.updatePreferences(a.id,r,{datetime_format:e}),s(t=>({...t,datetimeFormat:e}))}catch(t){throw t}},[a?.id,r]);return e(ol.Provider,{value:{...n,setLocale:l,setTimezone:m,setDatetimeFormat:h,isLoading:i},children:t})},cl=()=>{const e=i(ol);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e};function dl({children:r}){const{ready:n}=Kn(),[s,i]=d(!0);return u(()=>{n&&s&&i(!1)},[n,s]),s&&!n?e("div",{className:"flex items-center justify-center min-h-screen bg-background",children:t("div",{className:"flex flex-col items-center gap-4",children:[e(ln,{size:"lg"}),e("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Carregando traduções..."})]})}):e(a,{children:r})}const ul=Wt.Root,ml=Wt.CollapsibleTrigger,hl=Wt.CollapsibleContent;var pl=Object.defineProperty,fl=(e,t,a)=>((e,t,a)=>t in e?pl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);class gl extends p{constructor(e){super(e),fl(this,"copyErrorDetails",()=>{const e=ds.getErrors().slice(0,2),t=`\n=== ERRO ATUAL ===\n${this.state.error?.message||"Erro desconhecido"}\n\nStack Trace:\n${this.state.error?.stack||"Não disponível"}\n\n=== ÚLTIMOS ERROS ===\n${e.map((e,t)=>`${t+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(t),C.success("Detalhes copiados!",{description:"Os detalhes do erro foram copiados para a área de transferência."})}),this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,t){if(import.meta.env.DEV)throw e;ds.handleError(e,!1),this.setState({errorInfo:t})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const a=ds.getErrors().slice(0,2);return e("div",{className:"flex items-center justify-center min-h-screen p-4",children:t(vr,{className:"w-full max-w-2xl",children:[t(br,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e(Be,{className:"h-12 w-12 text-destructive"})}),e(yr,{children:"Algo deu errado"})]}),t(xr,{className:"space-y-4",children:[e("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),t(ul,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e(ml,{asChild:!0,children:t(mr,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e(P,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),t(hl,{className:"mt-4 space-y-4",children:[t("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[t("div",{children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),t("div",{className:"text-sm space-y-2",children:[e("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e(uo,{className:"h-32 w-full rounded border bg-muted p-2",children:e("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),a.length>0&&t("div",{className:"pt-3 border-t",children:[e("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e("div",{className:"space-y-2",children:a.map((a,r)=>e("div",{className:"text-sm p-2 rounded bg-muted/50",children:t("div",{className:"flex items-start gap-2",children:[t("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),t("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 flex-wrap",children:t("span",{className:"text-xs text-muted-foreground",children:["[",new Date(a.timestamp).toLocaleTimeString(),"]"]})}),e("p",{className:"text-sm break-words",children:a.message})]})]})},a.id))})]})]}),t(mr,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e(he,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e(mr,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}function vl({children:t,queryClient:a}){const r=a??new At({defaultOptions:{queries:{staleTime:3e5,retry:1}}});return e(gl,{children:e(Gn,{i18n:rr,children:e(It,{client:r,children:e(Zs,{children:e(ll,{children:e(dl,{children:t})})})})})})}const bl=Bt.Root,yl=r.forwardRef(({className:t,...a},r)=>e(Bt.Item,{ref:r,className:sr("border-b",t),...a}));yl.displayName="AccordionItem";const wl=r.forwardRef(({className:a,children:r,...n},s)=>e(Bt.Header,{className:"flex",children:t(Bt.Trigger,{ref:s,className:sr("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",a),...n,children:[r,e(P,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));wl.displayName=Bt.Trigger.displayName;const xl=r.forwardRef(({className:t,children:a,...r},n)=>e(Bt.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:e("div",{className:sr("pb-4 pt-0",t),children:a})}));xl.displayName=Bt.Content.displayName;const Nl=Ht.Root,kl=Ht.Trigger,Cl=Ht.Portal,Sl=r.forwardRef(({className:t,...a},r)=>e(Ht.Overlay,{className:sr("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a,ref:r}));Sl.displayName=Ht.Overlay.displayName;const El=r.forwardRef(({className:a,...r},n)=>t(Cl,{children:[e(Sl,{}),e(Ht.Content,{ref:n,className:sr("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...r})]}));El.displayName=Ht.Content.displayName;const _l=({className:t,...a})=>e("div",{className:sr("flex flex-col space-y-2 text-center sm:text-left",t),...a});_l.displayName="AlertDialogHeader";const Pl=({className:t,...a})=>e("div",{className:sr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});Pl.displayName="AlertDialogFooter";const Rl=r.forwardRef(({className:t,...a},r)=>e(Ht.Title,{ref:r,className:sr("text-lg font-semibold",t),...a}));Rl.displayName=Ht.Title.displayName;const Tl=r.forwardRef(({className:t,...a},r)=>e(Ht.Description,{ref:r,className:sr("text-sm text-muted-foreground",t),...a}));Tl.displayName=Ht.Description.displayName;const Al=r.forwardRef(({className:t,...a},r)=>e(Ht.Action,{ref:r,className:sr(ur(),t),...a}));Al.displayName=Ht.Action.displayName;const Il=r.forwardRef(({className:t,...a},r)=>e(Ht.Cancel,{ref:r,className:sr(ur({variant:"outline"}),"mt-2 sm:mt-0",t),...a}));Il.displayName=Ht.Cancel.displayName;const Ml=r.forwardRef(({className:t,...a},r)=>e(qt.Root,{ref:r,className:sr("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...a}));Ml.displayName=qt.Root.displayName;const Ol=r.forwardRef(({className:t,...a},r)=>e(qt.Image,{ref:r,className:sr("aspect-square h-full w-full",t),...a}));Ol.displayName=qt.Image.displayName;const Ll=r.forwardRef(({className:t,...a},r)=>e(qt.Fallback,{ref:r,className:sr("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...a}));Ll.displayName=qt.Fallback.displayName;const Dl=r.forwardRef(({...t},a)=>e("nav",{ref:a,"aria-label":"breadcrumb",...t}));Dl.displayName="Breadcrumb";const Fl=r.forwardRef(({className:t,...a},r)=>e("ol",{ref:r,className:sr("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",t),...a}));Fl.displayName="BreadcrumbList";const jl=r.forwardRef(({className:t,...a},r)=>e("li",{ref:r,className:sr("inline-flex items-center gap-1.5",t),...a}));jl.displayName="BreadcrumbItem";const zl=r.forwardRef(({asChild:t,className:a,...r},n)=>e(t?g:"a",{ref:n,className:sr("transition-colors hover:text-foreground",a),...r}));zl.displayName="BreadcrumbLink";const $l=r.forwardRef(({className:t,...a},r)=>e("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:sr("font-normal text-foreground",t),...a}));$l.displayName="BreadcrumbPage";const Ul=({children:t,className:a,...r})=>e("li",{role:"presentation","aria-hidden":"true",className:sr("[&>svg]:h-3.5 [&>svg]:w-3.5",a),...r,children:t??e($,{})});Ul.displayName="BreadcrumbSeparator";const Vl=({className:a,...r})=>t("span",{role:"presentation","aria-hidden":"true",className:sr("flex h-9 w-9 items-center justify-center",a),...r,children:[e(He,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Mais"})]});Vl.displayName="BreadcrumbEllipsis";const Wl=b("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),Bl=r.forwardRef(({className:t,orientation:a,...r},n)=>e("div",{ref:n,className:sr(Wl({orientation:a}),t),...r}));function Hl(e){return(t={})=>{const a=t.width?String(t.width):e.defaultWidth;return e.formats[a]||e.formats[e.defaultWidth]}}function ql(e){return(t,a)=>{let r;if("formatting"===(a?.context?String(a.context):"standalone")&&e.formattingValues){const t=e.defaultFormattingWidth||e.defaultWidth,n=a?.width?String(a.width):t;r=e.formattingValues[n]||e.formattingValues[t]}else{const t=e.defaultWidth,n=a?.width?String(a.width):e.defaultWidth;r=e.values[n]||e.values[t]}return r[e.argumentCallback?e.argumentCallback(t):t]}}function Kl(e){return(t,a={})=>{const r=a.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],s=t.match(n);if(!s)return null;const i=s[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,t){for(let a=0;a<e.length;a++)if(t(e[a]))return a;return}(o,e=>e.test(i)):function(e,t){for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return a;return}(o,e=>e.test(i));let c;c=e.valueCallback?e.valueCallback(l):l,c=a.valueCallback?a.valueCallback(c):c;return{value:c,rest:t.slice(i.length)}}}function Gl(e){return(t,a={})=>{const r=t.match(e.matchPattern);if(!r)return null;const n=r[0],s=t.match(e.parsePattern);if(!s)return null;let i=e.valueCallback?e.valueCallback(s[0]):s[0];i=a.valueCallback?a.valueCallback(i):i;return{value:i,rest:t.slice(n.length)}}}Bl.displayName="ButtonGroup";const Xl={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Jl={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Ql={ordinalNumber:(e,t)=>{const a=Number(e),r=a%100;if(r>20||r<10)switch(r%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},era:ql({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:ql({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:ql({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:ql({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:ql({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},Yl={ordinalNumber:Gl({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Kl({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:Kl({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Kl({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:Kl({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Kl({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},Zl={code:"en-US",formatDistance:(e,t,a)=>{let r;const n=Xl[e];return r="string"==typeof n?n:1===t?n.one:n.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"in "+r:r+" ago":r},formatLong:{date:Hl({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Hl({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:Hl({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,t,a,r)=>Jl[e],localize:Ql,match:Yl,options:{weekStartsOn:0,firstWeekContainsDate:1}},ec={lessThanXSeconds:{one:"menos de un segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"medio minuto",lessThanXMinutes:{one:"menos de un minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"alrededor de 1 hora",other:"alrededor de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 día",other:"{{count}} días"},aboutXWeeks:{one:"alrededor de 1 semana",other:"alrededor de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"alrededor de 1 mes",other:"alrededor de {{count}} meses"},xMonths:{one:"1 mes",other:"{{count}} meses"},aboutXYears:{one:"alrededor de 1 año",other:"alrededor de {{count}} años"},xYears:{one:"1 año",other:"{{count}} años"},overXYears:{one:"más de 1 año",other:"más de {{count}} años"},almostXYears:{one:"casi 1 año",other:"casi {{count}} años"}},tc={date:Hl({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:Hl({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Hl({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},ac={lastWeek:"'el' eeee 'pasado a la' p",yesterday:"'ayer a la' p",today:"'hoy a la' p",tomorrow:"'mañana a la' p",nextWeek:"eeee 'a la' p",other:"P"},rc={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},nc={ordinalNumber:(e,t)=>Number(e)+"º",era:ql({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:ql({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>Number(e)-1}),month:ql({values:{narrow:["e","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],wide:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},defaultWidth:"wide"}),day:ql({values:{narrow:["d","l","m","m","j","v","s"],short:["do","lu","ma","mi","ju","vi","sá"],abbreviated:["dom","lun","mar","mié","jue","vie","sáb"],wide:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"]},defaultWidth:"wide"}),dayPeriod:ql({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"}},defaultFormattingWidth:"wide"})},sc={ordinalNumber:Gl({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Kl({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|a\.?\s?e\.?\s?c\.?|d\.?\s?c\.?|e\.?\s?c\.?)/i,wide:/^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^(antes de cristo|antes de la era com[uú]n)/i,/^(despu[eé]s de cristo|era com[uú]n)/i]},defaultParseWidth:"any"}),quarter:Kl({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Kl({matchPatterns:{narrow:/^[efmajsond]/i,abbreviated:/^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,wide:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^e/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^en/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i]},defaultParseWidth:"any"}),day:Kl({matchPatterns:{narrow:/^[dlmjvs]/i,short:/^(do|lu|ma|mi|ju|vi|s[áa])/i,abbreviated:/^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,wide:/^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^do/i,/^lu/i,/^ma/i,/^mi/i,/^ju/i,/^vi/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Kl({matchPatterns:{narrow:/^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,any:/^([ap]\.?\s?m\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn/i,noon:/^md/i,morning:/mañana/i,afternoon:/tarde/i,evening:/tarde/i,night:/noche/i}},defaultParseWidth:"any"})},ic={code:"es",formatDistance:(e,t,a)=>{let r;const n=ec[e];return r="string"==typeof n?n:1===t?n.one:n.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"en "+r:"hace "+r:r},formatLong:tc,formatRelative:(e,t,a,r)=>1!==t.getHours()?rc[e]:ac[e],localize:nc,match:sc,options:{weekStartsOn:1,firstWeekContainsDate:1}},oc={lessThanXSeconds:{one:"menos de um segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"meio minuto",lessThanXMinutes:{one:"menos de um minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"cerca de 1 hora",other:"cerca de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 dia",other:"{{count}} dias"},aboutXWeeks:{one:"cerca de 1 semana",other:"cerca de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"cerca de 1 mês",other:"cerca de {{count}} meses"},xMonths:{one:"1 mês",other:"{{count}} meses"},aboutXYears:{one:"cerca de 1 ano",other:"cerca de {{count}} anos"},xYears:{one:"1 ano",other:"{{count}} anos"},overXYears:{one:"mais de 1 ano",other:"mais de {{count}} anos"},almostXYears:{one:"quase 1 ano",other:"quase {{count}} anos"}},lc={date:Hl({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/yyyy"},defaultWidth:"full"}),time:Hl({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Hl({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},cc={lastWeek:e=>{const t=e.getDay();return"'"+(0===t||6===t?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},dc={ordinalNumber:(e,t)=>{const a=Number(e);return"week"===t?.unit?a+"ª":a+"º"},era:ql({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:ql({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:ql({values:{narrow:["j","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["jan","fev","mar","abr","mai","jun","jul","ago","set","out","nov","dez"],wide:["janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro"]},defaultWidth:"wide"}),day:ql({values:{narrow:["D","S","T","Q","Q","S","S"],short:["dom","seg","ter","qua","qui","sex","sab"],abbreviated:["domingo","segunda","terça","quarta","quinta","sexta","sábado"],wide:["domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado"]},defaultWidth:"wide"}),dayPeriod:ql({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"manhã",afternoon:"tarde",evening:"tarde",night:"noite"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},abbreviated:{am:"AM",pm:"PM",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"},wide:{am:"a.m.",pm:"p.m.",midnight:"meia-noite",noon:"meio-dia",morning:"da manhã",afternoon:"da tarde",evening:"da tarde",night:"da noite"}},defaultFormattingWidth:"wide"})},uc={ordinalNumber:Gl({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Kl({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|d\.?\s?c\.?)/i,wide:/^(antes de cristo|depois de cristo)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^antes de cristo/i,/^depois de cristo/i]},defaultParseWidth:"any"}),quarter:Kl({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^T[1234]/i,wide:/^[1234](º)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Kl({matchPatterns:{narrow:/^[jfmajsond]/i,abbreviated:/^(jan|fev|mar|abr|mai|jun|jul|ago|set|out|nov|dez)/i,wide:/^(janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^fev/i,/^mar/i,/^abr/i,/^mai/i,/^jun/i,/^jul/i,/^ago/i,/^set/i,/^out/i,/^nov/i,/^dez/i]},defaultParseWidth:"any"}),day:Kl({matchPatterns:{narrow:/^(dom|[23456]ª?|s[aá]b)/i,short:/^(dom|[23456]ª?|s[aá]b)/i,abbreviated:/^(dom|seg|ter|qua|qui|sex|s[aá]b)/i,wide:/^(domingo|(segunda|ter[cç]a|quarta|quinta|sexta)([- ]feira)?|s[aá]bado)/i},defaultMatchWidth:"wide",parsePatterns:{short:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],narrow:[/^d/i,/^2/i,/^3/i,/^4/i,/^5/i,/^6/i,/^s[aá]/i],any:[/^d/i,/^seg/i,/^t/i,/^qua/i,/^qui/i,/^sex/i,/^s[aá]b/i]},defaultParseWidth:"any"}),dayPeriod:Kl({matchPatterns:{narrow:/^(a|p|mn|md|(da) (manhã|tarde|noite))/i,any:/^([ap]\.?\s?m\.?|meia[-\s]noite|meio[-\s]dia|(da) (manhã|tarde|noite))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn|^meia[-\s]noite/i,noon:/^md|^meio[-\s]dia/i,morning:/manhã/i,afternoon:/tarde/i,evening:/tarde/i,night:/noite/i}},defaultParseWidth:"any"})},mc={code:"pt-BR",formatDistance:(e,t,a)=>{let r;const n=oc[e];return r="string"==typeof n?n:1===t?n.one:n.other.replace("{{count}}",String(t)),a?.addSuffix?a.comparison&&a.comparison>0?"em "+r:"há "+r:r},formatLong:lc,formatRelative:(e,t,a,r)=>{const n=cc[e];return"function"==typeof n?n(t):n},localize:dc,match:uc,options:{weekStartsOn:0,firstWeekContainsDate:1}};function hc({className:t,classNames:a,showOutsideDays:r=!0,...n}){return e(Kt,{showOutsideDays:r,className:sr("p-3 pointer-events-auto",t),locale:mc,classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:sr(ur({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:sr(ur({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...a},components:{IconLeft:({...t})=>e(ke,{className:"h-4 w-4"}),IconRight:({...t})=>e($,{className:"h-4 w-4"})},...n})}hc.displayName="Calendar";const pc={Root:function({children:t,className:a}){return e("div",{className:sr("space-y-4",a),children:t})},Item:function({children:t,onClick:a,className:r}){return e(vr,{className:sr("transition-colors",a&&"cursor-pointer hover:bg-muted/50",r),onClick:a,children:e(xr,{className:"p-4",children:t})})},Field:function({label:a,value:r,className:n}){return t("div",{className:sr("flex justify-between items-center text-sm",n),children:[t("span",{className:"text-muted-foreground font-medium",children:[a,":"]}),e("span",{className:"text-foreground",children:r})]})}};function fc({date:a,onDateChange:r,placeholder:n="Pick a date",disabled:s=!1,className:i,disabledDates:o}){return t(un,{children:[e(mn,{asChild:!0,children:t(mr,{variant:"outline",disabled:s,className:sr("w-full justify-start text-left font-normal",!a&&"text-muted-foreground",i),children:[e(Me,{className:"mr-2 h-4 w-4"}),a?k(a,"PPP"):e("span",{children:n})]})}),e(hn,{className:"w-auto p-0",align:"start",children:e(hc,{mode:"single",selected:a,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const gc=({shouldScaleBackground:t=!0,...a})=>e(Gt.Root,{shouldScaleBackground:t,...a});gc.displayName="Drawer";const vc=Gt.Trigger,bc=Gt.Portal,yc=Gt.Close,wc=r.forwardRef(({className:t,...a},r)=>e(Gt.Overlay,{ref:r,className:sr("fixed inset-0 z-50 bg-black/80",t),...a}));wc.displayName=Gt.Overlay.displayName;const xc=r.forwardRef(({className:a,children:r,...n},s)=>t(bc,{children:[e(wc,{}),t(Gt.Content,{ref:s,className:sr("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",a),...n,children:[e("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));xc.displayName="DrawerContent";const Nc=({className:t,...a})=>e("div",{className:sr("grid gap-1.5 p-4 text-center sm:text-left",t),...a});Nc.displayName="DrawerHeader";const kc=({className:t,...a})=>e("div",{className:sr("mt-auto flex flex-col gap-2 p-4",t),...a});kc.displayName="DrawerFooter";const Cc=r.forwardRef(({className:t,...a},r)=>e(Gt.Title,{ref:r,className:sr("text-lg font-semibold leading-none tracking-tight",t),...a}));Cc.displayName=Gt.Title.displayName;const Sc=r.forwardRef(({className:t,...a},r)=>e(Gt.Description,{ref:r,className:sr("text-sm text-muted-foreground",t),...a}));Sc.displayName=Gt.Description.displayName;const Ec={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6","auto-fit":"grid-cols-[repeat(auto-fit,minmax(250px,1fr))]","auto-fill":"grid-cols-[repeat(auto-fill,minmax(250px,1fr))]"},_c={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Pc({children:t,cols:a="auto-fit",gap:r="md",className:n}){return e("div",{className:sr("grid",Ec[a],_c[r],n),children:t})}const Rc=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-slot":"input-group",className:sr("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",t),...a}));Rc.displayName="InputGroup";const Tc=b("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),Ac=r.forwardRef(({className:t,align:a,...r},n)=>e("div",{ref:n,"data-slot":"input-group-addon",className:sr(Tc({align:a}),t),...r}));Ac.displayName="InputGroupAddon";const Ic=b("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),Mc=r.forwardRef(({className:t,size:a,variant:r="ghost",...n},s)=>e(mr,{ref:s,"data-slot":"input-group-button",variant:r,className:sr(Ic({size:a}),"rounded-none first:rounded-l-md last:rounded-r-md",t),...n}));Mc.displayName="InputGroupButton";const Oc=r.forwardRef(({className:t,...a},r)=>e(pr,{ref:r,"data-slot":"input-group-control",className:sr("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));Oc.displayName="InputGroupInput";const Lc=r.forwardRef(({className:t,...a},r)=>e(rn,{ref:r,"data-slot":"input-group-control",className:sr("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));Lc.displayName="InputGroupTextarea";const Dc=r.forwardRef(({className:t,...a},r)=>e("h1",{ref:r,className:sr("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",t),...a}));Dc.displayName="H1";const Fc=r.forwardRef(({className:t,...a},r)=>e("h2",{ref:r,className:sr("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",t),...a}));Fc.displayName="H2";const jc=r.forwardRef(({className:t,...a},r)=>e("h3",{ref:r,className:sr("scroll-m-20 text-2xl font-semibold tracking-tight",t),...a}));jc.displayName="H3";const zc=r.forwardRef(({className:t,...a},r)=>e("h4",{ref:r,className:sr("scroll-m-20 text-xl font-semibold tracking-tight",t),...a}));zc.displayName="H4";const $c=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:sr("leading-7 [&:not(:first-child)]:mt-6",t),...a}));$c.displayName="P";const Uc=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:sr("text-xl text-muted-foreground",t),...a}));Uc.displayName="Lead";const Vc=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,className:sr("text-lg font-semibold",t),...a}));Vc.displayName="Large";const Wc=r.forwardRef(({className:t,...a},r)=>e("small",{ref:r,className:sr("text-sm font-medium leading-none",t),...a}));Wc.displayName="Small";const Bc=r.forwardRef(({className:t,...a},r)=>e("p",{ref:r,className:sr("text-sm text-muted-foreground",t),...a}));Bc.displayName="Muted";const Hc=r.forwardRef(({className:t,...a},r)=>e("code",{ref:r,className:sr("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",t),...a}));Hc.displayName="InlineCode";const qc=r.forwardRef(({className:t,...a},r)=>e("blockquote",{ref:r,className:sr("mt-6 border-l-2 pl-6 italic",t),...a}));qc.displayName="Blockquote";const Kc=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,className:sr("my-6 ml-6 list-disc [&>li]:mt-2",t),...a}));function Gc({items:r,maxItems:n=3,className:s}){const i=r.length>n?[r[0],...r.slice(-(n-1))]:r,o=r.length>n;return e(Dl,{className:s,children:e(Fl,{children:i.map((r,n)=>{const s=o&&1===n;return t(jl,{children:[!(0===n)&&e(Ul,{}),s&&t(a,{children:[e(Vl,{}),e(Ul,{})]}),r.isCurrentPage?e($l,{children:r.label}):e(zl,{href:r.href,children:r.label})]},r.label)})})})}function Xc(){const e=Ot();return(()=>{const t=e.pathname.split("/").filter(Boolean),a=[{label:"Exemplos",href:"/"}];let r="";return t.forEach((e,n)=>{r+=`/${e}`;const s=n===t.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");a.push({label:i,href:s?void 0:r,isCurrentPage:s})}),a})()}Kc.displayName="List";const Jc=({className:t,...a})=>e("nav",{role:"navigation","aria-label":"pagination",className:sr("mx-auto flex w-full justify-center",t),...a});Jc.displayName="Pagination";const Qc=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,className:sr("flex flex-row items-center gap-1",t),...a}));Qc.displayName="PaginationContent";const Yc=r.forwardRef(({className:t,...a},r)=>e("li",{ref:r,className:sr("",t),...a}));Yc.displayName="PaginationItem";const Zc=({className:t,isActive:a,size:r="icon",...n})=>e("a",{"aria-current":a?"page":void 0,className:sr(ur({variant:a?"outline":"ghost",size:r}),t),...n});Zc.displayName="PaginationLink";const ed=({className:a,...r})=>t(Zc,{"aria-label":"Go to previous page",size:"default",className:sr("gap-1 pl-2.5",a),...r,children:[e(ke,{className:"h-4 w-4"}),e("span",{children:"Previous"})]});ed.displayName="PaginationPrevious";const td=({className:a,...r})=>t(Zc,{"aria-label":"Go to next page",size:"default",className:sr("gap-1 pr-2.5",a),...r,children:[e("span",{children:"Next"}),e($,{className:"h-4 w-4"})]});td.displayName="PaginationNext";const ad=({className:a,...r})=>t("span",{"aria-hidden":!0,className:sr("flex h-9 w-9 items-center justify-center",a),...r,children:[e(He,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"More pages"})]});ad.displayName="PaginationEllipsis";const rd=r.forwardRef(({className:t,...a},r)=>e(Xt.Root,{className:sr("grid gap-2",t),...a,ref:r}));rd.displayName=Xt.Root.displayName;const nd=r.forwardRef(({className:t,...a},r)=>e(Xt.Item,{ref:r,className:sr("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...a,children:e(Xt.Indicator,{className:"flex items-center justify-center",children:e(U,{className:"h-2.5 w-2.5 fill-current text-current"})})}));nd.displayName=Xt.Item.displayName;const sd=vt.Root,id=vt.Trigger,od=vt.Close,ld=vt.Portal,cd=r.forwardRef(({className:t,...a},r)=>e(vt.Overlay,{className:sr("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...a,ref:r}));cd.displayName=vt.Overlay.displayName;const dd=b("fixed z-50 flex flex-col bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),ud=r.forwardRef(({side:a="right",className:r,children:n,...s},i)=>t(ld,{children:[e(cd,{}),t(vt.Content,{ref:i,className:sr(dd({side:a}),r),...s,children:[n,t(vt.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[e(_,{className:"h-4 w-4"}),e("span",{className:"sr-only",children:"Close"})]})]})]}));ud.displayName=vt.Content.displayName;const md=({className:a,showSeparator:r=!1,children:n,...s})=>t("div",{className:sr("flex flex-col flex-shrink-0",a),...s,children:[e("div",{className:"flex flex-col text-left",children:n}),r&&e(kr,{className:"mt-2"})]});md.displayName="SheetHeader";const hd=({className:t,...a})=>e("div",{className:sr("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",t),...a});hd.displayName="SheetBody";const pd=({className:a,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[e(kr,{className:"mb-4"}),e("div",{className:sr("flex flex-row justify-end gap-2",a),...n,children:r})]});pd.displayName="SheetFooter";const fd=r.forwardRef(({className:t,...a},r)=>e(vt.Title,{ref:r,className:sr("text-lg font-semibold text-foreground",t),...a}));fd.displayName=vt.Title.displayName;const gd=r.forwardRef(({className:t,...a},r)=>e(vt.Description,{ref:r,className:sr("text-sm text-muted-foreground",t),...a}));gd.displayName=vt.Description.displayName;const vd="sidebar:state",bd=r.createContext(null);function yd(){const e=r.useContext(bd);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const wd=r.forwardRef(({defaultOpen:t=!0,open:a,onOpenChange:n,className:s,style:i,children:o,...l},c)=>{const[d,u]=r.useState(!1);r.useEffect(()=>{const e=()=>u(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[m,h]=r.useState(!1),[p,f]=r.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(vd);return null!==e?"true"===e:t}return t}),g=a??p,v=r.useCallback(e=>{const t="function"==typeof e?e(g):e;n?n(t):f(t),"undefined"!=typeof window&&localStorage.setItem(vd,String(t))},[n,g]),b=r.useCallback(()=>d?h(e=>!e):v(e=>!e),[d,v,h]);r.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),b())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[b]);const y=g?"expanded":"collapsed",w=r.useMemo(()=>({state:y,open:g,setOpen:v,isMobile:d,openMobile:m,setOpenMobile:h,toggleSidebar:b}),[y,g,v,d,m,h,b]);return e(bd.Provider,{value:w,children:e(bi,{delayDuration:0,children:e("div",{className:sr("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",s),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...i},ref:c,...l,children:o})})})});wd.displayName="SidebarProvider";const xd=r.forwardRef(({side:a="left",variant:r="sidebar",collapsible:n="offcanvas",className:s,children:i,...o},l)=>{const{isMobile:c,state:d,openMobile:u,setOpenMobile:m}=yd();return"none"===n?e("div",{className:sr("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",s),ref:l,...o,children:i}):c?e(sd,{open:u,onOpenChange:m,...o,children:t(ud,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:a,children:[e(fd,{className:"sr-only",children:"Menu de Navegação"}),e("div",{className:"flex h-full w-full flex-col",children:i})]})}):t("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?n:"","data-variant":r,"data-side":a,children:[e("div",{className:sr("duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e("div",{className:sr("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===a?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",s),...o,children:e("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow bg-white",children:i})})]})});xd.displayName="Sidebar";const Nd=r.forwardRef(({className:a,onClick:r,...n},s)=>{const{toggleSidebar:i}=yd();return t(mr,{ref:s,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:sr("h-7 w-7",a),onClick:e=>{r?.(e),i()},...n,children:[e(qe,{}),e("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Nd.displayName="SidebarTrigger";const kd=r.forwardRef(({className:t,...a},r)=>{const{toggleSidebar:n}=yd();return e("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:sr("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",t),...a})});kd.displayName="SidebarRail";const Cd=r.forwardRef(({className:t,...a},r)=>e("main",{ref:r,className:sr("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",t),...a}));Cd.displayName="SidebarInset";const Sd=r.forwardRef(({className:t,...a},r)=>e(pr,{ref:r,"data-sidebar":"input",className:sr("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),...a}));Sd.displayName="SidebarInput";const Ed=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"header",className:sr("flex flex-col gap-2 p-2",t),...a}));Ed.displayName="SidebarHeader";const _d=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"footer",className:sr("flex flex-col gap-2 p-2",t),...a}));_d.displayName="SidebarFooter";const Pd=r.forwardRef(({className:t,...a},r)=>e(kr,{ref:r,"data-sidebar":"separator",className:sr("mx-2 w-auto bg-sidebar-border",t),...a}));Pd.displayName="SidebarSeparator";const Rd=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"content",className:sr("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...a}));Rd.displayName="SidebarContent";const Td=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"group",className:sr("relative flex w-full min-w-0 flex-col p-2",t),...a}));Td.displayName="SidebarGroup";const Ad=r.forwardRef(({className:t,asChild:a=!1,...r},n)=>e(a?g:"div",{ref:n,"data-sidebar":"group-label",className:sr("duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",t),...r}));Ad.displayName="SidebarGroupLabel";const Id=r.forwardRef(({className:t,asChild:a=!1,...r},n)=>e(a?g:"button",{ref:n,"data-sidebar":"group-action",className:sr("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",t),...r}));Id.displayName="SidebarGroupAction";const Md=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"group-content",className:sr("w-full text-sm",t),...a}));Md.displayName="SidebarGroupContent";const Od=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,"data-sidebar":"menu",className:sr("flex w-full min-w-0 flex-col gap-1",t),...a}));Od.displayName="SidebarMenu";const Ld=r.forwardRef(({className:t,...a},r)=>e("li",{ref:r,"data-sidebar":"menu-item",className:sr("group/menu-item relative",t),...a}));Ld.displayName="SidebarMenuItem";const Dd=b("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-primary data-[active=true]:font-medium data-[active=true]:text-sidebar-primary-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:gap-0 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 group-data-[collapsible=icon]:[&>*]:!mr-0 group-data-[collapsible=icon]:[&>*]:!ml-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-10 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),Fd=r.forwardRef(({asChild:a=!1,isActive:r=!1,variant:n="default",size:s="default",tooltip:i,className:o,...l},c)=>{const d=a?g:"button",{isMobile:u,state:m}=yd(),h=e(d,{ref:c,"data-sidebar":"menu-button","data-size":s,"data-active":r,className:sr(Dd({variant:n,size:s}),o),...l});return i?("string"==typeof i&&(i={children:i}),t(yi,{children:[e(wi,{asChild:!0,children:h}),e(xi,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):h});Fd.displayName="SidebarMenuButton";const jd=r.forwardRef(({className:t,asChild:a=!1,showOnHover:r=!1,...n},s)=>e(a?g:"button",{ref:s,"data-sidebar":"menu-action",className:sr("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",t),...n}));jd.displayName="SidebarMenuAction";const zd=r.forwardRef(({className:t,...a},r)=>e("div",{ref:r,"data-sidebar":"menu-badge",className:sr("absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",t),...a}));zd.displayName="SidebarMenuBadge";const $d=r.forwardRef(({className:a,showIcon:n=!1,...s},i)=>{const o=r.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return t("div",{ref:i,"data-sidebar":"menu-skeleton",className:sr("rounded-md h-8 flex gap-2 px-2 items-center",a),...s,children:[n&&e("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":o}})]})});$d.displayName="SidebarMenuSkeleton";const Ud=r.forwardRef(({className:t,...a},r)=>e("ul",{ref:r,"data-sidebar":"menu-sub",className:sr("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",t),...a}));Ud.displayName="SidebarMenuSub";const Vd=r.forwardRef(({...t},a)=>e("li",{ref:a,...t}));Vd.displayName="SidebarMenuSubItem";const Wd=r.forwardRef(({asChild:t=!1,size:a="md",isActive:r,className:n,...s},i)=>e(t?g:"a",{ref:i,"data-sidebar":"menu-sub-button","data-size":a,"data-active":r,className:sr("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground","sm"===a&&"text-xs","md"===a&&"text-sm","group-data-[collapsible=icon]:hidden",n),...s}));Wd.displayName="SidebarMenuSubButton";const Bd=r.forwardRef(({className:a,...r},n)=>t(Jt.Root,{ref:n,className:sr("relative flex w-full touch-none select-none items-center",a),...r,children:[e(Jt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e(Jt.Range,{className:"absolute h-full bg-primary"})}),e(Jt.Thumb,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Bd.displayName=Jt.Root.displayName;const Hd=Qt.Root,qd=r.forwardRef(({className:t,...a},r)=>e(Qt.List,{ref:r,className:sr("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",t),...a}));qd.displayName=Qt.List.displayName;const Kd=r.forwardRef(({className:t,...a},r)=>e(Qt.Trigger,{ref:r,className:sr("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",t),...a}));Kd.displayName=Qt.Trigger.displayName;const Gd=r.forwardRef(({className:t,...a},r)=>e(Qt.Content,{ref:r,className:sr("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));function Xd({children:t,className:a}){return e("div",{className:sr("flex flex-col h-full",a),children:e(uo,{className:"flex-1",children:e("div",{className:"space-y-6 p-6",children:t})})})}function Jd({title:a,description:r,actions:n,className:s}){return t("div",{className:sr("space-y-4",s),children:[t("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[t("div",{className:"space-y-1",children:[e("h2",{className:"text-2xl font-bold tracking-tight",children:a}),r&&e("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&e("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),e(kr,{})]})}function Qd({children:t,className:a}){return e("div",{className:sr("space-y-6",a),children:t})}Gd.displayName=Qt.Content.displayName;const Yd=b("inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),Zd=r.forwardRef(({className:t,variant:a,size:r,...n},s)=>e(Yt.Root,{ref:s,className:sr(Yd({variant:a,size:r,className:t})),...n}));Zd.displayName=Yt.Root.displayName;const eu=r.createContext({size:"default",variant:"default"}),tu=r.forwardRef(({className:t,variant:a,size:r,children:n,...s},i)=>e(Zt.Root,{ref:i,className:sr("flex items-center justify-center gap-1",t),...s,children:e(eu.Provider,{value:{variant:a,size:r},children:n})}));tu.displayName=Zt.Root.displayName;const au=r.forwardRef(({className:t,children:a,variant:n,size:s,...i},o)=>{const l=r.useContext(eu);return e(Zt.Item,{ref:o,className:sr(Yd({variant:l.variant||n,size:l.size||s}),t),...i,children:a})});function ru(t,a=[]){let n=[];const s=()=>{const e=n.map(e=>r.createContext(e));return function(a){const n=a?.[t]||e;return r.useMemo(()=>({[`__scope${t}`]:{...a,[t]:n}}),[a,n])}};return s.scopeName=t,[function(a,s){const i=r.createContext(s),o=n.length;n=[...n,s];const l=a=>{const{scope:n,children:s,...l}=a,c=n?.[t]?.[o]||i,d=r.useMemo(()=>l,Object.values(l));return e(c.Provider,{value:d,children:s})};return l.displayName=a+"Provider",[l,function(e,n){const l=n?.[t]?.[o]||i,c=r.useContext(l);if(c)return c;if(void 0!==s)return s;throw new Error(`\`${e}\` must be used within \`${a}\``)}]},nu(s,...a)]}function nu(...e){const t=e[0];if(1===e.length)return t;const a=()=>{const a=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const n=a.reduce((t,{useScope:a,scopeName:r})=>({...t,...a(e)[`__scope${r}`]}),{});return r.useMemo(()=>({[`__scope${t.scopeName}`]:n}),[n])}};return a.scopeName=t.scopeName,a}function su(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function iu(...e){return t=>{let a=!1;const r=e.map(e=>{const r=su(e,t);return a||"function"!=typeof r||(a=!0),r});if(a)return()=>{for(let t=0;t<r.length;t++){const a=r[t];"function"==typeof a?a():su(e[t],null)}}}}function ou(...e){return r.useCallback(iu(...e),e)}function lu(t){const a=t+"CollectionProvider",[r,s]=ru(a),[i,o]=r(a,{collectionRef:{current:null},itemMap:new Map}),l=t=>{const{scope:a,children:r}=t,s=n.useRef(null),o=n.useRef(new Map).current;return e(i,{scope:a,itemMap:o,collectionRef:s,children:r})};l.displayName=a;const c=t+"CollectionSlot",d=v(c),u=n.forwardRef((t,a)=>{const{scope:r,children:n}=t,s=ou(a,o(c,r).collectionRef);return e(d,{ref:s,children:n})});u.displayName=c;const m=t+"CollectionItemSlot",h="data-radix-collection-item",p=v(m),f=n.forwardRef((t,a)=>{const{scope:r,children:s,...i}=t,l=n.useRef(null),c=ou(a,l),d=o(m,r);return n.useEffect(()=>(d.itemMap.set(l,{ref:l,...i}),()=>{d.itemMap.delete(l)})),e(p,{[h]:"",ref:c,children:s})});return f.displayName=m,[{Provider:l,Slot:u,ItemSlot:f},function(e){const a=o(t+"CollectionConsumer",e);return n.useCallback(()=>{const e=a.collectionRef.current;if(!e)return[];const t=Array.from(e.querySelectorAll(`[${h}]`));return Array.from(a.itemMap.values()).sort((e,a)=>t.indexOf(e.ref.current)-t.indexOf(a.ref.current))},[a.collectionRef,a.itemMap])},s]}au.displayName=Zt.Item.displayName;var cu=r.createContext(void 0);function du(e){const t=r.useContext(cu);return e||t||"ltr"}function uu(e,t,{checkForDefaultPrevented:a=!0}={}){return function(r){if(e?.(r),!1===a||!r.defaultPrevented)return t?.(r)}}var mu=globalThis?.document?r.useLayoutEffect:()=>{},hu=r[" useId ".trim().toString()]||(()=>{}),pu=0;function fu(e){const[t,a]=r.useState(hu());return mu(()=>{a(e=>e??String(pu++))},[e]),t?`radix-${t}`:""}var gu=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((t,a)=>{const n=v(`Primitive.${a}`),s=r.forwardRef((t,r)=>{const{asChild:s,...i}=t,o=s?n:a;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),e(o,{...i,ref:r})});return s.displayName=`Primitive.${a}`,{...t,[a]:s}},{});function vu(e,t){e&&ea.flushSync(()=>e.dispatchEvent(t))}function bu(e){const t=r.useRef(e);return r.useEffect(()=>{t.current=e}),r.useMemo(()=>(...e)=>t.current?.(...e),[])}var yu,wu="dismissableLayer.update",xu="dismissableLayer.pointerDownOutside",Nu="dismissableLayer.focusOutside",ku=r.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Cu=r.forwardRef((t,a)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:l,onDismiss:c,...d}=t,u=r.useContext(ku),[m,h]=r.useState(null),p=m?.ownerDocument??globalThis?.document,[,f]=r.useState({}),g=ou(a,e=>h(e)),v=Array.from(u.layers),[b]=[...u.layersWithOutsidePointerEventsDisabled].slice(-1),y=v.indexOf(b),w=m?v.indexOf(m):-1,x=u.layersWithOutsidePointerEventsDisabled.size>0,N=w>=y,k=function(e,t=globalThis?.document){const a=bu(e),n=r.useRef(!1),s=r.useRef(()=>{});return r.useEffect(()=>{const e=e=>{if(e.target&&!n.current){let r=function(){Eu(xu,a,n,{discrete:!0})};const n={originalEvent:e};"touch"===e.pointerType?(t.removeEventListener("click",s.current),s.current=r,t.addEventListener("click",s.current,{once:!0})):r()}else t.removeEventListener("click",s.current);n.current=!1},r=window.setTimeout(()=>{t.addEventListener("pointerdown",e)},0);return()=>{window.clearTimeout(r),t.removeEventListener("pointerdown",e),t.removeEventListener("click",s.current)}},[t,a]),{onPointerDownCapture:()=>n.current=!0}}(e=>{const t=e.target,a=[...u.branches].some(e=>e.contains(t));N&&!a&&(i?.(e),l?.(e),e.defaultPrevented||c?.())},p),C=function(e,t=globalThis?.document){const a=bu(e),n=r.useRef(!1);return r.useEffect(()=>{const e=e=>{if(e.target&&!n.current){Eu(Nu,a,{originalEvent:e},{discrete:!1})}};return t.addEventListener("focusin",e),()=>t.removeEventListener("focusin",e)},[t,a]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}(e=>{const t=e.target;[...u.branches].some(e=>e.contains(t))||(o?.(e),l?.(e),e.defaultPrevented||c?.())},p);return function(e,t=globalThis?.document){const a=bu(e);r.useEffect(()=>{const e=e=>{"Escape"===e.key&&a(e)};return t.addEventListener("keydown",e,{capture:!0}),()=>t.removeEventListener("keydown",e,{capture:!0})},[a,t])}(e=>{w===u.layers.size-1&&(s?.(e),!e.defaultPrevented&&c&&(e.preventDefault(),c()))},p),r.useEffect(()=>{if(m)return n&&(0===u.layersWithOutsidePointerEventsDisabled.size&&(yu=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),u.layersWithOutsidePointerEventsDisabled.add(m)),u.layers.add(m),Su(),()=>{n&&1===u.layersWithOutsidePointerEventsDisabled.size&&(p.body.style.pointerEvents=yu)}},[m,p,n,u]),r.useEffect(()=>()=>{m&&(u.layers.delete(m),u.layersWithOutsidePointerEventsDisabled.delete(m),Su())},[m,u]),r.useEffect(()=>{const e=()=>f({});return document.addEventListener(wu,e),()=>document.removeEventListener(wu,e)},[]),e(gu.div,{...d,ref:g,style:{pointerEvents:x?N?"auto":"none":void 0,...t.style},onFocusCapture:uu(t.onFocusCapture,C.onFocusCapture),onBlurCapture:uu(t.onBlurCapture,C.onBlurCapture),onPointerDownCapture:uu(t.onPointerDownCapture,k.onPointerDownCapture)})});Cu.displayName="DismissableLayer";function Su(){const e=new CustomEvent(wu);document.dispatchEvent(e)}function Eu(e,t,a,{discrete:r}){const n=a.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:a});t&&n.addEventListener(e,t,{once:!0}),r?vu(n,s):n.dispatchEvent(s)}r.forwardRef((t,a)=>{const n=r.useContext(ku),s=r.useRef(null),i=ou(a,s);return r.useEffect(()=>{const e=s.current;if(e)return n.branches.add(e),()=>{n.branches.delete(e)}},[n.branches]),e(gu.div,{...t,ref:i})}).displayName="DismissableLayerBranch";var _u=0;function Pu(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var Ru="focusScope.autoFocusOnMount",Tu="focusScope.autoFocusOnUnmount",Au={bubbles:!1,cancelable:!0},Iu=r.forwardRef((t,a)=>{const{loop:n=!1,trapped:s=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...l}=t,[c,d]=r.useState(null),u=bu(i),m=bu(o),h=r.useRef(null),p=ou(a,e=>d(e)),f=r.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;r.useEffect(()=>{if(s){let e=function(e){if(f.paused||!c)return;const t=e.target;c.contains(t)?h.current=t:Du(h.current,{select:!0})},t=function(e){if(f.paused||!c)return;const t=e.relatedTarget;null!==t&&(c.contains(t)||Du(h.current,{select:!0}))},a=function(e){if(document.activeElement===document.body)for(const t of e)t.removedNodes.length>0&&Du(c)};document.addEventListener("focusin",e),document.addEventListener("focusout",t);const r=new MutationObserver(a);return c&&r.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",e),document.removeEventListener("focusout",t),r.disconnect()}}},[s,c,f.paused]),r.useEffect(()=>{if(c){Fu.add(f);const t=document.activeElement;if(!c.contains(t)){const a=new CustomEvent(Ru,Au);c.addEventListener(Ru,u),c.dispatchEvent(a),a.defaultPrevented||(!function(e,{select:t=!1}={}){const a=document.activeElement;for(const r of e)if(Du(r,{select:t}),document.activeElement!==a)return}((e=Mu(c),e.filter(e=>"A"!==e.tagName)),{select:!0}),document.activeElement===t&&Du(c))}return()=>{c.removeEventListener(Ru,u),setTimeout(()=>{const e=new CustomEvent(Tu,Au);c.addEventListener(Tu,m),c.dispatchEvent(e),e.defaultPrevented||Du(t??document.body,{select:!0}),c.removeEventListener(Tu,m),Fu.remove(f)},0)}}var e},[c,u,m,f]);const g=r.useCallback(e=>{if(!n&&!s)return;if(f.paused)return;const t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,a=document.activeElement;if(t&&a){const t=e.currentTarget,[r,s]=function(e){const t=Mu(e),a=Ou(t,e),r=Ou(t.reverse(),e);return[a,r]}(t);r&&s?e.shiftKey||a!==s?e.shiftKey&&a===r&&(e.preventDefault(),n&&Du(s,{select:!0})):(e.preventDefault(),n&&Du(r,{select:!0})):a===t&&e.preventDefault()}},[n,s,f.paused]);return e(gu.div,{tabIndex:-1,...l,ref:p,onKeyDown:g})});function Mu(e){const t=[],a=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{const t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;a.nextNode();)t.push(a.currentNode);return t}function Ou(e,t){for(const a of e)if(!Lu(a,{upTo:t}))return a}function Lu(e,{upTo:t}){if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==t&&e===t)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function Du(e,{select:t=!1}={}){if(e&&e.focus){const a=document.activeElement;e.focus({preventScroll:!0}),e!==a&&function(e){return e instanceof HTMLInputElement&&"select"in e}(e)&&t&&e.select()}}Iu.displayName="FocusScope";var Fu=function(){let e=[];return{add(t){const a=e[0];t!==a&&a?.pause(),e=ju(e,t),e.unshift(t)},remove(t){e=ju(e,t),e[0]?.resume()}}}();function ju(e,t){const a=[...e],r=a.indexOf(t);return-1!==r&&a.splice(r,1),a}const zu=["top","right","bottom","left"],$u=Math.min,Uu=Math.max,Vu=Math.round,Wu=Math.floor,Bu=e=>({x:e,y:e}),Hu={left:"right",right:"left",bottom:"top",top:"bottom"},qu={start:"end",end:"start"};function Ku(e,t,a){return Uu(e,$u(t,a))}function Gu(e,t){return"function"==typeof e?e(t):e}function Xu(e){return e.split("-")[0]}function Ju(e){return e.split("-")[1]}function Qu(e){return"x"===e?"y":"x"}function Yu(e){return"y"===e?"height":"width"}const Zu=new Set(["top","bottom"]);function em(e){return Zu.has(Xu(e))?"y":"x"}function tm(e){return Qu(em(e))}function am(e){return e.replace(/start|end/g,e=>qu[e])}const rm=["left","right"],nm=["right","left"],sm=["top","bottom"],im=["bottom","top"];function om(e,t,a,r){const n=Ju(e);let s=function(e,t,a){switch(e){case"top":case"bottom":return a?t?nm:rm:t?rm:nm;case"left":case"right":return t?sm:im;default:return[]}}(Xu(e),"start"===a,r);return n&&(s=s.map(e=>e+"-"+n),t&&(s=s.concat(s.map(am)))),s}function lm(e){return e.replace(/left|right|bottom|top/g,e=>Hu[e])}function cm(e){return"number"!=typeof e?function(e){return{top:0,right:0,bottom:0,left:0,...e}}(e):{top:e,right:e,bottom:e,left:e}}function dm(e){const{x:t,y:a,width:r,height:n}=e;return{width:r,height:n,top:a,left:t,right:t+r,bottom:a+n,x:t,y:a}}function um(e,t,a){let{reference:r,floating:n}=e;const s=em(t),i=tm(t),o=Yu(i),l=Xu(t),c="y"===s,d=r.x+r.width/2-n.width/2,u=r.y+r.height/2-n.height/2,m=r[o]/2-n[o]/2;let h;switch(l){case"top":h={x:d,y:r.y-n.height};break;case"bottom":h={x:d,y:r.y+r.height};break;case"right":h={x:r.x+r.width,y:u};break;case"left":h={x:r.x-n.width,y:u};break;default:h={x:r.x,y:r.y}}switch(Ju(t)){case"start":h[i]-=m*(a&&c?-1:1);break;case"end":h[i]+=m*(a&&c?-1:1)}return h}async function mm(e,t){var a;void 0===t&&(t={});const{x:r,y:n,platform:s,rects:i,elements:o,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:m=!1,padding:h=0}=Gu(t,e),p=cm(h),f=o[m?"floating"===u?"reference":"floating":u],g=dm(await s.getClippingRect({element:null==(a=await(null==s.isElement?void 0:s.isElement(f)))||a?f:f.contextElement||await(null==s.getDocumentElement?void 0:s.getDocumentElement(o.floating)),boundary:c,rootBoundary:d,strategy:l})),v="floating"===u?{x:r,y:n,width:i.floating.width,height:i.floating.height}:i.reference,b=await(null==s.getOffsetParent?void 0:s.getOffsetParent(o.floating)),y=await(null==s.isElement?void 0:s.isElement(b))&&await(null==s.getScale?void 0:s.getScale(b))||{x:1,y:1},w=dm(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:v,offsetParent:b,strategy:l}):v);return{top:(g.top-w.top+p.top)/y.y,bottom:(w.bottom-g.bottom+p.bottom)/y.y,left:(g.left-w.left+p.left)/y.x,right:(w.right-g.right+p.right)/y.x}}function hm(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function pm(e){return zu.some(t=>e[t]>=0)}const fm=new Set(["left","top"]);function gm(){return"undefined"!=typeof window}function vm(e){return wm(e)?(e.nodeName||"").toLowerCase():"#document"}function bm(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function ym(e){var t;return null==(t=(wm(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function wm(e){return!!gm()&&(e instanceof Node||e instanceof bm(e).Node)}function xm(e){return!!gm()&&(e instanceof Element||e instanceof bm(e).Element)}function Nm(e){return!!gm()&&(e instanceof HTMLElement||e instanceof bm(e).HTMLElement)}function km(e){return!(!gm()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof bm(e).ShadowRoot)}const Cm=new Set(["inline","contents"]);function Sm(e){const{overflow:t,overflowX:a,overflowY:r,display:n}=Fm(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+a)&&!Cm.has(n)}const Em=new Set(["table","td","th"]);function _m(e){return Em.has(vm(e))}const Pm=[":popover-open",":modal"];function Rm(e){return Pm.some(t=>{try{return e.matches(t)}catch(a){return!1}})}const Tm=["transform","translate","scale","rotate","perspective"],Am=["transform","translate","scale","rotate","perspective","filter"],Im=["paint","layout","strict","content"];function Mm(e){const t=Om(),a=xm(e)?Fm(e):e;return Tm.some(e=>!!a[e]&&"none"!==a[e])||!!a.containerType&&"normal"!==a.containerType||!t&&!!a.backdropFilter&&"none"!==a.backdropFilter||!t&&!!a.filter&&"none"!==a.filter||Am.some(e=>(a.willChange||"").includes(e))||Im.some(e=>(a.contain||"").includes(e))}function Om(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const Lm=new Set(["html","body","#document"]);function Dm(e){return Lm.has(vm(e))}function Fm(e){return bm(e).getComputedStyle(e)}function jm(e){return xm(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function zm(e){if("html"===vm(e))return e;const t=e.assignedSlot||e.parentNode||km(e)&&e.host||ym(e);return km(t)?t.host:t}function $m(e){const t=zm(e);return Dm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Nm(t)&&Sm(t)?t:$m(t)}function Um(e,t,a){var r;void 0===t&&(t=[]),void 0===a&&(a=!0);const n=$m(e),s=n===(null==(r=e.ownerDocument)?void 0:r.body),i=bm(n);if(s){const e=Vm(i);return t.concat(i,i.visualViewport||[],Sm(n)?n:[],e&&a?Um(e):[])}return t.concat(n,Um(n,[],a))}function Vm(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Wm(e){const t=Fm(e);let a=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const n=Nm(e),s=n?e.offsetWidth:a,i=n?e.offsetHeight:r,o=Vu(a)!==s||Vu(r)!==i;return o&&(a=s,r=i),{width:a,height:r,$:o}}function Bm(e){return xm(e)?e:e.contextElement}function Hm(e){const t=Bm(e);if(!Nm(t))return Bu(1);const a=t.getBoundingClientRect(),{width:r,height:n,$:s}=Wm(t);let i=(s?Vu(a.width):a.width)/r,o=(s?Vu(a.height):a.height)/n;return i&&Number.isFinite(i)||(i=1),o&&Number.isFinite(o)||(o=1),{x:i,y:o}}const qm=Bu(0);function Km(e){const t=bm(e);return Om()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:qm}function Gm(e,t,a,r){void 0===t&&(t=!1),void 0===a&&(a=!1);const n=e.getBoundingClientRect(),s=Bm(e);let i=Bu(1);t&&(r?xm(r)&&(i=Hm(r)):i=Hm(e));const o=function(e,t,a){return void 0===t&&(t=!1),!(!a||t&&a!==bm(e))&&t}(s,a,r)?Km(s):Bu(0);let l=(n.left+o.x)/i.x,c=(n.top+o.y)/i.y,d=n.width/i.x,u=n.height/i.y;if(s){const e=bm(s),t=r&&xm(r)?bm(r):r;let a=e,n=Vm(a);for(;n&&r&&t!==a;){const e=Hm(n),t=n.getBoundingClientRect(),r=Fm(n),s=t.left+(n.clientLeft+parseFloat(r.paddingLeft))*e.x,i=t.top+(n.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,d*=e.x,u*=e.y,l+=s,c+=i,a=bm(n),n=Vm(a)}}return dm({width:d,height:u,x:l,y:c})}function Xm(e,t){const a=jm(e).scrollLeft;return t?t.left+a:Gm(ym(e)).left+a}function Jm(e,t){const a=e.getBoundingClientRect();return{x:a.left+t.scrollLeft-Xm(e,a),y:a.top+t.scrollTop}}const Qm=new Set(["absolute","fixed"]);function Ym(e,t,a){let r;if("viewport"===t)r=function(e,t){const a=bm(e),r=ym(e),n=a.visualViewport;let s=r.clientWidth,i=r.clientHeight,o=0,l=0;if(n){s=n.width,i=n.height;const e=Om();(!e||e&&"fixed"===t)&&(o=n.offsetLeft,l=n.offsetTop)}const c=Xm(r);if(c<=0){const e=r.ownerDocument,t=e.body,a=getComputedStyle(t),n="CSS1Compat"===e.compatMode&&parseFloat(a.marginLeft)+parseFloat(a.marginRight)||0,i=Math.abs(r.clientWidth-t.clientWidth-n);i<=25&&(s-=i)}else c<=25&&(s+=c);return{width:s,height:i,x:o,y:l}}(e,a);else if("document"===t)r=function(e){const t=ym(e),a=jm(e),r=e.ownerDocument.body,n=Uu(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Uu(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let i=-a.scrollLeft+Xm(e);const o=-a.scrollTop;return"rtl"===Fm(r).direction&&(i+=Uu(t.clientWidth,r.clientWidth)-n),{width:n,height:s,x:i,y:o}}(ym(e));else if(xm(t))r=function(e,t){const a=Gm(e,!0,"fixed"===t),r=a.top+e.clientTop,n=a.left+e.clientLeft,s=Nm(e)?Hm(e):Bu(1);return{width:e.clientWidth*s.x,height:e.clientHeight*s.y,x:n*s.x,y:r*s.y}}(t,a);else{const a=Km(e);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return dm(r)}function Zm(e,t){const a=zm(e);return!(a===t||!xm(a)||Dm(a))&&("fixed"===Fm(a).position||Zm(a,t))}function eh(e,t,a){const r=Nm(t),n=ym(t),s="fixed"===a,i=Gm(e,!0,s,t);let o={scrollLeft:0,scrollTop:0};const l=Bu(0);function c(){l.x=Xm(n)}if(r||!r&&!s)if(("body"!==vm(t)||Sm(n))&&(o=jm(t)),r){const e=Gm(t,!0,s,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else n&&c();s&&!r&&n&&c();const d=!n||r||s?Bu(0):Jm(n,o);return{x:i.left+o.scrollLeft-l.x-d.x,y:i.top+o.scrollTop-l.y-d.y,width:i.width,height:i.height}}function th(e){return"static"===Fm(e).position}function ah(e,t){if(!Nm(e)||"fixed"===Fm(e).position)return null;if(t)return t(e);let a=e.offsetParent;return ym(e)===a&&(a=a.ownerDocument.body),a}function rh(e,t){const a=bm(e);if(Rm(e))return a;if(!Nm(e)){let t=zm(e);for(;t&&!Dm(t);){if(xm(t)&&!th(t))return t;t=zm(t)}return a}let r=ah(e,t);for(;r&&_m(r)&&th(r);)r=ah(r,t);return r&&Dm(r)&&th(r)&&!Mm(r)?a:r||function(e){let t=zm(e);for(;Nm(t)&&!Dm(t);){if(Mm(t))return t;if(Rm(t))return null;t=zm(t)}return null}(e)||a}const nh={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:a,offsetParent:r,strategy:n}=e;const s="fixed"===n,i=ym(r),o=!!t&&Rm(t.floating);if(r===i||o&&s)return a;let l={scrollLeft:0,scrollTop:0},c=Bu(1);const d=Bu(0),u=Nm(r);if((u||!u&&!s)&&(("body"!==vm(r)||Sm(i))&&(l=jm(r)),Nm(r))){const e=Gm(r);c=Hm(r),d.x=e.x+r.clientLeft,d.y=e.y+r.clientTop}const m=!i||u||s?Bu(0):Jm(i,l);return{width:a.width*c.x,height:a.height*c.y,x:a.x*c.x-l.scrollLeft*c.x+d.x+m.x,y:a.y*c.y-l.scrollTop*c.y+d.y+m.y}},getDocumentElement:ym,getClippingRect:function(e){let{element:t,boundary:a,rootBoundary:r,strategy:n}=e;const s=[..."clippingAncestors"===a?Rm(t)?[]:function(e,t){const a=t.get(e);if(a)return a;let r=Um(e,[],!1).filter(e=>xm(e)&&"body"!==vm(e)),n=null;const s="fixed"===Fm(e).position;let i=s?zm(e):e;for(;xm(i)&&!Dm(i);){const t=Fm(i),a=Mm(i);a||"fixed"!==t.position||(n=null),(s?!a&&!n:!a&&"static"===t.position&&n&&Qm.has(n.position)||Sm(i)&&!a&&Zm(e,i))?r=r.filter(e=>e!==i):n=t,i=zm(i)}return t.set(e,r),r}(t,this._c):[].concat(a),r],i=s[0],o=s.reduce((e,a)=>{const r=Ym(t,a,n);return e.top=Uu(r.top,e.top),e.right=$u(r.right,e.right),e.bottom=$u(r.bottom,e.bottom),e.left=Uu(r.left,e.left),e},Ym(t,i,n));return{width:o.right-o.left,height:o.bottom-o.top,x:o.left,y:o.top}},getOffsetParent:rh,getElementRects:async function(e){const t=this.getOffsetParent||rh,a=this.getDimensions,r=await a(e.floating);return{reference:eh(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:a}=Wm(e);return{width:t,height:a}},getScale:Hm,isElement:xm,isRTL:function(e){return"rtl"===Fm(e).direction}};function sh(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ih(e,t,a,r){void 0===r&&(r={});const{ancestorScroll:n=!0,ancestorResize:s=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:o="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=Bm(e),d=n||s?[...c?Um(c):[],...Um(t)]:[];d.forEach(e=>{n&&e.addEventListener("scroll",a,{passive:!0}),s&&e.addEventListener("resize",a)});const u=c&&o?function(e,t){let a,r=null;const n=ym(e);function s(){var e;clearTimeout(a),null==(e=r)||e.disconnect(),r=null}return function i(o,l){void 0===o&&(o=!1),void 0===l&&(l=1),s();const c=e.getBoundingClientRect(),{left:d,top:u,width:m,height:h}=c;if(o||t(),!m||!h)return;const p={rootMargin:-Wu(u)+"px "+-Wu(n.clientWidth-(d+m))+"px "+-Wu(n.clientHeight-(u+h))+"px "+-Wu(d)+"px",threshold:Uu(0,$u(1,l))||1};let f=!0;function g(t){const r=t[0].intersectionRatio;if(r!==l){if(!f)return i();r?i(!1,r):a=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==r||sh(c,e.getBoundingClientRect())||i(),f=!1}try{r=new IntersectionObserver(g,{...p,root:n.ownerDocument})}catch(v){r=new IntersectionObserver(g,p)}r.observe(e)}(!0),s}(c,a):null;let m,h=-1,p=null;i&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=p)||e.observe(t)})),a()}),c&&!l&&p.observe(c),p.observe(t));let f=l?Gm(e):null;return l&&function t(){const r=Gm(e);f&&!sh(f,r)&&a();f=r,m=requestAnimationFrame(t)}(),a(),()=>{var e;d.forEach(e=>{n&&e.removeEventListener("scroll",a),s&&e.removeEventListener("resize",a)}),null==u||u(),null==(e=p)||e.disconnect(),p=null,l&&cancelAnimationFrame(m)}}const oh=function(e){return void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var a,r;const{x:n,y:s,placement:i,middlewareData:o}=t,l=await async function(e,t){const{placement:a,platform:r,elements:n}=e,s=await(null==r.isRTL?void 0:r.isRTL(n.floating)),i=Xu(a),o=Ju(a),l="y"===em(a),c=fm.has(i)?-1:1,d=s&&l?-1:1,u=Gu(t,e);let{mainAxis:m,crossAxis:h,alignmentAxis:p}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return o&&"number"==typeof p&&(h="end"===o?-1*p:p),l?{x:h*d,y:m*c}:{x:m*c,y:h*d}}(t,e);return i===(null==(a=o.offset)?void 0:a.placement)&&null!=(r=o.arrow)&&r.alignmentOffset?{}:{x:n+l.x,y:s+l.y,data:{...l,placement:i}}}}},lh=function(e){return void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:a,y:r,placement:n}=t,{mainAxis:s=!0,crossAxis:i=!1,limiter:o={fn:e=>{let{x:t,y:a}=e;return{x:t,y:a}}},...l}=Gu(e,t),c={x:a,y:r},d=await mm(t,l),u=em(Xu(n)),m=Qu(u);let h=c[m],p=c[u];if(s){const e="y"===m?"bottom":"right";h=Ku(h+d["y"===m?"top":"left"],h,h-d[e])}if(i){const e="y"===u?"bottom":"right";p=Ku(p+d["y"===u?"top":"left"],p,p-d[e])}const f=o.fn({...t,[m]:h,[u]:p});return{...f,data:{x:f.x-a,y:f.y-r,enabled:{[m]:s,[u]:i}}}}}},ch=function(e){return void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var a,r;const{placement:n,middlewareData:s,rects:i,initialPlacement:o,platform:l,elements:c}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:m,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:p="none",flipAlignment:f=!0,...g}=Gu(e,t);if(null!=(a=s.arrow)&&a.alignmentOffset)return{};const v=Xu(n),b=em(o),y=Xu(o)===o,w=await(null==l.isRTL?void 0:l.isRTL(c.floating)),x=m||(y||!f?[lm(o)]:function(e){const t=lm(e);return[am(e),t,am(t)]}(o)),N="none"!==p;!m&&N&&x.push(...om(o,f,p,w));const k=[o,...x],C=await mm(t,g),S=[];let E=(null==(r=s.flip)?void 0:r.overflows)||[];if(d&&S.push(C[v]),u){const e=function(e,t,a){void 0===a&&(a=!1);const r=Ju(e),n=tm(e),s=Yu(n);let i="x"===n?r===(a?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[s]>t.floating[s]&&(i=lm(i)),[i,lm(i)]}(n,i,w);S.push(C[e[0]],C[e[1]])}if(E=[...E,{placement:n,overflows:S}],!S.every(e=>e<=0)){var _,P;const e=((null==(_=s.flip)?void 0:_.index)||0)+1,t=k[e];if(t){if(!("alignment"===u&&b!==em(t))||E.every(e=>em(e.placement)!==b||e.overflows[0]>0))return{data:{index:e,overflows:E},reset:{placement:t}}}let a=null==(P=E.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:P.placement;if(!a)switch(h){case"bestFit":{var R;const e=null==(R=E.filter(e=>{if(N){const t=em(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:R[0];e&&(a=e);break}case"initialPlacement":a=o}if(n!==a)return{reset:{placement:a}}}return{}}}},dh=function(e){return void 0===e&&(e={}),{name:"size",options:e,async fn(t){var a,r;const{placement:n,rects:s,platform:i,elements:o}=t,{apply:l=()=>{},...c}=Gu(e,t),d=await mm(t,c),u=Xu(n),m=Ju(n),h="y"===em(n),{width:p,height:f}=s.floating;let g,v;"top"===u||"bottom"===u?(g=u,v=m===(await(null==i.isRTL?void 0:i.isRTL(o.floating))?"start":"end")?"left":"right"):(v=u,g="end"===m?"top":"bottom");const b=f-d.top-d.bottom,y=p-d.left-d.right,w=$u(f-d[g],b),x=$u(p-d[v],y),N=!t.middlewareData.shift;let k=w,C=x;if(null!=(a=t.middlewareData.shift)&&a.enabled.x&&(C=y),null!=(r=t.middlewareData.shift)&&r.enabled.y&&(k=b),N&&!m){const e=Uu(d.left,0),t=Uu(d.right,0),a=Uu(d.top,0),r=Uu(d.bottom,0);h?C=p-2*(0!==e||0!==t?e+t:Uu(d.left,d.right)):k=f-2*(0!==a||0!==r?a+r:Uu(d.top,d.bottom))}await l({...t,availableWidth:C,availableHeight:k});const S=await i.getDimensions(o.floating);return p!==S.width||f!==S.height?{reset:{rects:!0}}:{}}}},uh=function(e){return void 0===e&&(e={}),{name:"hide",options:e,async fn(t){const{rects:a}=t,{strategy:r="referenceHidden",...n}=Gu(e,t);switch(r){case"referenceHidden":{const e=hm(await mm(t,{...n,elementContext:"reference"}),a.reference);return{data:{referenceHiddenOffsets:e,referenceHidden:pm(e)}}}case"escaped":{const e=hm(await mm(t,{...n,altBoundary:!0}),a.floating);return{data:{escapedOffsets:e,escaped:pm(e)}}}default:return{}}}}},mh=e=>({name:"arrow",options:e,async fn(t){const{x:a,y:r,placement:n,rects:s,platform:i,elements:o,middlewareData:l}=t,{element:c,padding:d=0}=Gu(e,t)||{};if(null==c)return{};const u=cm(d),m={x:a,y:r},h=tm(n),p=Yu(h),f=await i.getDimensions(c),g="y"===h,v=g?"top":"left",b=g?"bottom":"right",y=g?"clientHeight":"clientWidth",w=s.reference[p]+s.reference[h]-m[h]-s.floating[p],x=m[h]-s.reference[h],N=await(null==i.getOffsetParent?void 0:i.getOffsetParent(c));let k=N?N[y]:0;k&&await(null==i.isElement?void 0:i.isElement(N))||(k=o.floating[y]||s.floating[p]);const C=w/2-x/2,S=k/2-f[p]/2-1,E=$u(u[v],S),_=$u(u[b],S),P=E,R=k-f[p]-_,T=k/2-f[p]/2+C,A=Ku(P,T,R),I=!l.arrow&&null!=Ju(n)&&T!==A&&s.reference[p]/2-(T<P?E:_)-f[p]/2<0,M=I?T<P?T-P:T-R:0;return{[h]:m[h]+M,data:{[h]:A,centerOffset:T-A-M,...I&&{alignmentOffset:M}},reset:I}}}),hh=function(e){return void 0===e&&(e={}),{options:e,fn(t){const{x:a,y:r,placement:n,rects:s,middlewareData:i}=t,{offset:o=0,mainAxis:l=!0,crossAxis:c=!0}=Gu(e,t),d={x:a,y:r},u=em(n),m=Qu(u);let h=d[m],p=d[u];const f=Gu(o,t),g="number"==typeof f?{mainAxis:f,crossAxis:0}:{mainAxis:0,crossAxis:0,...f};if(l){const e="y"===m?"height":"width",t=s.reference[m]-s.floating[e]+g.mainAxis,a=s.reference[m]+s.reference[e]-g.mainAxis;h<t?h=t:h>a&&(h=a)}if(c){var v,b;const e="y"===m?"width":"height",t=fm.has(Xu(n)),a=s.reference[u]-s.floating[e]+(t&&(null==(v=i.offset)?void 0:v[u])||0)+(t?0:g.crossAxis),r=s.reference[u]+s.reference[e]+(t?0:(null==(b=i.offset)?void 0:b[u])||0)-(t?g.crossAxis:0);p<a?p=a:p>r&&(p=r)}return{[m]:h,[u]:p}}}},ph=(e,t,a)=>{const r=new Map,n={platform:nh,...a},s={...n.platform,_c:r};return(async(e,t,a)=>{const{placement:r="bottom",strategy:n="absolute",middleware:s=[],platform:i}=a,o=s.filter(Boolean),l=await(null==i.isRTL?void 0:i.isRTL(t));let c=await i.getElementRects({reference:e,floating:t,strategy:n}),{x:d,y:u}=um(c,r,l),m=r,h={},p=0;for(let f=0;f<o.length;f++){const{name:a,fn:s}=o[f],{x:g,y:v,data:b,reset:y}=await s({x:d,y:u,initialPlacement:r,placement:m,strategy:n,middlewareData:h,rects:c,platform:i,elements:{reference:e,floating:t}});d=null!=g?g:d,u=null!=v?v:u,h={...h,[a]:{...h[a],...b}},y&&p<=50&&(p++,"object"==typeof y&&(y.placement&&(m=y.placement),y.rects&&(c=!0===y.rects?await i.getElementRects({reference:e,floating:t,strategy:n}):y.rects),({x:d,y:u}=um(c,m,l))),f=-1)}return{x:d,y:u,placement:m,strategy:n,middlewareData:h}})(e,t,{...n,platform:s})};var fh="undefined"!=typeof document?f:function(){};function gh(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if("function"==typeof e&&e.toString()===t.toString())return!0;let a,r,n;if(e&&t&&"object"==typeof e){if(Array.isArray(e)){if(a=e.length,a!==t.length)return!1;for(r=a;0!==r--;)if(!gh(e[r],t[r]))return!1;return!0}if(n=Object.keys(e),a=n.length,a!==Object.keys(t).length)return!1;for(r=a;0!==r--;)if(!{}.hasOwnProperty.call(t,n[r]))return!1;for(r=a;0!==r--;){const a=n[r];if(("_owner"!==a||!e.$$typeof)&&!gh(e[a],t[a]))return!1}return!0}return e!=e&&t!=t}function vh(e){if("undefined"==typeof window)return 1;return(e.ownerDocument.defaultView||window).devicePixelRatio||1}function bh(e,t){const a=vh(e);return Math.round(t*a)/a}function yh(e){const t=r.useRef(e);return fh(()=>{t.current=e}),t}const wh=e=>({name:"arrow",options:e,fn(t){const{element:a,padding:r}="function"==typeof e?e(t):e;return a&&function(e){return{}.hasOwnProperty.call(e,"current")}(a)?null!=a.current?mh({element:a.current,padding:r}).fn(t):{}:a?mh({element:a,padding:r}).fn(t):{}}}),xh=(e,t)=>({...oh(e),options:[e,t]}),Nh=(e,t)=>({...lh(e),options:[e,t]}),kh=(e,t)=>({...hh(e),options:[e,t]}),Ch=(e,t)=>({...ch(e),options:[e,t]}),Sh=(e,t)=>({...dh(e),options:[e,t]}),Eh=(e,t)=>({...uh(e),options:[e,t]}),_h=(e,t)=>({...wh(e),options:[e,t]});var Ph=r.forwardRef((t,a)=>{const{children:r,width:n=10,height:s=5,...i}=t;return e(gu.svg,{...i,ref:a,width:n,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:e("polygon",{points:"0,0 30,0 15,10"})})});Ph.displayName="Arrow";var Rh=Ph;var Th="Popper",[Ah,Ih]=ru(Th),[Mh,Oh]=Ah(Th),Lh=t=>{const{__scopePopper:a,children:n}=t,[s,i]=r.useState(null);return e(Mh,{scope:a,anchor:s,onAnchorChange:i,children:n})};Lh.displayName=Th;var Dh="PopperAnchor",Fh=r.forwardRef((t,a)=>{const{__scopePopper:n,virtualRef:s,...i}=t,o=Oh(Dh,n),l=r.useRef(null),c=ou(a,l),d=r.useRef(null);return r.useEffect(()=>{const e=d.current;d.current=s?.current||l.current,e!==d.current&&o.onAnchorChange(d.current)}),s?null:e(gu.div,{...i,ref:c})});Fh.displayName=Dh;var jh="PopperContent",[zh,$h]=Ah(jh),Uh=r.forwardRef((t,a)=>{const{__scopePopper:n,side:s="bottom",sideOffset:i=0,align:o="center",alignOffset:l=0,arrowPadding:c=0,avoidCollisions:d=!0,collisionBoundary:u=[],collisionPadding:m=0,sticky:h="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:g,...v}=t,b=Oh(jh,n),[y,w]=r.useState(null),x=ou(a,e=>w(e)),[N,k]=r.useState(null),C=function(e){const[t,a]=r.useState(void 0);return mu(()=>{if(e){a({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver(t=>{if(!Array.isArray(t))return;if(!t.length)return;const r=t[0];let n,s;if("borderBoxSize"in r){const e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;n=t.inlineSize,s=t.blockSize}else n=e.offsetWidth,s=e.offsetHeight;a({width:n,height:s})});return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}a(void 0)},[e]),t}(N),S=C?.width??0,E=C?.height??0,_=s+("center"!==o?"-"+o:""),P="number"==typeof m?m:{top:0,right:0,bottom:0,left:0,...m},R=Array.isArray(u)?u:[u],T=R.length>0,A={padding:P,boundary:R.filter(Hh),altBoundary:T},{refs:I,floatingStyles:M,placement:O,isPositioned:L,middlewareData:D}=function(e){void 0===e&&(e={});const{placement:t="bottom",strategy:a="absolute",middleware:n=[],platform:s,elements:{reference:i,floating:o}={},transform:l=!0,whileElementsMounted:c,open:d}=e,[u,m]=r.useState({x:0,y:0,strategy:a,placement:t,middlewareData:{},isPositioned:!1}),[h,p]=r.useState(n);gh(h,n)||p(n);const[f,g]=r.useState(null),[v,b]=r.useState(null),y=r.useCallback(e=>{e!==k.current&&(k.current=e,g(e))},[]),w=r.useCallback(e=>{e!==C.current&&(C.current=e,b(e))},[]),x=i||f,N=o||v,k=r.useRef(null),C=r.useRef(null),S=r.useRef(u),E=null!=c,_=yh(c),P=yh(s),R=yh(d),T=r.useCallback(()=>{if(!k.current||!C.current)return;const e={placement:t,strategy:a,middleware:h};P.current&&(e.platform=P.current),ph(k.current,C.current,e).then(e=>{const t={...e,isPositioned:!1!==R.current};A.current&&!gh(S.current,t)&&(S.current=t,ea.flushSync(()=>{m(t)}))})},[h,t,a,P,R]);fh(()=>{!1===d&&S.current.isPositioned&&(S.current.isPositioned=!1,m(e=>({...e,isPositioned:!1})))},[d]);const A=r.useRef(!1);fh(()=>(A.current=!0,()=>{A.current=!1}),[]),fh(()=>{if(x&&(k.current=x),N&&(C.current=N),x&&N){if(_.current)return _.current(x,N,T);T()}},[x,N,T,_,E]);const I=r.useMemo(()=>({reference:k,floating:C,setReference:y,setFloating:w}),[y,w]),M=r.useMemo(()=>({reference:x,floating:N}),[x,N]),O=r.useMemo(()=>{const e={position:a,left:0,top:0};if(!M.floating)return e;const t=bh(M.floating,u.x),r=bh(M.floating,u.y);return l?{...e,transform:"translate("+t+"px, "+r+"px)",...vh(M.floating)>=1.5&&{willChange:"transform"}}:{position:a,left:t,top:r}},[a,l,M.floating,u.x,u.y]);return r.useMemo(()=>({...u,update:T,refs:I,elements:M,floatingStyles:O}),[u,T,I,M,O])}({strategy:"fixed",placement:_,whileElementsMounted:(...e)=>ih(...e,{animationFrame:"always"===f}),elements:{reference:b.anchor},middleware:[xh({mainAxis:i+E,alignmentAxis:l}),d&&Nh({mainAxis:!0,crossAxis:!1,limiter:"partial"===h?kh():void 0,...A}),d&&Ch({...A}),Sh({...A,apply:({elements:e,rects:t,availableWidth:a,availableHeight:r})=>{const{width:n,height:s}=t.reference,i=e.floating.style;i.setProperty("--radix-popper-available-width",`${a}px`),i.setProperty("--radix-popper-available-height",`${r}px`),i.setProperty("--radix-popper-anchor-width",`${n}px`),i.setProperty("--radix-popper-anchor-height",`${s}px`)}}),N&&_h({element:N,padding:c}),qh({arrowWidth:S,arrowHeight:E}),p&&Eh({strategy:"referenceHidden",...A})]}),[F,j]=Kh(O),z=bu(g);mu(()=>{L&&z?.()},[L,z]);const $=D.arrow?.x,U=D.arrow?.y,V=0!==D.arrow?.centerOffset,[W,B]=r.useState();return mu(()=>{y&&B(window.getComputedStyle(y).zIndex)},[y]),e("div",{ref:I.setFloating,"data-radix-popper-content-wrapper":"",style:{...M,transform:L?M.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:W,"--radix-popper-transform-origin":[D.transformOrigin?.x,D.transformOrigin?.y].join(" "),...D.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:e(zh,{scope:n,placedSide:F,onArrowChange:k,arrowX:$,arrowY:U,shouldHideArrow:V,children:e(gu.div,{"data-side":F,"data-align":j,...v,ref:x,style:{...v.style,animation:L?void 0:"none"}})})})});Uh.displayName=jh;var Vh="PopperArrow",Wh={top:"bottom",right:"left",bottom:"top",left:"right"},Bh=r.forwardRef(function(t,a){const{__scopePopper:r,...n}=t,s=$h(Vh,r),i=Wh[s.placedSide];return e("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:e(Rh,{...n,ref:a,style:{...n.style,display:"block"}})})});function Hh(e){return null!==e}Bh.displayName=Vh;var qh=e=>({name:"transformOrigin",options:e,fn(t){const{placement:a,rects:r,middlewareData:n}=t,s=0!==n.arrow?.centerOffset,i=s?0:e.arrowWidth,o=s?0:e.arrowHeight,[l,c]=Kh(a),d={start:"0%",center:"50%",end:"100%"}[c],u=(n.arrow?.x??0)+i/2,m=(n.arrow?.y??0)+o/2;let h="",p="";return"bottom"===l?(h=s?d:`${u}px`,p=-o+"px"):"top"===l?(h=s?d:`${u}px`,p=`${r.floating.height+o}px`):"right"===l?(h=-o+"px",p=s?d:`${m}px`):"left"===l&&(h=`${r.floating.width+o}px`,p=s?d:`${m}px`),{data:{x:h,y:p}}}});function Kh(e){const[t,a="center"]=e.split("-");return[t,a]}var Gh=Lh,Xh=Fh,Jh=Uh,Qh=Bh,Yh=r.forwardRef((t,a)=>{const{container:n,...s}=t,[i,o]=r.useState(!1);mu(()=>o(!0),[]);const l=n||i&&globalThis?.document?.body;return l?ta.createPortal(e(gu.div,{...s,ref:a}),l):null});Yh.displayName="Portal";var Zh=e=>{const{present:t,children:a}=e,n=function(e){const[t,a]=r.useState(),n=r.useRef(null),s=r.useRef(e),i=r.useRef("none"),o=e?"mounted":"unmounted",[l,c]=function(e,t){return r.useReducer((e,a)=>t[e][a]??e,e)}(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return r.useEffect(()=>{const e=ep(n.current);i.current="mounted"===l?e:"none"},[l]),mu(()=>{const t=n.current,a=s.current;if(a!==e){const r=i.current,n=ep(t);if(e)c("MOUNT");else if("none"===n||"none"===t?.display)c("UNMOUNT");else{c(a&&r!==n?"ANIMATION_OUT":"UNMOUNT")}s.current=e}},[e,c]),mu(()=>{if(t){let e;const a=t.ownerDocument.defaultView??window,r=r=>{const i=ep(n.current).includes(CSS.escape(r.animationName));if(r.target===t&&i&&(c("ANIMATION_END"),!s.current)){const r=t.style.animationFillMode;t.style.animationFillMode="forwards",e=a.setTimeout(()=>{"forwards"===t.style.animationFillMode&&(t.style.animationFillMode=r)})}},o=e=>{e.target===t&&(i.current=ep(n.current))};return t.addEventListener("animationstart",o),t.addEventListener("animationcancel",r),t.addEventListener("animationend",r),()=>{a.clearTimeout(e),t.removeEventListener("animationstart",o),t.removeEventListener("animationcancel",r),t.removeEventListener("animationend",r)}}c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:r.useCallback(e=>{n.current=e?getComputedStyle(e):null,a(e)},[])}}(t),s="function"==typeof a?a({present:n.isPresent}):r.Children.only(a),i=ou(n.ref,function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,a=t&&"isReactWarning"in t&&t.isReactWarning;if(a)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,a=t&&"isReactWarning"in t&&t.isReactWarning,a)return e.props.ref;return e.props.ref||e.ref}(s));return"function"==typeof a||n.isPresent?r.cloneElement(s,{ref:i}):null};function ep(e){return e?.animationName||"none"}Zh.displayName="Presence";var tp=r[" useInsertionEffect ".trim().toString()]||mu;function ap({prop:e,defaultProp:t,onChange:a=()=>{},caller:n}){const[s,i,o]=function({defaultProp:e,onChange:t}){const[a,n]=r.useState(e),s=r.useRef(a),i=r.useRef(t);return tp(()=>{i.current=t},[t]),r.useEffect(()=>{s.current!==a&&(i.current?.(a),s.current=a)},[a,s]),[a,n,i]}({defaultProp:t,onChange:a}),l=void 0!==e,c=l?e:s;{const t=r.useRef(void 0!==e);r.useEffect(()=>{const e=t.current;if(e!==l){}t.current=l},[l,n])}const d=r.useCallback(t=>{if(l){const a=function(e){return"function"==typeof e}(t)?t(e):t;a!==e&&o.current?.(a)}else i(t)},[l,e,i,o]);return[c,d]}var rp="rovingFocusGroup.onEntryFocus",np={bubbles:!1,cancelable:!0},sp="RovingFocusGroup",[ip,op,lp]=lu(sp),[cp,dp]=ru(sp,[lp]),[up,mp]=cp(sp),hp=r.forwardRef((t,a)=>e(ip.Provider,{scope:t.__scopeRovingFocusGroup,children:e(ip.Slot,{scope:t.__scopeRovingFocusGroup,children:e(pp,{...t,ref:a})})}));hp.displayName=sp;var pp=r.forwardRef((t,a)=>{const{__scopeRovingFocusGroup:n,orientation:s,loop:i=!1,dir:o,currentTabStopId:l,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:m=!1,...h}=t,p=r.useRef(null),f=ou(a,p),g=du(o),[v,b]=ap({prop:l,defaultProp:c??null,onChange:d,caller:sp}),[y,w]=r.useState(!1),x=bu(u),N=op(n),k=r.useRef(!1),[C,S]=r.useState(0);return r.useEffect(()=>{const e=p.current;if(e)return e.addEventListener(rp,x),()=>e.removeEventListener(rp,x)},[x]),e(up,{scope:n,orientation:s,dir:g,loop:i,currentTabStopId:v,onItemFocus:r.useCallback(e=>b(e),[b]),onItemShiftTab:r.useCallback(()=>w(!0),[]),onFocusableItemAdd:r.useCallback(()=>S(e=>e+1),[]),onFocusableItemRemove:r.useCallback(()=>S(e=>e-1),[]),children:e(gu.div,{tabIndex:y||0===C?-1:0,"data-orientation":s,...h,ref:f,style:{outline:"none",...t.style},onMouseDown:uu(t.onMouseDown,()=>{k.current=!0}),onFocus:uu(t.onFocus,e=>{const t=!k.current;if(e.target===e.currentTarget&&t&&!y){const t=new CustomEvent(rp,np);if(e.currentTarget.dispatchEvent(t),!t.defaultPrevented){const e=N().filter(e=>e.focusable);bp([e.find(e=>e.active),e.find(e=>e.id===v),...e].filter(Boolean).map(e=>e.ref.current),m)}}k.current=!1}),onBlur:uu(t.onBlur,()=>w(!1))})})}),fp="RovingFocusGroupItem",gp=r.forwardRef((t,a)=>{const{__scopeRovingFocusGroup:n,focusable:s=!0,active:i=!1,tabStopId:o,children:l,...c}=t,d=fu(),u=o||d,m=mp(fp,n),h=m.currentTabStopId===u,p=op(n),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:v}=m;return r.useEffect(()=>{if(s)return f(),()=>g()},[s,f,g]),e(ip.ItemSlot,{scope:n,id:u,focusable:s,active:i,children:e(gu.span,{tabIndex:h?0:-1,"data-orientation":m.orientation,...c,ref:a,onMouseDown:uu(t.onMouseDown,e=>{s?m.onItemFocus(u):e.preventDefault()}),onFocus:uu(t.onFocus,()=>m.onItemFocus(u)),onKeyDown:uu(t.onKeyDown,e=>{if("Tab"===e.key&&e.shiftKey)return void m.onItemShiftTab();if(e.target!==e.currentTarget)return;const t=function(e,t,a){const r=function(e,t){return"rtl"!==t?e:"ArrowLeft"===e?"ArrowRight":"ArrowRight"===e?"ArrowLeft":e}(e.key,a);return"vertical"===t&&["ArrowLeft","ArrowRight"].includes(r)||"horizontal"===t&&["ArrowUp","ArrowDown"].includes(r)?void 0:vp[r]}(e,m.orientation,m.dir);if(void 0!==t){if(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey)return;e.preventDefault();let n=p().filter(e=>e.focusable).map(e=>e.ref.current);if("last"===t)n.reverse();else if("prev"===t||"next"===t){"prev"===t&&n.reverse();const s=n.indexOf(e.currentTarget);n=m.loop?(r=s+1,(a=n).map((e,t)=>a[(r+t)%a.length])):n.slice(s+1)}setTimeout(()=>bp(n))}var a,r}),children:"function"==typeof l?l({isCurrentTabStop:h,hasTabStop:null!=v}):l})})});gp.displayName=fp;var vp={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function bp(e,t=!1){const a=document.activeElement;for(const r of e){if(r===a)return;if(r.focus({preventScroll:t}),document.activeElement!==a)return}}var yp=hp,wp=gp,xp=new WeakMap,Np=new WeakMap,kp={},Cp=0,Sp=function(e){return e&&(e.host||Sp(e.parentNode))},Ep=function(e,t,a,r){var n=function(e,t){return t.map(function(t){if(e.contains(t))return t;var a=Sp(t);return a&&e.contains(a)?a:null}).filter(function(e){return Boolean(e)})}(t,Array.isArray(e)?e:[e]);kp[a]||(kp[a]=new WeakMap);var s=kp[a],i=[],o=new Set,l=new Set(n),c=function(e){e&&!o.has(e)&&(o.add(e),c(e.parentNode))};n.forEach(c);var d=function(e){e&&!l.has(e)&&Array.prototype.forEach.call(e.children,function(e){if(o.has(e))d(e);else try{var t=e.getAttribute(r),n=null!==t&&"false"!==t,l=(xp.get(e)||0)+1,c=(s.get(e)||0)+1;xp.set(e,l),s.set(e,c),i.push(e),1===l&&n&&Np.set(e,!0),1===c&&e.setAttribute(a,"true"),n||e.setAttribute(r,"true")}catch(u){}})};return d(t),o.clear(),Cp++,function(){i.forEach(function(e){var t=xp.get(e)-1,n=s.get(e)-1;xp.set(e,t),s.set(e,n),t||(Np.has(e)||e.removeAttribute(r),Np.delete(e)),n||e.removeAttribute(a)}),--Cp||(xp=new WeakMap,xp=new WeakMap,Np=new WeakMap,kp={})}},_p=function(e,t,a){void 0===a&&(a="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),n=function(e){return"undefined"==typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e);return n?(r.push.apply(r,Array.from(n.querySelectorAll("[aria-live], script"))),Ep(r,n,a,"aria-hidden")):function(){return null}},Pp=function(){return Pp=Object.assign||function(e){for(var t,a=1,r=arguments.length;a<r;a++)for(var n in t=arguments[a])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},Pp.apply(this,arguments)};function Rp(e,t){var a={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(a[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(a[r[n]]=e[r[n]])}return a}"function"==typeof SuppressedError&&SuppressedError;var Tp="right-scroll-bar-position",Ap="width-before-scroll-bar";function Ip(e,t){return"function"==typeof e?e(t):e&&(e.current=t),e}var Mp="undefined"!=typeof window?r.useLayoutEffect:r.useEffect,Op=new WeakMap;function Lp(e,t){var a,r,n,s=(a=null,r=function(t){return e.forEach(function(e){return Ip(e,t)})},n=d(function(){return{value:a,callback:r,facade:{get current(){return n.value},set current(e){var t=n.value;t!==e&&(n.value=e,n.callback(e,t))}}}})[0],n.callback=r,n.facade);return Mp(function(){var t=Op.get(s);if(t){var a=new Set(t),r=new Set(e),n=s.current;a.forEach(function(e){r.has(e)||Ip(e,null)}),r.forEach(function(e){a.has(e)||Ip(e,n)})}Op.set(s,e)},[e]),s}function Dp(e){return e}var Fp=function(e){var t=e.sideCar,a=Rp(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return r.createElement(n,Pp({},a))};Fp.isSideCarExport=!0;var jp=function(e){void 0===e&&(e={});var t=function(e,t){void 0===t&&(t=Dp);var a=[],r=!1;return{read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return a.length?a[a.length-1]:e},useMedium:function(e){var n=t(e,r);return a.push(n),function(){a=a.filter(function(e){return e!==n})}},assignSyncMedium:function(e){for(r=!0;a.length;){var t=a;a=[],t.forEach(e)}a={push:function(t){return e(t)},filter:function(){return a}}},assignMedium:function(e){r=!0;var t=[];if(a.length){var n=a;a=[],n.forEach(e),t=a}var s=function(){var a=t;t=[],a.forEach(e)},i=function(){return Promise.resolve().then(s)};i(),a={push:function(e){t.push(e),i()},filter:function(e){return t=t.filter(e),a}}}}}(null);return t.options=Pp({async:!0,ssr:!1},e),t}(),zp=function(){},$p=r.forwardRef(function(e,t){var a=r.useRef(null),n=r.useState({onScrollCapture:zp,onWheelCapture:zp,onTouchMoveCapture:zp}),s=n[0],i=n[1],o=e.forwardProps,l=e.children,c=e.className,d=e.removeScrollBar,u=e.enabled,m=e.shards,h=e.sideCar,p=e.noRelative,f=e.noIsolation,g=e.inert,v=e.allowPinchZoom,b=e.as,y=void 0===b?"div":b,w=e.gapMode,x=Rp(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=h,k=Lp([a,t]),C=Pp(Pp({},x),s);return r.createElement(r.Fragment,null,u&&r.createElement(N,{sideCar:jp,removeScrollBar:d,shards:m,noRelative:p,noIsolation:f,inert:g,setCallbacks:i,allowPinchZoom:!!v,lockRef:a,gapMode:w}),o?r.cloneElement(r.Children.only(l),Pp(Pp({},C),{ref:k})):r.createElement(y,Pp({},C,{className:c,ref:k}),l))});$p.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},$p.classNames={fullWidth:Ap,zeroRight:Tp};function Up(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=function(){if("undefined"!=typeof __webpack_nonce__)return __webpack_nonce__}();return t&&e.setAttribute("nonce",t),e}var Vp=function(){var e=0,t=null;return{add:function(a){var r,n;0==e&&(t=Up())&&(n=a,(r=t).styleSheet?r.styleSheet.cssText=n:r.appendChild(document.createTextNode(n)),function(e){(document.head||document.getElementsByTagName("head")[0]).appendChild(e)}(t)),e++},remove:function(){! --e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Wp=function(){var e,t=(e=Vp(),function(t,a){r.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&a])});return function(e){var a=e.styles,r=e.dynamic;return t(a,r),null}},Bp={left:0,top:0,right:0,gap:0},Hp=function(e){return parseInt(e||"",10)||0},qp=function(e){if(void 0===e&&(e="margin"),"undefined"==typeof window)return Bp;var t=function(e){var t=window.getComputedStyle(document.body),a=t["padding"===e?"paddingLeft":"marginLeft"],r=t["padding"===e?"paddingTop":"marginTop"],n=t["padding"===e?"paddingRight":"marginRight"];return[Hp(a),Hp(r),Hp(n)]}(e),a=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-a+t[2]-t[0])}},Kp=Wp(),Gp="data-scroll-locked",Xp=function(e,t,a,r){var n=e.left,s=e.top,i=e.right,o=e.gap;return void 0===a&&(a="margin"),"\n .".concat("with-scroll-bars-hidden"," {\n overflow: hidden ").concat(r,";\n padding-right: ").concat(o,"px ").concat(r,";\n }\n body[").concat(Gp,"] {\n overflow: hidden ").concat(r,";\n overscroll-behavior: contain;\n ").concat([t&&"position: relative ".concat(r,";"),"margin"===a&&"\n padding-left: ".concat(n,"px;\n padding-top: ").concat(s,"px;\n padding-right: ").concat(i,"px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(o,"px ").concat(r,";\n "),"padding"===a&&"padding-right: ".concat(o,"px ").concat(r,";")].filter(Boolean).join(""),"\n }\n \n .").concat(Tp," {\n right: ").concat(o,"px ").concat(r,";\n }\n \n .").concat(Ap," {\n margin-right: ").concat(o,"px ").concat(r,";\n }\n \n .").concat(Tp," .").concat(Tp," {\n right: 0 ").concat(r,";\n }\n \n .").concat(Ap," .").concat(Ap," {\n margin-right: 0 ").concat(r,";\n }\n \n body[").concat(Gp,"] {\n ").concat("--removed-body-scroll-bar-size",": ").concat(o,"px;\n }\n")},Jp=function(){var e=parseInt(document.body.getAttribute(Gp)||"0",10);return isFinite(e)?e:0},Qp=function(e){var t=e.noRelative,a=e.noImportant,n=e.gapMode,s=void 0===n?"margin":n;r.useEffect(function(){return document.body.setAttribute(Gp,(Jp()+1).toString()),function(){var e=Jp()-1;e<=0?document.body.removeAttribute(Gp):document.body.setAttribute(Gp,e.toString())}},[]);var i=r.useMemo(function(){return qp(s)},[s]);return r.createElement(Kp,{styles:Xp(i,!t,s,a?"":"!important")})},Yp=!1;if("undefined"!=typeof window)try{var Zp=Object.defineProperty({},"passive",{get:function(){return Yp=!0,!0}});window.addEventListener("test",Zp,Zp),window.removeEventListener("test",Zp,Zp)}catch(Fy){Yp=!1}var ef=!!Yp&&{passive:!1},tf=function(e,t){if(!(e instanceof Element))return!1;var a=window.getComputedStyle(e);return"hidden"!==a[t]&&!(a.overflowY===a.overflowX&&!function(e){return"TEXTAREA"===e.tagName}(e)&&"visible"===a[t])},af=function(e,t){var a=t.ownerDocument,r=t;do{if("undefined"!=typeof ShadowRoot&&r instanceof ShadowRoot&&(r=r.host),rf(e,r)){var n=nf(e,r);if(n[1]>n[2])return!0}r=r.parentNode}while(r&&r!==a.body);return!1},rf=function(e,t){return"v"===e?function(e){return tf(e,"overflowY")}(t):function(e){return tf(e,"overflowX")}(t)},nf=function(e,t){return"v"===e?[(a=t).scrollTop,a.scrollHeight,a.clientHeight]:function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]}(t);var a},sf=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},of=function(e){return[e.deltaX,e.deltaY]},lf=function(e){return e&&"current"in e?e.current:e},cf=function(e){return"\n .block-interactivity-".concat(e," {pointer-events: none;}\n .allow-interactivity-").concat(e," {pointer-events: all;}\n")},df=0,uf=[];function mf(e){for(var t=null;null!==e;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var hf,pf=(hf=function(e){var t=r.useRef([]),a=r.useRef([0,0]),n=r.useRef(),s=r.useState(df++)[0],i=r.useState(Wp)[0],o=r.useRef(e);r.useEffect(function(){o.current=e},[e]),r.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var t=function(e,t,a){if(a||2===arguments.length)for(var r,n=0,s=t.length;n<s;n++)!r&&n in t||(r||(r=Array.prototype.slice.call(t,0,n)),r[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))}([e.lockRef.current],(e.shards||[]).map(lf),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),t.forEach(function(e){return e.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var l=r.useCallback(function(e,t){if("touches"in e&&2===e.touches.length||"wheel"===e.type&&e.ctrlKey)return!o.current.allowPinchZoom;var r,s=sf(e),i=a.current,l="deltaX"in e?e.deltaX:i[0]-s[0],c="deltaY"in e?e.deltaY:i[1]-s[1],d=e.target,u=Math.abs(l)>Math.abs(c)?"h":"v";if("touches"in e&&"h"===u&&"range"===d.type)return!1;var m=af(u,d);if(!m)return!0;if(m?r=u:(r="v"===u?"h":"v",m=af(u,d)),!m)return!1;if(!n.current&&"changedTouches"in e&&(l||c)&&(n.current=r),!r)return!0;var h=n.current||r;return function(e,t,a,r){var n=function(e,t){return"h"===e&&"rtl"===t?-1:1}(e,window.getComputedStyle(t).direction),s=n*r,i=a.target,o=t.contains(i),l=!1,c=s>0,d=0,u=0;do{if(!i)break;var m=nf(e,i),h=m[0],p=m[1]-m[2]-n*h;(h||p)&&rf(e,i)&&(d+=p,u+=h);var f=i.parentNode;i=f&&f.nodeType===Node.DOCUMENT_FRAGMENT_NODE?f.host:f}while(!o&&i!==document.body||o&&(t.contains(i)||t===i));return(c&&Math.abs(d)<1||!c&&Math.abs(u)<1)&&(l=!0),l}(h,t,e,"h"===h?l:c)},[]),c=r.useCallback(function(e){var a=e;if(uf.length&&uf[uf.length-1]===i){var r="deltaY"in a?of(a):sf(a),n=t.current.filter(function(e){return e.name===a.type&&(e.target===a.target||a.target===e.shadowParent)&&(t=e.delta,n=r,t[0]===n[0]&&t[1]===n[1]);var t,n})[0];if(n&&n.should)a.cancelable&&a.preventDefault();else if(!n){var s=(o.current.shards||[]).map(lf).filter(Boolean).filter(function(e){return e.contains(a.target)});(s.length>0?l(a,s[0]):!o.current.noIsolation)&&a.cancelable&&a.preventDefault()}}},[]),d=r.useCallback(function(e,a,r,n){var s={name:e,delta:a,target:r,should:n,shadowParent:mf(r)};t.current.push(s),setTimeout(function(){t.current=t.current.filter(function(e){return e!==s})},1)},[]),u=r.useCallback(function(e){a.current=sf(e),n.current=void 0},[]),m=r.useCallback(function(t){d(t.type,of(t),t.target,l(t,e.lockRef.current))},[]),h=r.useCallback(function(t){d(t.type,sf(t),t.target,l(t,e.lockRef.current))},[]);r.useEffect(function(){return uf.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:h}),document.addEventListener("wheel",c,ef),document.addEventListener("touchmove",c,ef),document.addEventListener("touchstart",u,ef),function(){uf=uf.filter(function(e){return e!==i}),document.removeEventListener("wheel",c,ef),document.removeEventListener("touchmove",c,ef),document.removeEventListener("touchstart",u,ef)}},[]);var p=e.removeScrollBar,f=e.inert;return r.createElement(r.Fragment,null,f?r.createElement(i,{styles:cf(s)}):null,p?r.createElement(Qp,{noRelative:e.noRelative,gapMode:e.gapMode}):null)},jp.useMedium(hf),Fp),ff=r.forwardRef(function(e,t){return r.createElement($p,Pp({},e,{ref:t,sideCar:pf}))});ff.classNames=$p.classNames;var gf=["Enter"," "],vf=["ArrowUp","PageDown","End"],bf=["ArrowDown","PageUp","Home",...vf],yf={ltr:[...gf,"ArrowRight"],rtl:[...gf,"ArrowLeft"]},wf={ltr:["ArrowLeft"],rtl:["ArrowRight"]},xf="Menu",[Nf,kf,Cf]=lu(xf),[Sf,Ef]=ru(xf,[Cf,Ih,dp]),_f=Ih(),Pf=dp(),[Rf,Tf]=Sf(xf),[Af,If]=Sf(xf),Mf=t=>{const{__scopeMenu:a,open:n=!1,children:s,dir:i,onOpenChange:o,modal:l=!0}=t,c=_f(a),[d,u]=r.useState(null),m=r.useRef(!1),h=bu(o),p=du(i);return r.useEffect(()=>{const e=()=>{m.current=!0,document.addEventListener("pointerdown",t,{capture:!0,once:!0}),document.addEventListener("pointermove",t,{capture:!0,once:!0})},t=()=>m.current=!1;return document.addEventListener("keydown",e,{capture:!0}),()=>{document.removeEventListener("keydown",e,{capture:!0}),document.removeEventListener("pointerdown",t,{capture:!0}),document.removeEventListener("pointermove",t,{capture:!0})}},[]),e(Gh,{...c,children:e(Rf,{scope:a,open:n,onOpenChange:h,content:d,onContentChange:u,children:e(Af,{scope:a,onClose:r.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:p,modal:l,children:s})})})};Mf.displayName=xf;var Of=r.forwardRef((t,a)=>{const{__scopeMenu:r,...n}=t,s=_f(r);return e(Xh,{...s,...n,ref:a})});Of.displayName="MenuAnchor";var Lf="MenuPortal",[Df,Ff]=Sf(Lf,{forceMount:void 0}),jf=t=>{const{__scopeMenu:a,forceMount:r,children:n,container:s}=t,i=Tf(Lf,a);return e(Df,{scope:a,forceMount:r,children:e(Zh,{present:r||i.open,children:e(Yh,{asChild:!0,container:s,children:n})})})};jf.displayName=Lf;var zf="MenuContent",[$f,Uf]=Sf(zf),Vf=r.forwardRef((t,a)=>{const r=Ff(zf,t.__scopeMenu),{forceMount:n=r.forceMount,...s}=t,i=Tf(zf,t.__scopeMenu),o=If(zf,t.__scopeMenu);return e(Nf.Provider,{scope:t.__scopeMenu,children:e(Zh,{present:n||i.open,children:e(Nf.Slot,{scope:t.__scopeMenu,children:o.modal?e(Wf,{...s,ref:a}):e(Bf,{...s,ref:a})})})})}),Wf=r.forwardRef((t,a)=>{const n=Tf(zf,t.__scopeMenu),s=r.useRef(null),i=ou(a,s);return r.useEffect(()=>{const e=s.current;if(e)return _p(e)},[]),e(qf,{...t,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:uu(t.onFocusOutside,e=>e.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Bf=r.forwardRef((t,a)=>{const r=Tf(zf,t.__scopeMenu);return e(qf,{...t,ref:a,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),Hf=v("MenuContent.ScrollLock"),qf=r.forwardRef((t,a)=>{const{__scopeMenu:n,loop:s=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:l,disableOutsidePointerEvents:c,onEntryFocus:d,onEscapeKeyDown:u,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:p,onDismiss:f,disableOutsideScroll:g,...v}=t,b=Tf(zf,n),y=If(zf,n),w=_f(n),x=Pf(n),N=kf(n),[k,C]=r.useState(null),S=r.useRef(null),E=ou(a,S,b.onContentChange),_=r.useRef(0),P=r.useRef(""),R=r.useRef(0),T=r.useRef(null),A=r.useRef("right"),I=r.useRef(0),M=g?ff:r.Fragment,O=g?{as:Hf,allowPinchZoom:!0}:void 0,L=e=>{const t=P.current+e,a=N().filter(e=>!e.disabled),r=document.activeElement,n=a.find(e=>e.ref.current===r)?.textValue,s=function(e,t,a){const r=t.length>1&&Array.from(t).every(e=>e===t[0]),n=r?t[0]:t,s=a?e.indexOf(a):-1;let i=(o=e,l=Math.max(s,0),o.map((e,t)=>o[(l+t)%o.length]));var o,l;1===n.length&&(i=i.filter(e=>e!==a));const c=i.find(e=>e.toLowerCase().startsWith(n.toLowerCase()));return c!==a?c:void 0}(a.map(e=>e.textValue),t,n),i=a.find(e=>e.textValue===s)?.ref.current;!function e(t){P.current=t,window.clearTimeout(_.current),""!==t&&(_.current=window.setTimeout(()=>e(""),1e3))}(t),i&&setTimeout(()=>i.focus())};r.useEffect(()=>()=>window.clearTimeout(_.current),[]),r.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Pu()),document.body.insertAdjacentElement("beforeend",e[1]??Pu()),_u++,()=>{1===_u&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),_u--}},[]);const D=r.useCallback(e=>A.current===T.current?.side&&function(e,t){if(!t)return!1;const a={x:e.clientX,y:e.clientY};return function(e,t){const{x:a,y:r}=e;let n=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const e=t[s],o=t[i],l=e.x,c=e.y,d=o.x,u=o.y;c>r!=u>r&&a<(d-l)*(r-c)/(u-c)+l&&(n=!n)}return n}(a,t)}(e,T.current?.area),[]);return e($f,{scope:n,searchRef:P,onItemEnter:r.useCallback(e=>{D(e)&&e.preventDefault()},[D]),onItemLeave:r.useCallback(e=>{D(e)||(S.current?.focus(),C(null))},[D]),onTriggerLeave:r.useCallback(e=>{D(e)&&e.preventDefault()},[D]),pointerGraceTimerRef:R,onPointerGraceIntentChange:r.useCallback(e=>{T.current=e},[]),children:e(M,{...O,children:e(Iu,{asChild:!0,trapped:i,onMountAutoFocus:uu(o,e=>{e.preventDefault(),S.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e(Cu,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:p,onDismiss:f,children:e(yp,{asChild:!0,...x,dir:y.dir,orientation:"vertical",loop:s,currentTabStopId:k,onCurrentTabStopIdChange:C,onEntryFocus:uu(d,e=>{y.isUsingKeyboardRef.current||e.preventDefault()}),preventScrollOnEntryFocus:!0,children:e(Jh,{role:"menu","aria-orientation":"vertical","data-state":wg(b.open),"data-radix-menu-content":"",dir:y.dir,...w,...v,ref:E,style:{outline:"none",...v.style},onKeyDown:uu(v.onKeyDown,e=>{const t=e.target.closest("[data-radix-menu-content]")===e.currentTarget,a=e.ctrlKey||e.altKey||e.metaKey,r=1===e.key.length;t&&("Tab"===e.key&&e.preventDefault(),!a&&r&&L(e.key));const n=S.current;if(e.target!==n)return;if(!bf.includes(e.key))return;e.preventDefault();const s=N().filter(e=>!e.disabled).map(e=>e.ref.current);vf.includes(e.key)&&s.reverse(),function(e){const t=document.activeElement;for(const a of e){if(a===t)return;if(a.focus(),document.activeElement!==t)return}}(s)}),onBlur:uu(t.onBlur,e=>{e.currentTarget.contains(e.target)||(window.clearTimeout(_.current),P.current="")}),onPointerMove:uu(t.onPointerMove,kg(e=>{const t=e.target,a=I.current!==e.clientX;if(e.currentTarget.contains(t)&&a){const t=e.clientX>I.current?"right":"left";A.current=t,I.current=e.clientX}}))})})})})})})});Vf.displayName=zf;var Kf=r.forwardRef((t,a)=>{const{__scopeMenu:r,...n}=t;return e(gu.div,{role:"group",...n,ref:a})});Kf.displayName="MenuGroup";var Gf=r.forwardRef((t,a)=>{const{__scopeMenu:r,...n}=t;return e(gu.div,{...n,ref:a})});Gf.displayName="MenuLabel";var Xf="MenuItem",Jf="menu.itemSelect",Qf=r.forwardRef((t,a)=>{const{disabled:n=!1,onSelect:s,...i}=t,o=r.useRef(null),l=If(Xf,t.__scopeMenu),c=Uf(Xf,t.__scopeMenu),d=ou(a,o),u=r.useRef(!1);return e(Yf,{...i,ref:d,disabled:n,onClick:uu(t.onClick,()=>{const e=o.current;if(!n&&e){const t=new CustomEvent(Jf,{bubbles:!0,cancelable:!0});e.addEventListener(Jf,e=>s?.(e),{once:!0}),vu(e,t),t.defaultPrevented?u.current=!1:l.onClose()}}),onPointerDown:e=>{t.onPointerDown?.(e),u.current=!0},onPointerUp:uu(t.onPointerUp,e=>{u.current||e.currentTarget?.click()}),onKeyDown:uu(t.onKeyDown,e=>{const t=""!==c.searchRef.current;n||t&&" "===e.key||gf.includes(e.key)&&(e.currentTarget.click(),e.preventDefault())})})});Qf.displayName=Xf;var Yf=r.forwardRef((t,a)=>{const{__scopeMenu:n,disabled:s=!1,textValue:i,...o}=t,l=Uf(Xf,n),c=Pf(n),d=r.useRef(null),u=ou(a,d),[m,h]=r.useState(!1),[p,f]=r.useState("");return r.useEffect(()=>{const e=d.current;e&&f((e.textContent??"").trim())},[o.children]),e(Nf.ItemSlot,{scope:n,disabled:s,textValue:i??p,children:e(wp,{asChild:!0,...c,focusable:!s,children:e(gu.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":s||void 0,"data-disabled":s?"":void 0,...o,ref:u,onPointerMove:uu(t.onPointerMove,kg(e=>{if(s)l.onItemLeave(e);else if(l.onItemEnter(e),!e.defaultPrevented){e.currentTarget.focus({preventScroll:!0})}})),onPointerLeave:uu(t.onPointerLeave,kg(e=>l.onItemLeave(e))),onFocus:uu(t.onFocus,()=>h(!0)),onBlur:uu(t.onBlur,()=>h(!1))})})})}),Zf=r.forwardRef((t,a)=>{const{checked:r=!1,onCheckedChange:n,...s}=t;return e(og,{scope:t.__scopeMenu,checked:r,children:e(Qf,{role:"menuitemcheckbox","aria-checked":xg(r)?"mixed":r,...s,ref:a,"data-state":Ng(r),onSelect:uu(s.onSelect,()=>n?.(!!xg(r)||!r),{checkForDefaultPrevented:!1})})})});Zf.displayName="MenuCheckboxItem";var eg="MenuRadioGroup",[tg,ag]=Sf(eg,{value:void 0,onValueChange:()=>{}}),rg=r.forwardRef((t,a)=>{const{value:r,onValueChange:n,...s}=t,i=bu(n);return e(tg,{scope:t.__scopeMenu,value:r,onValueChange:i,children:e(Kf,{...s,ref:a})})});rg.displayName=eg;var ng="MenuRadioItem",sg=r.forwardRef((t,a)=>{const{value:r,...n}=t,s=ag(ng,t.__scopeMenu),i=r===s.value;return e(og,{scope:t.__scopeMenu,checked:i,children:e(Qf,{role:"menuitemradio","aria-checked":i,...n,ref:a,"data-state":Ng(i),onSelect:uu(n.onSelect,()=>s.onValueChange?.(r),{checkForDefaultPrevented:!1})})})});sg.displayName=ng;var ig="MenuItemIndicator",[og,lg]=Sf(ig,{checked:!1}),cg=r.forwardRef((t,a)=>{const{__scopeMenu:r,forceMount:n,...s}=t,i=lg(ig,r);return e(Zh,{present:n||xg(i.checked)||!0===i.checked,children:e(gu.span,{...s,ref:a,"data-state":Ng(i.checked)})})});cg.displayName=ig;var dg=r.forwardRef((t,a)=>{const{__scopeMenu:r,...n}=t;return e(gu.div,{role:"separator","aria-orientation":"horizontal",...n,ref:a})});dg.displayName="MenuSeparator";var ug=r.forwardRef((t,a)=>{const{__scopeMenu:r,...n}=t,s=_f(r);return e(Qh,{...s,...n,ref:a})});ug.displayName="MenuArrow";var mg="MenuSub",[hg,pg]=Sf(mg),fg=t=>{const{__scopeMenu:a,children:n,open:s=!1,onOpenChange:i}=t,o=Tf(mg,a),l=_f(a),[c,d]=r.useState(null),[u,m]=r.useState(null),h=bu(i);return r.useEffect(()=>(!1===o.open&&h(!1),()=>h(!1)),[o.open,h]),e(Gh,{...l,children:e(Rf,{scope:a,open:s,onOpenChange:h,content:u,onContentChange:m,children:e(hg,{scope:a,contentId:fu(),triggerId:fu(),trigger:c,onTriggerChange:d,children:n})})})};fg.displayName=mg;var gg="MenuSubTrigger",vg=r.forwardRef((t,a)=>{const n=Tf(gg,t.__scopeMenu),s=If(gg,t.__scopeMenu),i=pg(gg,t.__scopeMenu),o=Uf(gg,t.__scopeMenu),l=r.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:d}=o,u={__scopeMenu:t.__scopeMenu},m=r.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return r.useEffect(()=>m,[m]),r.useEffect(()=>{const e=c.current;return()=>{window.clearTimeout(e),d(null)}},[c,d]),e(Of,{asChild:!0,...u,children:e(Yf,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":wg(n.open),...t,ref:iu(a,i.onTriggerChange),onClick:e=>{t.onClick?.(e),t.disabled||e.defaultPrevented||(e.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:uu(t.onPointerMove,kg(e=>{o.onItemEnter(e),e.defaultPrevented||t.disabled||n.open||l.current||(o.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:uu(t.onPointerLeave,kg(e=>{m();const t=n.content?.getBoundingClientRect();if(t){const a=n.content?.dataset.side,r="right"===a,s=r?-5:5,i=t[r?"left":"right"],l=t[r?"right":"left"];o.onPointerGraceIntentChange({area:[{x:e.clientX+s,y:e.clientY},{x:i,y:t.top},{x:l,y:t.top},{x:l,y:t.bottom},{x:i,y:t.bottom}],side:a}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(e),e.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:uu(t.onKeyDown,e=>{const a=""!==o.searchRef.current;t.disabled||a&&" "===e.key||yf[s.dir].includes(e.key)&&(n.onOpenChange(!0),n.content?.focus(),e.preventDefault())})})})});vg.displayName=gg;var bg="MenuSubContent",yg=r.forwardRef((t,a)=>{const n=Ff(zf,t.__scopeMenu),{forceMount:s=n.forceMount,...i}=t,o=Tf(zf,t.__scopeMenu),l=If(zf,t.__scopeMenu),c=pg(bg,t.__scopeMenu),d=r.useRef(null),u=ou(a,d);return e(Nf.Provider,{scope:t.__scopeMenu,children:e(Zh,{present:s||o.open,children:e(Nf.Slot,{scope:t.__scopeMenu,children:e(qf,{id:c.contentId,"aria-labelledby":c.triggerId,...i,ref:u,align:"start",side:"rtl"===l.dir?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:e=>{l.isUsingKeyboardRef.current&&d.current?.focus(),e.preventDefault()},onCloseAutoFocus:e=>e.preventDefault(),onFocusOutside:uu(t.onFocusOutside,e=>{e.target!==c.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:uu(t.onEscapeKeyDown,e=>{l.onClose(),e.preventDefault()}),onKeyDown:uu(t.onKeyDown,e=>{const t=e.currentTarget.contains(e.target),a=wf[l.dir].includes(e.key);t&&a&&(o.onOpenChange(!1),c.trigger?.focus(),e.preventDefault())})})})})})});function wg(e){return e?"open":"closed"}function xg(e){return"indeterminate"===e}function Ng(e){return xg(e)?"indeterminate":e?"checked":"unchecked"}function kg(e){return t=>"mouse"===t.pointerType?e(t):void 0}yg.displayName=bg;var Cg=Mf,Sg=Of,Eg=jf,_g=Vf,Pg=Kf,Rg=Gf,Tg=Qf,Ag=Zf,Ig=rg,Mg=sg,Og=cg,Lg=dg,Dg=ug,Fg=fg,jg=vg,zg=yg,$g="Menubar",[Ug,Vg,Wg]=lu($g),[Bg]=ru($g,[Wg,dp]),Hg=Ef(),qg=dp(),[Kg,Gg]=Bg($g),Xg=r.forwardRef((t,a)=>{const{__scopeMenubar:n,value:s,onValueChange:i,defaultValue:o,loop:l=!0,dir:c,...d}=t,u=du(c),m=qg(n),[h,p]=ap({prop:s,onChange:i,defaultProp:o??"",caller:$g}),[f,g]=r.useState(null);return e(Kg,{scope:n,value:h,onMenuOpen:r.useCallback(e=>{p(e),g(e)},[p]),onMenuClose:r.useCallback(()=>p(""),[p]),onMenuToggle:r.useCallback(e=>{p(t=>t?"":e),g(e)},[p]),dir:u,loop:l,children:e(Ug.Provider,{scope:n,children:e(Ug.Slot,{scope:n,children:e(yp,{asChild:!0,...m,orientation:"horizontal",loop:l,dir:u,currentTabStopId:f,onCurrentTabStopIdChange:g,children:e(gu.div,{role:"menubar",...d,ref:a})})})})})});Xg.displayName=$g;var Jg="MenubarMenu",[Qg,Yg]=Bg(Jg),Zg=t=>{const{__scopeMenubar:a,value:n,...s}=t,i=fu(),o=n||i||"LEGACY_REACT_AUTO_VALUE",l=Gg(Jg,a),c=Hg(a),d=r.useRef(null),u=r.useRef(!1),m=l.value===o;return r.useEffect(()=>{m||(u.current=!1)},[m]),e(Qg,{scope:a,value:o,triggerId:fu(),triggerRef:d,contentId:fu(),wasKeyboardTriggerOpenRef:u,children:e(Cg,{...c,open:m,onOpenChange:e=>{e||l.onMenuClose()},modal:!1,dir:l.dir,...s})})};Zg.displayName=Jg;var ev="MenubarTrigger",tv=r.forwardRef((t,a)=>{const{__scopeMenubar:n,disabled:s=!1,...i}=t,o=qg(n),l=Hg(n),c=Gg(ev,n),d=Yg(ev,n),u=r.useRef(null),m=ou(a,u,d.triggerRef),[h,p]=r.useState(!1),f=c.value===d.value;return e(Ug.ItemSlot,{scope:n,value:d.value,disabled:s,children:e(wp,{asChild:!0,...o,focusable:!s,tabStopId:d.value,children:e(Sg,{asChild:!0,...l,children:e(gu.button,{type:"button",role:"menuitem",id:d.triggerId,"aria-haspopup":"menu","aria-expanded":f,"aria-controls":f?d.contentId:void 0,"data-highlighted":h?"":void 0,"data-state":f?"open":"closed","data-disabled":s?"":void 0,disabled:s,...i,ref:m,onPointerDown:uu(t.onPointerDown,e=>{s||0!==e.button||!1!==e.ctrlKey||(c.onMenuOpen(d.value),f||e.preventDefault())}),onPointerEnter:uu(t.onPointerEnter,()=>{Boolean(c.value)&&!f&&(c.onMenuOpen(d.value),u.current?.focus())}),onKeyDown:uu(t.onKeyDown,e=>{s||(["Enter"," "].includes(e.key)&&c.onMenuToggle(d.value),"ArrowDown"===e.key&&c.onMenuOpen(d.value),["Enter"," ","ArrowDown"].includes(e.key)&&(d.wasKeyboardTriggerOpenRef.current=!0,e.preventDefault()))}),onFocus:uu(t.onFocus,()=>p(!0)),onBlur:uu(t.onBlur,()=>p(!1))})})})})});tv.displayName=ev;var av=t=>{const{__scopeMenubar:a,...r}=t,n=Hg(a);return e(Eg,{...n,...r})};av.displayName="MenubarPortal";var rv="MenubarContent",nv=r.forwardRef((t,a)=>{const{__scopeMenubar:n,align:s="start",...i}=t,o=Hg(n),l=Gg(rv,n),c=Yg(rv,n),d=Vg(n),u=r.useRef(!1);return e(_g,{id:c.contentId,"aria-labelledby":c.triggerId,"data-radix-menubar-content":"",...o,...i,ref:a,align:s,onCloseAutoFocus:uu(t.onCloseAutoFocus,e=>{Boolean(l.value)||u.current||c.triggerRef.current?.focus(),u.current=!1,e.preventDefault()}),onFocusOutside:uu(t.onFocusOutside,e=>{const t=e.target;d().some(e=>e.ref.current?.contains(t))&&e.preventDefault()}),onInteractOutside:uu(t.onInteractOutside,()=>{u.current=!0}),onEntryFocus:e=>{c.wasKeyboardTriggerOpenRef.current||e.preventDefault()},onKeyDown:uu(t.onKeyDown,e=>{if(["ArrowRight","ArrowLeft"].includes(e.key)){const r=e.target,n=r.hasAttribute("data-radix-menubar-subtrigger"),s=r.closest("[data-radix-menubar-content]")!==e.currentTarget,i=("rtl"===l.dir?"ArrowRight":"ArrowLeft")===e.key;if(!i&&n)return;if(s&&i)return;let o=d().filter(e=>!e.disabled).map(e=>e.value);i&&o.reverse();const u=o.indexOf(c.value);o=l.loop?(a=u+1,(t=o).map((e,r)=>t[(a+r)%t.length])):o.slice(u+1);const[m]=o;m&&l.onMenuOpen(m)}var t,a},{checkForDefaultPrevented:!1}),style:{...t.style,"--radix-menubar-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-menubar-content-available-width":"var(--radix-popper-available-width)","--radix-menubar-content-available-height":"var(--radix-popper-available-height)","--radix-menubar-trigger-width":"var(--radix-popper-anchor-width)","--radix-menubar-trigger-height":"var(--radix-popper-anchor-height)"}})});nv.displayName=rv;var sv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Pg,{...s,...n,ref:a})});sv.displayName="MenubarGroup";var iv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Rg,{...s,...n,ref:a})});iv.displayName="MenubarLabel";var ov=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Tg,{...s,...n,ref:a})});ov.displayName="MenubarItem";var lv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Ag,{...s,...n,ref:a})});lv.displayName="MenubarCheckboxItem";var cv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Ig,{...s,...n,ref:a})});cv.displayName="MenubarRadioGroup";var dv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Mg,{...s,...n,ref:a})});dv.displayName="MenubarRadioItem";var uv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Og,{...s,...n,ref:a})});uv.displayName="MenubarItemIndicator";var mv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Lg,{...s,...n,ref:a})});mv.displayName="MenubarSeparator";r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(Dg,{...s,...n,ref:a})}).displayName="MenubarArrow";var hv="MenubarSub",pv=t=>{const{__scopeMenubar:a,children:r,open:n,onOpenChange:s,defaultOpen:i}=t,o=Hg(a),[l,c]=ap({prop:n,defaultProp:i??!1,onChange:s,caller:hv});return e(Fg,{...o,open:l,onOpenChange:c,children:r})};pv.displayName=hv;var fv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(jg,{"data-radix-menubar-subtrigger":"",...s,...n,ref:a})});fv.displayName="MenubarSubTrigger";var gv=r.forwardRef((t,a)=>{const{__scopeMenubar:r,...n}=t,s=Hg(r);return e(zg,{...s,"data-radix-menubar-content":"",...n,ref:a,style:{...t.style,"--radix-menubar-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-menubar-content-available-width":"var(--radix-popper-available-width)","--radix-menubar-content-available-height":"var(--radix-popper-available-height)","--radix-menubar-trigger-width":"var(--radix-popper-anchor-width)","--radix-menubar-trigger-height":"var(--radix-popper-anchor-height)"}})});gv.displayName="MenubarSubContent";var vv=Xg,bv=tv,yv=av,wv=nv,xv=iv,Nv=ov,kv=lv,Cv=dv,Sv=uv,Ev=mv,_v=fv,Pv=gv;const Rv=Zg,Tv=sv,Av=yv,Iv=pv,Mv=cv,Ov=r.forwardRef(({className:t,...a},r)=>e(vv,{ref:r,className:sr("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",t),...a}));Ov.displayName=vv.displayName;const Lv=r.forwardRef(({className:t,...a},r)=>e(bv,{ref:r,className:sr("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",t),...a}));Lv.displayName=bv.displayName;const Dv=r.forwardRef(({className:a,inset:r,children:n,...s},i)=>t(_v,{ref:i,className:sr("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",a),...s,children:[n,e($,{className:"ml-auto h-4 w-4"})]}));Dv.displayName=_v.displayName;const Fv=r.forwardRef(({className:t,...a},r)=>e(Pv,{ref:r,className:sr("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a}));Fv.displayName=Pv.displayName;const jv=r.forwardRef(({className:t,align:a="start",alignOffset:r=-4,sideOffset:n=8,...s},i)=>e(yv,{children:e(wv,{ref:i,align:a,alignOffset:r,sideOffset:n,className:sr("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...s})}));jv.displayName=wv.displayName;const zv=r.forwardRef(({className:t,inset:a,...r},n)=>e(Nv,{ref:n,className:sr("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a&&"pl-8",t),...r}));zv.displayName=Nv.displayName;const $v=r.forwardRef(({className:a,children:r,checked:n,...s},i)=>t(kv,{ref:i,className:sr("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:n,...s,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Sv,{children:e(T,{className:"h-4 w-4"})})}),r]}));$v.displayName=kv.displayName;const Uv=r.forwardRef(({className:a,children:r,...n},s)=>t(Cv,{ref:s,className:sr("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...n,children:[e("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e(Sv,{children:e(U,{className:"h-2 w-2 fill-current"})})}),r]}));Uv.displayName=Cv.displayName;const Vv=r.forwardRef(({className:t,inset:a,...r},n)=>e(xv,{ref:n,className:sr("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...r}));Vv.displayName=xv.displayName;const Wv=r.forwardRef(({className:t,...a},r)=>e(Ev,{ref:r,className:sr("-mx-1 my-1 h-px bg-muted",t),...a}));Wv.displayName=Ev.displayName;const Bv=({className:t,...a})=>e("span",{className:sr("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});Bv.displayname="MenubarShortcut";const Hv={light:"",dark:".dark"},qv=r.createContext(null);function Kv(){const e=r.useContext(qv);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Gv=r.forwardRef(({id:a,className:n,children:s,config:i,...o},l)=>{const c=r.useId(),d=`chart-${a||c.replace(/:/g,"")}`;return e(qv.Provider,{value:{config:i},children:t("div",{"data-chart":d,ref:l,className:sr("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",n),...o,children:[e(Xv,{id:d,config:i}),e(aa.ResponsiveContainer,{children:s})]})})});Gv.displayName="Chart";const Xv=({id:t,config:a})=>{const r=Object.entries(a).filter(([,e])=>e.theme||e.color);return r.length?e("style",{dangerouslySetInnerHTML:{__html:Object.entries(Hv).map(([e,a])=>`\n${a} [data-chart=${t}] {\n${r.map(([t,a])=>{const r=a.theme?.[e]||a.color;return r?` --color-${t}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},Jv=aa.Tooltip,Qv=r.forwardRef(({active:n,payload:s,className:i,indicator:o="dot",hideLabel:l=!1,hideIndicator:c=!1,label:d,labelFormatter:u,labelClassName:m,formatter:h,color:p,nameKey:f,labelKey:g},v)=>{const{config:b}=Kv(),y=r.useMemo(()=>{if(l||!s?.length)return null;const[t]=s,a=eb(b,t,`${g||t?.dataKey||t?.name||"value"}`),r=g||"string"!=typeof d?a?.label:b[d]?.label||d;return u?e("div",{className:sr("font-medium",m),children:u(r,s)}):r?e("div",{className:sr("font-medium",m),children:r}):null},[d,u,s,l,m,b,g]);if(!n||!s?.length)return null;const w=1===s.length&&"dot"!==o;return t("div",{ref:v,className:sr("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",i),children:[w?null:y,e("div",{className:"grid gap-1.5",children:s.map((r,n)=>{const s=`${f||r.name||r.dataKey||"value"}`,i=eb(b,r,s),l=p||r.payload?.fill||r.color;return e("div",{className:sr("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:h&&void 0!==r?.value&&r.name?h(r.value,r.name,r,n,r.payload):t(a,{children:[i?.icon?e(i.icon,{}):!c&&e("div",{className:sr("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":w&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),t("div",{className:sr("flex flex-1 justify-between leading-none",w?"items-end":"items-center"),children:[t("div",{className:"grid gap-1.5",children:[w?y:null,e("span",{className:"text-muted-foreground",children:i?.label||r.name})]}),void 0!==r.value&&e("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof r.value?r.value.toLocaleString():r.value})]})]})},r.dataKey||n)})})]})});Qv.displayName="ChartTooltip";const Yv=aa.Legend,Zv=r.forwardRef(({className:a,hideIcon:r=!1,payload:n,verticalAlign:s="bottom",nameKey:i},o)=>{const{config:l}=Kv();return n?.length?e("div",{ref:o,className:sr("flex items-center justify-center gap-4","top"===s?"pb-3":"pt-3",a),children:n.map(a=>{const n=`${i||a.dataKey||"value"}`,s=eb(l,a,n);return t("div",{className:sr("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[s?.icon&&!r?e(s.icon,{}):e("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:a.color}}),s?.label]},a.value)})}):null});function eb(e,t,a){if("object"!=typeof t||null===t)return;const r="payload"in t&&"object"==typeof t.payload&&null!==t.payload?t.payload:void 0;let n=a;return a in t&&"string"==typeof t[a]?n=t[a]:r&&a in r&&"string"==typeof r[a]&&(n=r[a]),n in e?e[n]:e[a]}Zv.displayName="ChartLegend";const tb=({onClick:t,isActive:a,disabled:r,children:n,title:s})=>e("button",{type:"button",onClick:t,disabled:r,title:s,className:sr("p-1.5 rounded hover:bg-muted transition-colors",a?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),ab=()=>e("div",{className:"w-px h-5 bg-border mx-1"}),rb=({value:a,onChange:n,disabled:s,placeholder:i="Escreva o conteúdo aqui...",minHeight:o="300px",showModeToggle:l=!0,showVariableHint:u=!0,className:m})=>{const[h,p]=d("visual"),f=ra({extensions:[sa.configure({heading:{levels:[1,2,3]}}),ia,oa.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),la,ca,da.configure({multicolor:!0})],content:a||"",editable:!s,onUpdate:({editor:e})=>{n(e.getHTML())}});r.useEffect(()=>{f&&a!==f.getHTML()&&f.commands.setContent(a||"")},[a,f]);const g=c(()=>{if(!f)return;const e=f.getAttributes("link").href,t=window.prompt("URL",e);null!==t&&(""!==t?f.chain().focus().extendMarkRange("link").setLink({href:t}).run():f.chain().focus().extendMarkRange("link").unsetLink().run())},[f]);return f?t("div",{className:sr("space-y-2",m),children:[l&&t("div",{className:"flex justify-between items-center",children:[t("div",{className:"flex gap-1",children:[t(mr,{type:"button",size:"sm",variant:"visual"===h?"default":"outline",onClick:()=>p("visual"),disabled:s,children:[e(Ke,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),t(mr,{type:"button",size:"sm",variant:"code"===h?"default":"outline",onClick:()=>p("code"),disabled:s,children:[e(Ge,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),t(mr,{type:"button",size:"sm",variant:"preview"===h?"default":"outline",onClick:()=>p("preview"),disabled:s,children:[e(se,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),u&&t("p",{className:"text-xs text-muted-foreground",children:["Use ",e("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===h&&t("div",{className:"border rounded-md overflow-hidden bg-background",children:[t("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e(tb,{onClick:()=>f.chain().focus().toggleHeading({level:1}).run(),isActive:f.isActive("heading",{level:1}),disabled:s,title:"Título 1",children:e(Xe,{className:"h-4 w-4"})}),e(tb,{onClick:()=>f.chain().focus().toggleHeading({level:2}).run(),isActive:f.isActive("heading",{level:2}),disabled:s,title:"Título 2",children:e(Je,{className:"h-4 w-4"})}),e(tb,{onClick:()=>f.chain().focus().toggleHeading({level:3}).run(),isActive:f.isActive("heading",{level:3}),disabled:s,title:"Título 3",children:e(Qe,{className:"h-4 w-4"})}),e(ab,{}),e(tb,{onClick:()=>f.chain().focus().toggleBold().run(),isActive:f.isActive("bold"),disabled:s,title:"Negrito",children:e(Ye,{className:"h-4 w-4"})}),e(tb,{onClick:()=>f.chain().focus().toggleItalic().run(),isActive:f.isActive("italic"),disabled:s,title:"Itálico",children:e(Ze,{className:"h-4 w-4"})}),e(tb,{onClick:()=>f.chain().focus().toggleUnderline().run(),isActive:f.isActive("underline"),disabled:s,title:"Sublinhado",children:e(et,{className:"h-4 w-4"})}),e(tb,{onClick:()=>f.chain().focus().toggleStrike().run(),isActive:f.isActive("strike"),disabled:s,title:"Riscado",children:e(tt,{className:"h-4 w-4"})}),e(ab,{}),e(tb,{onClick:()=>f.chain().focus().toggleBulletList().run(),isActive:f.isActive("bulletList"),disabled:s,title:"Lista",children:e(at,{className:"h-4 w-4"})}),e(tb,{onClick:()=>f.chain().focus().toggleOrderedList().run(),isActive:f.isActive("orderedList"),disabled:s,title:"Lista Ordenada",children:e(rt,{className:"h-4 w-4"})}),e(ab,{}),e(tb,{onClick:()=>f.chain().focus().toggleHighlight().run(),isActive:f.isActive("highlight"),disabled:s,title:"Destacar",children:e(nt,{className:"h-4 w-4"})}),e(tb,{onClick:g,isActive:f.isActive("link"),disabled:s,title:"Link",children:e(st,{className:"h-4 w-4"})}),e(ab,{}),e(tb,{onClick:()=>f.chain().focus().unsetAllMarks().clearNodes().run(),disabled:s,title:"Limpar Formatação",children:e(it,{className:"h-4 w-4"})}),e(ab,{}),e(tb,{onClick:()=>f.chain().focus().undo().run(),disabled:s||!f.can().undo(),title:"Desfazer",children:e(ot,{className:"h-4 w-4"})}),e(tb,{onClick:()=>f.chain().focus().redo().run(),disabled:s||!f.can().redo(),title:"Refazer",children:e(lt,{className:"h-4 w-4"})})]}),e(na,{editor:f,className:sr("prose prose-sm max-w-none p-4 focus:outline-none","[&_.ProseMirror]:outline-none","[&_.ProseMirror_p.is-editor-empty:first-child::before]:text-muted-foreground","[&_.ProseMirror_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]","[&_.ProseMirror_p.is-editor-empty:first-child::before]:float-left","[&_.ProseMirror_p.is-editor-empty:first-child::before]:h-0","[&_.ProseMirror_p.is-editor-empty:first-child::before]:pointer-events-none"),style:{minHeight:o}})]}),"code"===h&&e("textarea",{value:a||"",onChange:e=>n(e.target.value),disabled:s,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:o},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===h&&e("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:o},children:e("div",{className:"bg-background shadow-sm rounded border p-4",children:e("div",{dangerouslySetInnerHTML:{__html:a||`<p class="text-muted-foreground">${i}</p>`}})})})]}):null};function nb({label:a,onClick:r,icon:n,actions:s=[],variant:i="default",size:o="default",disabled:l=!1,loading:c=!1,menuAlign:d="end",className:u}){const m=l||c;if(!(s.length>0))return t(mr,{variant:i,size:o,disabled:m,onClick:r,className:u,children:[c?e(A,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,a]});return t("div",{className:sr("inline-flex rounded-md shadow-sm",u),children:[t(mr,{variant:i,size:o,disabled:m,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[c?e(A,{className:"mr-2 h-4 w-4 animate-spin"}):n?e(n,{className:"mr-2 h-4 w-4"}):null,a]}),t(Ci,{children:[e(Si,{asChild:!0,children:e(mr,{variant:i,size:o,disabled:m,className:sr("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":"Mais opções",children:e(P,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),e(Ii,{align:d,className:"min-w-[160px]",children:s.map(a=>{const r=a.icon;return t(Mi,{onClick:a.onClick,disabled:a.disabled,className:sr("destructive"===a.variant&&"text-destructive focus:text-destructive"),children:[r&&e(r,{className:"mr-2 h-4 w-4"}),a.label]},a.id)})})]})]})}function sb({manager:a,config:r,onEdit:n,onDelete:s}){const{t:i}=Kn();return a.isLoading?e(Pc,{children:Array.from({length:3}).map((a,r)=>t(vr,{children:[t(br,{children:[e(kn,{className:"h-4 w-3/4"}),e(kn,{className:"h-3 w-1/2"})]}),e(xr,{children:t("div",{className:"space-y-2",children:[e(kn,{className:"h-3 w-full"}),e(kn,{className:"h-3 w-2/3"})]})})]},r))}):e(pc.Root,{children:a.entities.map(a=>t(pc.Item,{onClick:()=>n(a),children:[e(br,{className:"pb-3",children:t("div",{className:"flex items-start justify-between",children:[t("div",{className:"flex-1 min-w-0",children:[e(yr,{className:"text-base leading-6 truncate",children:a.title||a.name||i("no_title")}),e(wr,{className:"text-sm",children:k(new Date(a.created_at),"dd/MM/yyyy HH:mm",{locale:mc})})]}),t("div",{className:"flex items-center gap-2 ml-2",children:[a.link&&e(mr,{variant:"external-link",size:"icon-xs",onClick:e=>{e.stopPropagation(),(e=>{try{const t=window.open(e,"_blank");t&&!t.closed&&void 0!==t.closed||(navigator.clipboard.writeText(e),C.info(i("link_copied")))}catch(t){window.location.href=e}})(a.link)},title:i("open_external_link"),children:e(ct,{className:"h-4 w-4"})}),e("div",{onClick:e=>e.stopPropagation(),children:e(to,{onEdit:()=>n(a),onDelete:s?()=>s(a):void 0,canDelete:!!s})})]})]})}),e(xr,{className:"pt-0",children:e("div",{className:"space-y-2",children:r.cardFields?.map(t=>{const r=a[t.key];return r?e(pc.Field,{label:t.label,value:t.render?t.render(r,a):String(r)},String(t.key)):null})})})]},a.id))})}function ib({data:a,columns:r,sortField:n,sortDirection:s,onSort:i,onRowClick:l,renderActions:c,isLoading:d=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:h=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:g,isAllSelected:v=!1,enableColumnResize:b=!1,enableRowResize:y=!1,onColumnResize:w,onRowResize:x,storageKey:N}){const{columnWidths:k,isDragging:C,activeColumn:S,handleMouseDown:E}=ro({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:N?`${N}-columns`:void 0,onResize:w,enabled:b}),{isDragging:_,activeRow:P,handleMouseDown:R,getRowHeight:T}=no({rowIds:a.map(e=>e.id),storageKey:N?`${N}-rows`:void 0,onResize:x,enabled:y}),A=o(()=>{if(b)return r.map(e=>`${k[String(e.key)]??e.width??e.minWidth??150}px`);const e=r.reduce((e,t)=>t.width?e:e+(t.weight??1),0);return r.map(t=>{if(t.width)return`${t.width}px`;if(t.minWidth&&!t.weight)return`${t.minWidth}px`;const a=(t.weight??1)/e*100;return t.minWidth?`minmax(${t.minWidth}px, ${a}%)`:`${a}%`})},[r,b,k]);if(d)return e("div",{className:"flex-1 overflow-auto",children:e("div",{className:"p-4 space-y-3",children:[...Array(5)].map((t,a)=>e(kn,{className:"h-12 w-full"},a))})});if(0===a.length)return e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:u})})});return e("div",{className:"flex-1 overflow-auto "+(C||_?"select-none":""),children:t(ri,{className:m,children:[e(ni,{className:"sticky top-0 bg-background z-10",children:t(oi,{children:[h&&e(li,{className:"w-[40px]",children:e(an,{checked:v,onCheckedChange:g,"aria-label":"Selecionar todos"})}),r.map((a,r)=>{const o=b&&!1!==a.resizable,l=S===String(a.key);return t(li,{className:`${a.className||""} relative`,style:{width:A[r]},children:[a.sortable&&i?t("button",{onClick:()=>i(String(a.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[a.header,(c=String(a.key),n!==c?e(K,{size:14,className:"ml-1 opacity-50"}):e("asc"===s?G:X,{size:14,className:"ml-1"}))]}):e("span",{className:"font-medium",children:a.header}),o&&e(ki,{direction:"horizontal",onMouseDown:e=>E(String(a.key),e),isDragging:l})]},String(a.key));var c}),c&&e(li,{className:"w-[80px] text-right",children:"Ações"})]})}),e(si,{children:a.map(a=>{const n=y?T(a.id):void 0,s=P===a.id;return t(oi,{onClick:()=>l?.(a),className:(l?"cursor-pointer":"")+" relative",style:n?{height:`${n}px`}:void 0,children:[h&&e(ci,{children:e(an,{checked:p.includes(a.id),onCheckedChange:()=>f?.(a.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${a.id}`})}),r.map(t=>e(ci,{className:t.className,children:e(Ni,{children:t.render?t.render(a):String(a[t.key]??"-")})},String(t.key))),c&&e(ci,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(a)}),y&&e(ki,{direction:"vertical",onMouseDown:e=>R(a.id,e),isDragging:s})]},a.id)})})]})})}function ob({onEdit:a,onDelete:r,onToggleStatus:n,isActive:s=!0,canEdit:i=!0,canDelete:o=!0,customActions:l=[],renderAs:c="dropdown",variant:d="default"}){const{t:u}=Kn(),m=[];return a&&i&&m.push({icon:V,label:u("edit"),onClick:a,variant:"default"}),n&&m.push({icon:s?W:B,label:u(s?"deactivate":"activate"),onClick:n,variant:"default"}),l.forEach(e=>{!1!==e.show&&m.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),r&&o&&m.push({icon:H,label:u("remove"),onClick:r,variant:"destructive"}),0===m.length?null:"dropdown"===c?t(Ci,{children:[e(Si,{asChild:!0,children:e(mr,{variant:"ghost",size:"compact"===d?"sm":"default",className:"compact"===d?"h-7 px-2":"",children:e(E,{size:"compact"===d?14:16})})}),e(Ii,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:m.map((a,r)=>t(Mi,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},r))})]}):e("div",{className:"flex items-center gap-1",children:m.map((a,r)=>t(mr,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===d?"sm":"default",onClick:a.onClick,className:"compact"===d?"h-7 px-2":"",children:[a.icon&&e(a.icon,{size:"compact"===d?14:16}),"compact"!==d&&e("span",{className:"ml-1",children:a.label})]},r))})}function lb({searchValue:a="",onSearchChange:r,customFilters:n=[],onClearFilters:s,showClearButton:i=!0,layout:o="horizontal"}){const{t:l}=Kn(),c=a||n.length>0;return t("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&t("div",{className:"relative flex-1 min-w-[200px]",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(pr,{type:"text",placeholder:l("search"),value:a,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((t,a)=>e("div",{className:"vertical"===o?"w-full":"",children:t},a)),i&&c&&s&&t(mr,{variant:"ghost",size:"sm",onClick:s,className:"h-9 px-3 whitespace-nowrap",children:[e(_,{size:14,className:"mr-1"}),l("clear_filters")]})]})}function cb({data:t,renderCard:a,isLoading:r=!1,emptyMessage:n="Nenhum item encontrado",columns:s,gap:i="md",className:o}){return r?e(Pc,{cols:s?String(s):"auto-fit",gap:i,className:o,children:[...Array(6)].map((t,a)=>e(kn,{className:"h-48 w-full"},a))}):0===t.length?e("div",{className:"flex items-center justify-center p-8",children:e("div",{className:"text-center text-muted-foreground",children:e("p",{children:n})})}):e(Pc,{cols:s?String(s):"auto-fit",gap:i,className:o,children:t.map(a)})}function db(e){const t=Lt();return{onNew:()=>{const a=e.newPath||`${e.basePath}/new`;t(a)},onEdit:a=>{const r=e.editPath?e.editPath.replace(":id",a.id):`${e.basePath}/${a.id}/edit`;t(r)}}}function ub(e,t){const a=db({basePath:e,newPath:t.newPath,editPath:t.editPath});return{useCustomRouting:!0,onNew:a.onNew,onEdit:a.onEdit}}const mb=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],hb=[{value:"dd/MM/yyyy HH:mm",label:"dd/MM/yyyy HH:mm",example:"28/11/2024 14:30",description:"Padrão Brasileiro"},{value:"MM/dd/yyyy hh:mm a",label:"MM/dd/yyyy hh:mm a",example:"11/28/2024 02:30 PM",description:"Padrão Americano (12h)"},{value:"MM/dd/yyyy HH:mm",label:"MM/dd/yyyy HH:mm",example:"11/28/2024 14:30",description:"Padrão Americano (24h)"},{value:"yyyy-MM-dd HH:mm",label:"yyyy-MM-dd HH:mm",example:"2024-11-28 14:30",description:"ISO 8601"},{value:"dd.MM.yyyy HH:mm",label:"dd.MM.yyyy HH:mm",example:"28.11.2024 14:30",description:"Padrão Europeu"},{value:"d MMM yyyy, HH:mm",label:"d MMM yyyy, HH:mm",example:"28 Nov 2024, 14:30",description:"Formato Longo"}],pb=[{value:"America/Sao_Paulo",label:"Brasília (UTC-3)",offset:"-03:00"},{value:"America/Noronha",label:"Fernando de Noronha (UTC-2)",offset:"-02:00"},{value:"America/Manaus",label:"Manaus (UTC-4)",offset:"-04:00"},{value:"America/Rio_Branco",label:"Rio Branco (UTC-5)",offset:"-05:00"},{value:"America/New_York",label:"New York (UTC-5/-4)",offset:"-05:00"},{value:"America/Chicago",label:"Chicago (UTC-6/-5)",offset:"-06:00"},{value:"America/Los_Angeles",label:"Los Angeles (UTC-8/-7)",offset:"-08:00"},{value:"Europe/London",label:"Londres (UTC+0/+1)",offset:"+00:00"},{value:"Europe/Paris",label:"Paris (UTC+1/+2)",offset:"+01:00"},{value:"Europe/Berlin",label:"Berlim (UTC+1/+2)",offset:"+01:00"},{value:"Asia/Tokyo",label:"Tóquio (UTC+9)",offset:"+09:00"},{value:"Australia/Sydney",label:"Sydney (UTC+10/+11)",offset:"+10:00"}],fb=()=>{const{locale:a,datetimeFormat:r,timezone:n,setLocale:s,setDatetimeFormat:i,setTimezone:o}=cl(),{t:l}=Kn();return t("div",{className:"space-y-4 p-4",children:[t("div",{children:[t("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e(dt,{className:"h-4 w-4"}),l("language")]}),t(qr,{value:a,onValueChange:s,children:[e(Xr,{children:e(Gr,{})}),e(Yr,{children:mb.map(e=>t(en,{value:e.value,children:[e.flag," ",e.label]},e.value))})]})]}),t("div",{children:[t("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e(we,{className:"h-4 w-4"}),l("timezone")||"Fuso Horário"]}),t(qr,{value:n,onValueChange:o,children:[e(Xr,{children:e(Gr,{})}),e(Yr,{children:pb.map(t=>e(en,{value:t.value,children:t.label},t.value))})]})]}),t("div",{children:[t("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e(Me,{className:"h-4 w-4"}),l("dateTimeFormat")||"Formato de Data/Hora"]}),t(qr,{value:r,onValueChange:i,children:[e(Xr,{children:e(Gr,{})}),e(Yr,{children:hb.map(a=>e(en,{value:a.value,children:t("div",{className:"flex flex-col items-start",children:[e("span",{children:a.label}),t("span",{className:"text-xs text-muted-foreground",children:[a.description," • ",a.example]})]})},a.value))})]})]})]})},gb=n.memo(({variant:r="card",className:s="",selectedUnit:i,onUnitChange:o})=>{const{user:l,companies:c,alias:u,isAuthenticated:m,logout:h,switchUnit:p}=ei(),[f,g]=d(!1),v="true"===import.meta.env.VITE_SHOW_USER_PREFERENCES,b=c?.[0]||null,y=u?c?.find(e=>e.alias===u):b,w=c||[],x=i||y||b||b,N=n.useCallback(e=>{o?o(e):p(e)},[o,p]),k=n.useMemo(()=>{if(!w?.length)return[];const e=new Map;w.forEach(t=>{e.set(t.alias,t)});const t=Array.from(e.values()),a=t.find(e=>e.alias===x?.alias),r=t.filter(e=>e.alias!==x?.alias);return r.sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"})),a?[a,...r]:r},[w,x?.alias]);if(!m||!l)return null;const C=()=>t(a,{children:[t("div",{className:"flex items-center space-x-3",children:[e("div",{className:"flex-shrink-0",children:e("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e(Fe,{className:"h-5 w-5 text-primary-foreground"})})}),t("div",{className:"flex-1 min-w-0",children:[e("p",{className:"text-sm font-medium truncate",children:l.name}),t("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",x?.name||"N/A"]})]})]}),x&&e("div",{className:"mt-3",children:t("div",{className:"flex items-center space-x-2",children:[e(ut,{className:"h-4 w-4 text-muted-foreground"}),e("span",{className:"text-sm font-medium",children:x.name})]})}),k.length>1&&t("div",{className:"mt-2",children:[t("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",k.length]}),t("div",{className:"flex flex-wrap gap-1",children:[k.slice(0,3).map(t=>e(sn,{variant:t.alias===x?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>N(t),children:t.name},t.alias)),k.length>3&&t(sn,{variant:"outline",className:"text-xs",children:["+",k.length-3]})]})]})]});return"dropdown"===r?t(Ci,{children:[e(Si,{asChild:!0,children:e(mr,{variant:"ghost",className:`h-auto p-2 ${s}`,children:t("div",{className:"flex items-center space-x-2",children:[t("div",{className:"hidden md:block text-left",children:[e("p",{className:"text-sm font-medium",children:l.name}),e("p",{className:"text-xs text-muted-foreground",children:x?.name||"N/A"})]}),e("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e(Fe,{className:"h-4 w-4 text-primary-foreground"})}),e(P,{className:"h-4 w-4"})]})})}),t(Ii,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[t(Pi,{children:[t(Ti,{children:[e(We,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e(Ai,{children:k.map(a=>t(Mi,{onClick:()=>N(a),className:a.alias===x?.alias?"bg-muted":"",children:[e(ut,{className:"mr-2 h-4 w-4"}),a.name,a.alias===x?.alias&&e(sn,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},a.alias))})]}),v&&e(Fi,{}),v&&t(Mi,{onClick:()=>g(!0),children:[e(De,{className:"mr-2 h-4 w-4"}),"Preferências"]}),t(Mi,{onClick:h,children:[e(mt,{className:"mr-2 h-4 w-4"}),"Sair"]})]}),v&&e(Cr,{open:f,onOpenChange:g,children:t(Tr,{children:[e(Ar,{children:e(Or,{children:"Preferências de Internacionalização"})}),e(fb,{})]})})]}):t(vr,{className:s,children:[e(br,{children:e(yr,{className:"text-lg",children:"Informações do Usuário"})}),t(xr,{className:"space-y-4",children:[e(C,{}),e(kr,{}),v&&t(mr,{variant:"outline",onClick:()=>g(!0),size:"sm",className:"w-full",children:[e(De,{className:"mr-2 h-4 w-4"}),"Preferências"]}),t(mr,{variant:"outline",onClick:h,size:"sm",className:"w-full",children:[e(mt,{className:"mr-2 h-4 w-4"}),"Sair"]}),v&&e(Cr,{open:f,onOpenChange:g,children:t(Tr,{children:[e(Ar,{children:e(Or,{children:"Preferências de Internacionalização"})}),e(fb,{})]})})]})]})}),vb=s({});function bb({children:t,config:a}){const r=o(()=>({navigation:a?.navigation,appName:a?.appName}),[a?.navigation,a?.appName]);return e(vb.Provider,{value:r,children:t})}function yb(){return i(vb)}function wb(){const e=Ot(),{navigation:t}=yb(),{t:a}=Kn();if(!t)return a("page");const r=t.find(t=>t.path===e.pathname);if(r)return r.label;const n=t.find(t=>e.pathname.startsWith(t.path+"/"));return n?.label||a("page")}function xb(e,t){const[a,r]=d(e),n=l(),s=c(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return u(()=>(s(),n.current=setTimeout(()=>{r(e)},t),s),[e,t,s]),[a,s]}const Nb=h(function({actions:a}){const r=Ot(),n=wb(),{navigation:s,appName:i}=yb(),{metadata:o,headerActions:l}=Go(),{t:c}=Kn(),{companies:m,alias:h,isSearchVisible:p,clearSearch:f,refreshData:g,switchUnit:v}=ei(),b=h?m?.find(e=>e.alias===h)||m?.[0]||null:m?.[0]||null,[y,w]=Mt(),[x,N]=d(()=>y.get("search")||""),[k,C]=xb(x,Ts.debounceDelay);u(()=>{if(!p)return;const e=new URLSearchParams(y);k?(e.set("search",k),e.set("page","1")):e.delete("search"),w(e)},[k,w,p]);const S=s?.find(e=>e.path===r.pathname)||s?.find(e=>r.pathname.startsWith(e.path+"/")),E=o.title||n,P=o.subtitle||S?.complementaryText||c("item_details");return e("header",{className:"bg-background border-b border-border px-2 md:px-4 py-2",children:t("div",{className:"flex items-center gap-4",children:[t("div",{className:"flex-shrink-0",children:[t("div",{className:"flex items-center gap-2 mb-1",children:[e("h1",{className:"text-lg font-semibold text-foreground truncate",children:E}),e(sn,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:i||c("module")})]}),P&&e("p",{className:"text-sm text-muted-foreground truncate",children:P})]}),p&&t("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[t("div",{className:"relative flex-1",children:[e(j,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e(pr,{placeholder:c("search"),value:x,onChange:e=>(e=>{N(e)})(e.target.value),className:"w-full pl-10 pr-8"}),x&&e(mr,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-muted",onClick:()=>{C(),N("");const e=new URLSearchParams(y);e.delete("search"),e.delete("page"),w(e)},title:c("clear_search"),children:e(_,{size:14})})]}),e(mr,{variant:"outline",size:"sm",onClick:g,className:"flex-shrink-0 h-10 w-10 p-0",title:c("refresh_data"),children:e(We,{size:14})})]}),t("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(l||a)&&e("div",{className:"flex items-center gap-2",children:l||a}),import.meta.env.VITE_WIKI_URL&&e(mr,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>nr(import.meta.env.VITE_WIKI_URL,e),title:c("open_wiki"),children:"Wiki"}),e("div",{className:"text-sm",children:e(gb,{variant:"dropdown",selectedUnit:b,onUnitChange:v})})]})]})})}),kb=({key:e,enabled:t,checkFn:a,staleTime:r=3e5,gcTime:n=6e5})=>Rt({queryKey:["permission",e],queryFn:a,enabled:t,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1}),Cb=(e={})=>{const{enabled:t=!0}=e,{alias:a}=ei();return Rt({queryKey:["active-modules",a],queryFn:async()=>{if(!a)return[];const e=vs(),{data:t,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",a).eq("status","active").order("name");if(r){if(!Ns.handleError(r))throw r;return[]}return t||[]},enabled:t&&!!a})},Sb="forlogic-sidebar-pinned",Eb=()=>{try{const e=localStorage.getItem(Sb);return!!e&&JSON.parse(e)}catch{return!1}},_b=e=>{const t=["border-l-yellow-400","border-l-green-400","border-l-blue-400","border-l-red-400","border-l-purple-400","border-l-pink-400"];return t[e%t.length]},Pb=`https://${import.meta.env.VITE_SUPABASE_PROJECT_ID_STORAGE??import.meta.env.VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,Rb={logo:`${Pb}/${Ls.isQualiex?"logo-qualiex.svg":"logo.svg"}`,smallLogo:`${Pb}/${Ls.isQualiex?"small-forlogic.svg":"small.svg"}`},Tb=Rb.logo,Ab=Rb.smallLogo;function Ib({appName:r,isPinned:n,onPinToggle:s,open:i,dropdownOpen:o,onDropdownChange:l}){const{t:c}=Kn(),{data:d,isLoading:u,error:m}=Cb({enabled:o}),h=e=>{((e,t)=>{const a=e?.find(e=>e.url===t);a?.url&&window.open(a.url,"_blank")})(d,e)};return t(Ed,{className:"p-0 gap-0",children:[e("div",{className:"flex items-center justify-between h-[34px]",children:i?t(a,{children:[e("div",{className:"flex items-center pl-[12px]",children:e("img",{src:Rb.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e("button",{onClick:s,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(n?"bg-primary/20 text-primary":"hover:bg-muted text-muted-foreground"),children:e(qe,{className:"h-4 w-4"})})]}):e("div",{className:"flex items-center justify-center w-full h-[34px]",children:e("img",{src:Rb.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e("div",{className:"mt-2 pt-0",children:t(Ci,{onOpenChange:l,children:[e(Si,{asChild:!0,children:i?t("div",{className:"bg-muted hover:bg-muted/80 text-foreground font-medium text-sm flex items-center justify-between cursor-pointer transition-all duration-200 h-8 px-3 gap-3 rounded-md w-full",children:[t("div",{className:"flex items-center gap-2 min-w-0",children:[e("img",{src:"https://ccjfvpnndclajkleyqkc.supabase.co/storage/v1/object/public/library-assets/composit.svg",alt:"Menu",className:"h-6 w-6 text-muted-foreground flex-shrink-0"}),e("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:r})]}),e(P,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e("div",{className:"flex items-center justify-center w-full h-8 bg-muted hover:bg-muted/80 rounded-md cursor-pointer transition-all duration-200 p-[5px]",children:e(P,{className:"h-6 w-6 text-muted-foreground"})})}),e(Ii,{className:i?"w-80 bg-popover rounded-lg shadow-lg border border-border p-4 z-50":"w-[58px] bg-popover rounded-lg shadow-lg border border-border p-2 z-50",align:i?"start":"center",children:u?t("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e(A,{className:"h-4 w-4 animate-spin"}),e("span",{className:"text-sm",children:c("loading")})]}):m?t("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e(F,{className:"h-4 w-4"}),e("span",{className:"text-sm",children:c("error")})]}):d&&0!==d.length?e("div",{className:"space-y-2",children:d.map((a,r)=>e("div",{onClick:()=>h(a.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${_b(r)} transition-colors duration-200\n `,children:t("div",{className:"flex items-center justify-between",children:[e("span",{className:"font-medium text-foreground text-sm",children:a.name}),a.url&&e(ct,{className:"h-4 w-4 text-muted-foreground"})]})},a.id))}):e("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:c("no_results")})})]})})]})}function Mb({config:r,isCollapsed:n=!1,isDisabled:s=!1,className:i}){const{actions:o,triggerLabel:l="Criar",triggerIcon:c=q}=r;if(!o||0===o.length)return null;const d=(r,s,i=!1)=>t(a,{children:[r,!n&&s&&e("span",{className:"truncate",children:s}),!n&&i&&e(P,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(o.length>1)){const a=o[0],r=a.icon||c,l=s||a.disabled,u=e(mr,{onClick:a.onClick,disabled:l,className:sr("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:d(e(r,{className:"h-4 w-4 shrink-0"}),a.label)});return n?t(yi,{children:[e(wi,{asChild:!0,children:u}),e(xi,{side:"right",children:e("p",{children:a.label})})]}):u}const u=e(mr,{disabled:s,className:sr("w-full gap-2 justify-start",n&&"justify-center px-2",i),variant:"outline",size:"default",children:d(e(c,{className:"h-4 w-4 shrink-0"}),l,!0)});return t(Ci,{children:[e(Si,{asChild:!0,children:n?t(yi,{children:[e(wi,{asChild:!0,children:u}),e(xi,{side:"right",children:e("p",{children:l})})]}):u}),e(Ii,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:o.map(a=>{const r=a.icon;return t(Mi,{onClick:a.onClick,disabled:a.disabled,className:"cursor-pointer",children:[r&&e(r,{className:"mr-2 h-4 w-4"}),a.label]},a.id)})})]})}function Ob({direction:e="right",minWidth:t=224,maxWidth:a=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:s,isOpen:i=!0}={}){const[o,m]=d(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[h,p]=d(!1),f=l(null);u(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(i?e.style.setProperty("--sidebar-width",`${o}px`):e.style.setProperty("--sidebar-width","240px"))},[o,i]);const g=c(e=>{e.preventDefault(),p(!0)},[]);return u(()=>{if(!h)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(t,Math.min(a,n)),m(n),s?.(n)},i=()=>{p(!1),localStorage.setItem(n,o.toString())};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",i),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",i)}},[h,e,t,a,o,n,s]),u(()=>{h?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[h,e]),{width:o,isDragging:h,dragRef:f,handleMouseDown:g}}const Lb=s(void 0);function Db({children:t}){const[a,r]=d(new Set),[n,s]=d(!1),i=c(e=>{r(t=>{const a=new Set(t);return a.add(e),a})},[]),l=c(e=>{r(t=>{const a=new Set(t);return a.delete(e),a})},[]),u=c(e=>{s(e)},[]),m=o(()=>a.size>0||n,[a,n]),h=o(()=>({openModals:a,hasOpenModal:m,registerModal:i,unregisterModal:l,setHasOpenModal:u}),[a,m,i,l,u]);return e(Lb.Provider,{value:h,children:t})}function Fb(){const e=i(Lb);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function jb(){const{hasOpenModal:e}=Fb();return e}function zb({config:a,customContent:r,resizable:n=!1,minWidth:s=224,maxWidth:i=384}={}){const{t:o}=Kn(),{open:c,setOpen:m}=yd(),h=Ot(),{alias:p,user:f}=ei(),{hasOpenModal:g}=Fb(),[v,b]=d(!1),[y,w]=d(Eb),[x,N]=d(!1),k=l(!1),C=n?Ob({minWidth:s,maxWidth:i,storageKey:"app-sidebar-width",isOpen:c}):null;u(()=>{m(!!y||!(!x&&!v))},[y,x,v,m]);return t(xd,{collapsible:"icon",onMouseEnter:()=>{y||k.current||N(!0)},onMouseLeave:()=>{y||N(!1)},className:"app-sidebar bg-background border-r border-border py-6 px-3",style:C&&c?{width:`${C.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e(Ib,{appName:a?.appName||o("module_title"),isPinned:y,onPinToggle:()=>{const e=!y;w(e),(e=>{try{localStorage.setItem(Sb,JSON.stringify(e))}catch{}})(e),e||(k.current=!0,N(!1),m(!1),setTimeout(()=>{k.current=!1},300))},open:c,dropdownOpen:v,onDropdownChange:b}),a?.moduleActions&&a.moduleActions.actions.length>0&&e("div",{className:"px-3 py-2",children:e(bi,{children:e(Mb,{config:a.moduleActions,isCollapsed:!c,isDisabled:g})})}),e(Rd,{children:r||e(Td,{className:"p-0 mt-6",children:e(Md,{children:e(Od,{className:"space-y-2",children:e(bi,{children:a?.navigation?.map((a,r)=>{const n=({item:a,index:r})=>{const s=`${a.path}-${r}-${p??"noalias"}-${f?.id??"nouser"}`,{data:i=!0,isLoading:l}=kb({key:s,enabled:Boolean(a.permissionCheck&&p&&f?.id),checkFn:a.permissionCheck||(()=>Promise.resolve(!0))}),c=a.permissionCheck&&!i;if(c&&"Admin"===a.label)return null;const d=l?A:c?oe:a.icon;c?o("restricted_access"):a.complementaryText;return a.children&&a.children.length>0?e(ul,{defaultOpen:!0,className:"group/collapsible",children:t(Ld,{children:[e(ml,{asChild:!0,children:e(Fd,{size:"lg",className:"h-10",children:t("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label}),e($,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e(hl,{children:e(Ud,{children:a.children.map((t,a)=>e(n,{item:t,index:a},t.path))})})]})},a.path):e(Ld,{children:c||l?t(yi,{children:[e(wi,{asChild:!0,children:e(Fd,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:t("div",{className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-4 w-4 "+(l?"animate-spin":"")})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})}),e(xi,{children:e("p",{children:o(l?"checking_access":"restricted_access")})})]}):e(Fd,{asChild:!0,isActive:(u=a.path,h.pathname===u||h.pathname.startsWith(u+"/")),size:"lg",className:"h-10",children:t(Dt,{to:a.path,className:"flex w-full items-center gap-3",children:[e("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e(d,{className:"h-5 w-4"})}),e("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:a.label})]})})},a.path);var u};return e(n,{item:a,index:r},a.path)})})})})})}),n&&C&&c&&e("div",{ref:C.dragRef,onMouseDown:C.handleMouseDown,className:sr("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",C.isDragging&&"bg-primary/40")})]})}const $b=h(function({children:a,sidebar:r,sidebarConfig:n,showHeader:s=!0}){const i=o(()=>r||e(zb,{config:n}),[r,n]),l=o(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e(bb,{config:n,children:e(Ko,{children:e(wd,{defaultOpen:!1,style:l,children:t("div",{className:"sidebar-container min-h-screen flex w-full",children:[i,t("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[s&&e("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e(Nb,{})}),e("div",{className:"flex-1 overflow-y-auto bg-muted/30",children:a})]})]})})})})}),Ub={"pt-BR":mc,"en-US":Zl,"es-ES":ic},Vb=(e,t="pt-BR")=>{if(!e)return"";const a=x(e);if(!N(a))return"Invalid date";return k(a,"PP",{locale:Ub[t]||mc})},Wb=()=>{const{locale:e,timezone:t,datetimeFormat:a}=cl();return{formatDatetime:e=>((e,t="dd/MM/yyyy HH:mm")=>{if(!e)return"";const a=x(e);return N(a)?k(a,t):"Invalid date"})(e,a,t),formatDate:t=>Vb(t,e),locale:e,timezone:t,datetimeFormat:a}};class Bb{static async sendEmail(e){const t=vs(),{data:a,error:r}=await t.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return a}}const Hb=Bb;function qb({open:a,onOpenChange:r,placeId:n,placeName:s,onMakeManager:i,onMakeMembers:l,currentManagerId:c,currentMemberIds:u=[]}){const{t:m}=Kn(),[h,p]=d([]),[f,g]=d(!1),[v,b]=d(""),{data:y=[],isLoading:w}=go({enabled:a}),x=o(()=>{let e=[...y];if(e.sort((e,t)=>{const a=e.userName?.toLowerCase()||"",r=t.userName?.toLowerCase()||"";return a.localeCompare(r)}),v){const t=v.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(t)||e.userEmail?.toLowerCase().includes(t))}return e},[y,v]),N=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},k=1===h.length,C=h.length>0;return e(Cr,{open:a,onOpenChange:r,children:t(Tr,{className:"max-w-2xl",children:[e(Ar,{children:t(Or,{className:"flex items-center gap-2",children:[e(ht,{className:"h-5 w-5"}),"Gerenciar Acessos - ",s]})}),t("div",{className:"relative",children:[e(j,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e(pr,{placeholder:m("search_placeholder"),value:v,onChange:e=>b(e.target.value),className:"pl-9"})]}),e(uo,{className:"h-[400px] pr-4",children:w?e("div",{className:"space-y-2",children:[...Array(5)].map((t,a)=>e(kn,{className:"h-16 w-full"},a))}):0===x.length?t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e(ht,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e("p",{className:"text-sm text-muted-foreground",children:v?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e("div",{className:"space-y-2",children:x.map(a=>{const r=a.userId===c,n=u.includes(a.userId||""),s=h.includes(a.userId||"");return t("div",{className:sr("flex items-center gap-3 p-3 rounded-lg border transition-colors",s&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(a.userId||""),children:[e(an,{checked:s,onCheckedChange:()=>N(a.userId||""),onClick:e=>e.stopPropagation()}),t("div",{className:"flex-1",children:[t("div",{className:"flex items-center gap-2",children:[e("p",{className:"font-medium",children:a.userName}),r&&e(pt,{className:"h-4 w-4 text-yellow-500"})]}),e("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(r||n)&&e("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},a.userId)})})}),t(Mr,{className:"flex gap-2 sm:gap-2",children:[e("div",{className:"flex-1 text-sm text-muted-foreground",children:h.length>0&&t("span",{children:[h.length," selecionado(s)"]})}),k&&i&&t(mr,{onClick:async()=>{if(i&&1===h.length){g(!0);try{await i(h[0],n),p([])}finally{g(!1)}}},disabled:f,variant:"outline",children:[e(pt,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&l&&t(mr,{onClick:async()=>{if(l&&0!==h.length){g(!0);try{await l(h,n),p([])}finally{g(!1)}}},disabled:f,children:[e(ft,{className:"h-4 w-4 mr-2"}),"Tornar ",h.length>1?"Membros":"Membro"]})]})]})})}function Kb({place:a,level:r=0,manageAccessConfig:n}){const[s,i]=d(!1),[o,l]=d(!1),c=a.subPlaces&&a.subPlaces.length>0,u=a.isActive??!0,m=a.usersCount??0;return t("div",{children:[t(ul,{open:s,onOpenChange:i,children:[t("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[c?t(ml,{className:"flex items-center gap-2 flex-1",children:[e($,{className:sr("h-4 w-4 transition-transform shrink-0",s&&"rotate-90")}),e(ut,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:a.name}),t("span",{className:"text-sm text-muted-foreground",children:["(",a.subPlaces.length,")"]})]}):t("div",{className:"flex items-center gap-2 flex-1",children:[e("div",{className:"w-4 shrink-0"}),e(ut,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e("span",{className:"font-medium",children:a.name})]}),t("div",{className:"flex items-center gap-3 ml-auto",children:[t("div",{className:"flex items-center gap-1.5",children:[e(ht,{className:"h-3.5 w-3.5 text-muted-foreground"}),e("span",{className:"text-sm text-muted-foreground",children:m})]}),e(sn,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),n&&e(ob,{customActions:[{label:"Gerenciar Acessos",icon:De,onClick:()=>l(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e(hl,{children:a.subPlaces.map(t=>e(Kb,{place:t,level:r+1,manageAccessConfig:n},t.id))})]}),0===r&&e(kr,{}),n&&e(qb,{open:o,onOpenChange:l,placeId:a.id,placeName:a.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(a.id),currentMemberIds:n.getCurrentMemberIds?.(a.id)})]})}function Gb({places:a,isLoading:r,manageAccessConfig:n}){const{t:s}=Kn();return r?e("div",{className:"flex items-center justify-center py-12",children:t("div",{className:"text-center space-y-2",children:[e("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e("p",{className:"text-sm text-muted-foreground",children:s("loading_data")})]})}):a&&0!==a.length?t("div",{className:"space-y-1",children:[e("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(t=>e(Kb,{place:t,manageAccessConfig:n},t.id))]}):t("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e(ut,{className:"h-12 w-12 text-muted-foreground/50"}),t("div",{children:[e("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}var Xb=Object.defineProperty,Jb=(e,t,a)=>((e,t,a)=>t in e?Xb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const Qb=new class{constructor(){Jb(this,"baseUrl",import.meta.env.VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const r=Cs.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=os.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!a||""===a.trim())throw new Error("Alias da unidade é obrigatório");const s=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{s.searchParams.append(e,t)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":a}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const t=new Map,a=[];return e.forEach(e=>{t.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=t.get(e.id);if(e.parentId){const n=t.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):a.push(r)}else a.push(r)}),a}async getPlaces(e,t){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(a){if(await Cs.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),r=a.data||a||[];return this.buildHierarchy(r)}catch(r){return ds.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return ds.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};function Yb(e,t){const a=e.map(e=>({...e})),r=new Set(a.filter(e=>!t.has(e.id_user)).map(e=>e.id_user));return a.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let t=e.id_leader;for(;t&&r.has(t);){const e=a.find(e=>e.id_user===t);t=e?.id_leader||null}e.id_leader=t}}),a.filter(e=>t.has(e.id_user))}function Zb(e){const t=new Map,a=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};t.set(e.id,r),a.set(e.id_user,r)}),e.forEach(e=>{const n=t.get(e.id);if(e.id_leader){const t=a.get(e.id_leader);if(t)return void t.children.push(n)}r.push(n)});const n=(e,t)=>{e.level=t,e.children.forEach(e=>n(e,t+1))};r.forEach(e=>n(e,0));const s=e=>{e.sort((e,t)=>{const a=e.name||e.id_user||e.email||"",r=t.name||t.id_user||t.email||"";return a.localeCompare(r)}),e.forEach(e=>e.children.length>0&&s(e.children))};return s(r),r}function ey(e){const t=[],a=e=>{t.push(e),e.children.forEach(a)};return e.forEach(a),t}function ty(){const{alias:e,isAuthenticated:t}=ei(),a=os.getAccessToken(),{data:r=[]}=go({enabled:!0});return Rt({queryKey:["leadership",e,r.length],queryFn:async()=>{if(!a||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=vs(),{data:n,error:s}=await t.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!n||0===n.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=n.map(e=>({...e,name:i[e.id_user]?.name||"[Não encontrado]",email:i[e.id_user]?.email||"",subordinatesCount:n.filter(t=>t.id_leader===e.id_user).length})),l=new Set(n.map(e=>e.id_user));return new Set(n.filter(e=>e.id_leader&&!l.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const t=i[e];o.push({id:`virtual-${e}`,alias:n[0]?.alias||"",id_user:e,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:t?.name||"[Não encontrado]",email:t?.email||"",subordinatesCount:n.filter(t=>t.id_leader===e).length})}),Zb(o)},enabled:!!a&&!!e&&t&&r.length>0})}function ay(){const e="common",{alias:t}=ei(),a=Pt(),r=vs();return Tt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");if(a.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");if((await r.schema(e).from("leaders").select("id").eq("alias",t).eq("id_user",a.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");a.id_leader&&await ly(r,t,e,a.id_user,a.id_leader);const{data:n,error:s}=await r.schema(e).from("leaders").insert({alias:t,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),C.success("Líder adicionado com sucesso")},onError:e=>{C.error(e.message||"Erro ao adicionar líder")}})}function ry(){const e="common",{alias:t}=ei(),a=Pt(),r=vs();return Tt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");if(a.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await ly(r,t,e,a.id_user,a.id_leader);const{data:n,error:s}=await r.schema(e).from("leaders").insert({alias:t,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),C.success("Líder virtual promovido com sucesso")},onError:e=>{C.error(e.message||"Erro ao criar líder")}})}function ny(){const e="common",{alias:t}=ei(),a=Pt(),r=vs();return Tt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");if(!a.users.length)throw new Error("Selecione pelo menos um liderado");const n=a.users.map(e=>e.id_user),{data:s}=await r.schema(e).from("leaders").select("id_user").eq("alias",t).in("id_user",n).eq("is_removed",!1);if(s&&s.length>0){const e=s.map(e=>e.id_user);throw new Error(`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`)}for(const c of a.users){if(a.id_leader&&c.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await ly(r,t,e,c.id_user,a.id_leader)}const i=a.users.map(e=>({alias:t,id_user:e.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await r.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),C.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{C.error(e.message||"Erro ao adicionar liderados")}})}function sy(){const e="common",{alias:t}=ei(),a=Pt(),r=vs();return Tt({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");const{data:n}=await r.schema(e).from("leaders").select("id_user").eq("id",a.id).eq("alias",t).single();if(!n)throw new Error("Líder não encontrado");if(n.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await ly(r,t,e,n.id_user,a.id_leader,a.id);const{data:s,error:i}=await r.schema(e).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",t).select().single();if(i)throw i;return s},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),C.success("Líder atualizado com sucesso")},onError:e=>{C.error(e.message||"Erro ao atualizar líder")}})}function iy(){const{alias:e}=ei(),t=Pt(),a=vs();return Tt({mutationFn:async t=>{if(!e)throw new Error("Unidade não selecionada");const{error:r}=await a.schema("common").from("leaders").update({is_removed:!0}).eq("id",t).eq("alias",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",e]}),C.success("Líder removido com sucesso")},onError:e=>{C.error(e.message||"Erro ao remover líder")}})}function oy(){const e="common",{alias:t}=ei(),a=Pt(),r=vs();return Tt({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!t)throw new Error("Unidade não selecionada");const s=n.map(e=>e.id_user),i=await Promise.all([r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).eq("id_leader",a),r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).in("id_user",s.length?s:["__none__"])]),[{data:o,error:l},{data:c,error:d}]=i;if(l)throw l;if(d)throw d;const u=o||[],m=c||[],h=new Set(s),p=u.filter(e=>!h.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),v=n.filter(e=>!g.has(e.id_user));for(const w of f)await ly(r,t,e,w.id_user,a,w.id);for(const w of v){if(w.id_user===a)throw new Error("Usuário não pode ser seu próprio líder");await ly(r,t,e,w.id_user,a)}const b=[];if(p.length){const a=p.map(e=>e.id);b.push(r.schema(e).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",t))}if(f.length){const n=f.map(e=>e.id);b.push(r.schema(e).from("leaders").update({id_leader:a}).in("id",n).eq("alias",t))}if(v.length){const n=v.map(e=>({alias:t,id_user:e.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(r.schema(e).from("leaders").insert(n))}const y=(await Promise.all(b)).find(e=>e?.error);if(y?.error)throw y.error;return{unlinked:p.length,updated:f.length,created:v.length}},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),C.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{C.error(e.message||"Erro ao sincronizar subordinados")}})}async function ly(e,t,a,r,n,s){const{data:i,error:o}=await e.schema(a).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(o)throw o;const l=s?i.filter(e=>e.id!==s):i,c=new Set;let d=n;for(;d;){if(c.has(d))throw new Error("Esta associação criaria um ciclo na hierarquia");if(d===r)throw new Error("Esta associação criaria um ciclo na hierarquia");c.add(d);const e=l.find(e=>e.id_user===d);d=e?.id_leader||null}}function cy({leader:r,expandedIds:n,onToggleExpand:s,onEdit:i}){const o=n.has(r.id),l=r.children.length>0,c=32*r.level;return t(a,{children:[t("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e("td",{className:"py-3 px-4",children:t("div",{className:"flex items-center gap-2",style:{paddingLeft:`${c}px`},children:[l?e("button",{onClick:()=>s(r.id),className:"p-1 hover:bg-accent rounded",children:e(o?P:$,{className:"h-4 w-4"})}):e("div",{className:"w-6"}),e(Fe,{className:"h-4 w-4 text-muted-foreground"}),e("button",{onClick:()=>{i(r)},className:"font-medium hover:text-primary hover:underline text-left",children:r.name||r.id_user||r.email})]})}),e("td",{className:"py-3 px-4 text-center",children:e("span",{className:"text-sm",children:r.subordinatesCount||0})})]}),l&&o&&r.children.map(t=>e(cy,{leader:t,expandedIds:n,onToggleExpand:s,onEdit:i},t.id))]})}var dy=function(e,t){for(var a={};e.length;){var r=e[0],n=r.code,s=r.message,i=r.path.join(".");if(!a[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];a[i]={message:o.message,type:o.code}}else a[i]={message:s,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=a[i].types,c=l&&l[r.code];a[i]=Nt(i,t,a,n,c?[].concat(c,r.message):r.message)}e.shift()}return a},uy=function(e,t,a){return void 0===a&&(a={}),function(r,n,s){try{return Promise.resolve(function(n,i){try{var o=Promise.resolve(e["sync"===a.mode?"parse":"parseAsync"](r,t)).then(function(e){return s.shouldUseNativeValidation&&ma({},s),{errors:{},values:a.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:ha(dy(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const my=ua.object({id_leader:ua.string().nullable(),id_users:ua.array(ua.string()).min(1,"Selecione pelo menos um liderado")}),hy=ua.object({id_leader:ua.string().nullable(),id_users:ua.array(ua.string())});function py({value:a,onChange:r,excludeUserIds:n=[],error:s}){const{data:i=[],isLoading:o}=go(),[c,m]=d(""),h=l(null),p=l(0),{t:f}=Kn(),g=i.filter(e=>!n.includes(e.userId||"")).filter(e=>{const t=c.toLowerCase(),a=e.userName?.toLowerCase().includes(t);return a}).sort((e,t)=>{const r=a.includes(e.userId),n=a.includes(t.userId);if(r&&!n)return-1;if(!r&&n)return 1;const s=e.userName||e.userEmail||"",i=t.userName||t.userEmail||"";return s.localeCompare(i)});return u(()=>{h.current&&p.current>0&&(h.current.scrollTop=p.current)},[g]),t("div",o?{className:"flex items-center justify-center p-4",children:[e(A,{className:"h-6 w-6 animate-spin"}),e("span",{className:"ml-2",children:f("loading_data")})]}:{className:"space-y-2",children:[e(pr,{placeholder:f("search_user"),value:c,onChange:e=>m(e.target.value)}),e("div",{ref:h,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===g.length?e("p",{className:"text-sm text-muted-foreground",children:f("search_user")}):e("div",{className:"space-y-2",children:g.map(n=>t("div",{className:"flex items-center space-x-2",children:[e(an,{id:n.userId,checked:a.includes(n.userId),onCheckedChange:()=>{return e=n.userId,h.current&&(p.current=h.current.scrollTop),void(a.includes(e)?r(a.filter(t=>t!==e)):r([...a,e]));var e}}),e(gr,{htmlFor:n.userId,className:"flex-1 cursor-pointer",children:n.userName||n.userEmail})]},n.userId))})}),a.length>0&&e("p",{className:"text-sm text-muted-foreground",children:f("selected_count",{count:a.length})}),s&&e("p",{className:"text-sm text-destructive",children:s})]})}function fy({leader:r,prefilledLeaderId:n,onSuccess:s}){const{t:i}=Kn(),{alias:o}=ei(),l=!!r,c=r?.id.startsWith("virtual-"),m=ny(),h=ry(),p=sy(),f=oy(),g=iy(),{data:v=[]}=ty(),{data:b=[]}=go(),[y,w]=d(""),x=ey(v).map(e=>e.id_user),N=l?ey(v).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user):[],k=kt({resolver:uy(l?hy:my),defaultValues:{id_leader:n||(l?r?.id_leader:null)||null,id_users:l?N:[]}});u(()=>{if(r){const e=ey(v).filter(e=>e.id_leader===r.id_user).map(e=>e.id_user);k.reset({id_leader:r.id_leader||null,id_users:e})}else n?k.reset({id_leader:n,id_users:[]}):k.reset({id_leader:null,id_users:[]})},[o,r?.id,r?.id_user,r?.id_leader,n,v]);const C=m.isPending||h.isPending||p.isPending||f.isPending||g.isPending,S=k.watch("id_leader"),E=k.watch("id_users"),_=l?[r.id_user,...x.filter(e=>e!==r.id_user&&!E.includes(e)&&!N.includes(e))]:[S,...x.filter(e=>!E.includes(e))].filter(Boolean);return t("form",{onSubmit:k.handleSubmit(async e=>{try{if(l)if(c){await h.mutateAsync({id_user:r.id_user,id_leader:e.id_leader});const t=b.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await f.mutateAsync({leaderUserId:r.id_user,selectedUsers:t})}else{await p.mutateAsync({id:r.id,id_leader:e.id_leader});const t=b.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await f.mutateAsync({leaderUserId:r.id_user,selectedUsers:t})}else{const t=b.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({id_leader:e.id_leader,users:t})}s?.()}catch(t){}}),className:"space-y-4",children:[l&&t("div",{children:[e(gr,{children:i("leader")}),e(pr,{value:b.find(e=>e.userId===r.id_user)?.userName||r.name||r.id_user,disabled:!0,className:"bg-muted"})]}),t("div",{children:[e(gr,{children:i("superior")}),t(qr,{value:S||"none",onValueChange:e=>k.setValue("id_leader","none"===e?null:e),children:[e(Xr,{children:e(Gr,{placeholder:i("select_placeholder")})}),t(Yr,{children:[e("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e(pr,{placeholder:i("superior_search"),value:y,onChange:e=>w(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),t(uo,{className:"h-[200px]",children:[e(en,{value:"none",children:"[Nenhum]"}),b.filter(e=>{const t=l?e.userId!==r.id_user:!E.includes(e.userId),a=!y||e.userName?.toLowerCase().includes(y.toLowerCase());return t&&a}).sort((e,t)=>{const a=e.userName||e.userEmail||"",r=t.userName||t.userEmail||"";return a.localeCompare(r)}).map(t=>e(en,{value:t.userId,children:t.userName},t.userId))]})]})]},`superior-select-${o}`),k.formState.errors.id_leader&&e("p",{className:"text-sm text-destructive mt-1",children:k.formState.errors.id_leader.message})]}),t("div",{children:[t(gr,{children:[i("subordinates")," *"]}),e(py,{value:E,onChange:e=>k.setValue("id_users",e),excludeUserIds:_,error:k.formState.errors.id_users?.message},`users-multiselect-${o}`)]}),t("div",{className:"flex items-center justify-between gap-2",children:[e(mr,{type:"submit",disabled:C||!l&&0===E.length,children:C&&!g.isPending?t(a,{children:[e(A,{className:"mr-2 h-4 w-4 animate-spin"}),i(l?"updating":"saving")]}):l?E.length>0?i("update_success",{count:E.length}):i("update"):i("create_success",{count:E.length})}),l&&!S&&0===E.length&&e(mr,{type:"button",variant:"destructive",disabled:C,onClick:async()=>{if(r&&window.confirm(i("remove_confirm")))try{await g.mutateAsync(r.id),s?.()}catch(e){}},className:"ml-auto",children:g.isPending?t(a,{children:[e(A,{className:"mr-2 h-4 w-4 animate-spin"}),i("removing")]}):t(a,{children:[e(H,{className:"mr-2 h-4 w-4"}),i("remove")]})})]})]})}function gy({open:a,onOpenChange:r,leader:n,prefilledLeaderId:s,title:i}){return e(Cr,{open:a,onOpenChange:r,children:t(Tr,{className:"sm:max-w-[500px]",children:[e(Ar,{children:e(Or,{children:i})}),e(fy,{leader:n,prefilledLeaderId:s,onSuccess:()=>r(!1)})]})})}const vy="leadership-expanded-nodes",by=(e,t)=>{try{localStorage.setItem(`${vy}-${e}`,JSON.stringify(Array.from(t)))}catch(a){}};function yy(){const{alias:a}=ei(),{t:r}=Kn(),{data:n,isLoading:s,error:i,refetch:o}=ty(),{data:l=[]}=go({enabled:!0}),[c,m]=d(()=>a?(e=>{try{const t=localStorage.getItem(`${vy}-${e}`);if(t)return new Set(JSON.parse(t))}catch(i){}return new Set})(a):new Set),[h,p]=d(!1),[f,g]=d(),[v,b]=d(null),y=l.filter(e=>e.userName&&"Nome não disponível"!==e.userName),w=new Set(y.map(e=>e.userId)),x=y.length-(n?ey(n).filter(e=>w.has(e.id_user)&&"[Não encontrado]"!==e.name).length:0);u(()=>{if(n&&n.length>0&&a){if(!localStorage.getItem(`${vy}-${a}`)){const e=n.map(e=>e.id),t=new Set(e);m(t),by(a,t)}}},[n,a]);const N=e=>{m(t=>{const r=new Set(t);return r.has(e)?r.delete(e):r.add(e),a&&by(a,r),r})},k=e=>{g(e),b(null),p(!0)};return s?e("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center",children:[e(We,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e("p",{className:"text-muted-foreground",children:r("loading")})]})}):i?e("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center",children:[e("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e(mr,{onClick:()=>o(),children:"Tentar novamente"})]})}):t("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex items-center justify-between p-4 border-b",children:t("div",{className:"flex gap-2 items-center",children:[t(mr,{size:"sm",onClick:()=>{g(void 0),b(null),p(!0)},children:[e(q,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),t(mr,{variant:"outline",size:"sm",onClick:()=>{if(!n)return;const e=ey(n).filter(e=>e.children.length>0).map(e=>e.id),t=new Set(e);m(t),a&&by(a,t)},disabled:!n||0===n.length,children:[e(P,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),t(mr,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;m(e),a&&by(a,e)},disabled:!n||0===n.length,children:[e($,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e("div",{className:"flex items-center gap-2 ml-4",children:t("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e(ht,{className:"h-4 w-4 text-muted-foreground"}),t("span",{className:"text-sm font-medium",children:[x," usuário",1!==x?"s":""," não associado",1!==x?"s":""]})]})})]})}),n&&0!==n.length?e(uo,{className:"flex-1",children:e("div",{children:t("table",{className:"w-full",children:[e("thead",{children:t("tr",{className:"border-b bg-muted/50",children:[e("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e("tbody",{children:n.map(t=>e(cy,{leader:t,expandedIds:c,onToggleExpand:N,onEdit:k},t.id))})]})})}):e("div",{className:"flex items-center justify-center flex-1",children:t("div",{className:"text-center space-y-4",children:[e("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e(gy,{open:h,onOpenChange:()=>{p(!1),g(void 0),b(null)},leader:f,prefilledLeaderId:v,title:f?r("edit")+" "+r("name"):v?r("add")+" Liderado":r("add")+" Líder Raiz"},`leadership-dialog-${a}`)]})}function wy(e){const[t,a]=d(!1),[r,n]=d(0),{t:s}=Kn(),{uploadFunction:i,deleteFunction:o,defaultOptions:l,onSuccess:c,onError:u}=e||{};return{upload:async(e,t)=>{if(!i){const e=new Error("uploadFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}a(!0),n(0);try{const a={...l,...t};if(a.maxSize&&e.size>a.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(a.maxSize/1024/1024)}MB`);if(a.allowedTypes){if(!a.allowedTypes.some(t=>t.endsWith("/*")?e.type.startsWith(t.replace("/*","")):e.type===t))throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${a.allowedTypes.join(", ")}`)}const r=await i(e,a);return n(100),C.success("Sucesso",{description:s("file_upload_success")}),c?.(r),r}catch(r){const e=r instanceof Error?r:new Error("Erro ao fazer upload");throw C.error("Erro",{description:e.message}),u?.(e),e}finally{a(!1)}},deleteMedia:async(e,t)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await o(e,t),C.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(a){throw C.error("Erro",{description:"Erro ao remover o arquivo"}),a}},uploading:t,progress:r}}function xy(e){const t=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const a of t){const t=e.match(a);if(t)return t[1]}return null}function Ny(e,t){const a=xy(e);if(!a)return e;return`https://www.youtube.com/embed/${a}${t?"?autoplay=1&mute=1":""}`}function ky(e){const t=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function Cy(e,t){const a=ky(e);if(!a)return e;return`https://player.vimeo.com/video/${a}${t?"?autoplay=1&muted=1":""}`}function Sy(e){if(!e)return;const t=e.match(/src="([^"]+)"/);return t?t[1]:void 0}function Ey(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function _y(e,t,a){switch(t||Ey(e)){case"youtube":return Ny(e,a);case"vimeo":return Cy(e,a);default:return e}}function Py({value:r,onChange:n,onSubmit:s,onCancel:i,uploadFunction:c,deleteFunction:u,uploadOptions:m}){const{t:h}=Kn(),[p,f]=d(r||{inputType:"url",controls:!0}),g=l(null),v=l(null),{upload:b,uploading:y}=wy({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["video/*"],maxSize:104857600}}),{upload:w,uploading:x}=wy({uploadFunction:c,deleteFunction:u,defaultOptions:{...m,allowedTypes:["image/*"],maxSize:5242880}}),N=o(()=>Ey(p.videoUrl||Sy(p.embedCode)||""),[p.videoUrl,p.embedCode]),k=(e,t)=>{const a={...p,[e]:t};f(a),n(a)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[e(gr,{children:h("input_type")}),t(qr,{value:p.inputType||"url",onValueChange:e=>k("inputType",e),children:[e(Xr,{children:e(Gr,{})}),t(Yr,{children:[e(en,{value:"url",children:h("url")}),e(en,{value:"upload",children:h("input_type_upload")}),e(en,{value:"embed",children:h("input_type_embed")})]})]})]}),"upload"===p.inputType&&c&&t("div",{className:"space-y-2",children:[e(gr,{children:h("file")}),t("div",{className:"flex gap-2",children:[e("input",{ref:g,type:"file",accept:"video/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await b(t),a={...p,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:p.title||t.name.replace(/\.[^/.]+$/,"")};f(a),n(a)}catch(a){}finally{g.current&&(g.current.value="")}},className:"hidden"}),e(mr,{type:"button",variant:"outline",onClick:()=>g.current?.click(),disabled:y,children:t(a,y?{children:[e(A,{className:"mr-2 h-4 w-4 animate-spin"}),h("uploading")]}:{children:[e(fe,{className:"mr-2 h-4 w-4"}),h("select_video")]})}),p.videoFile&&e("span",{className:"text-xs text-muted-foreground truncate self-center",children:h("video.fileInfo",{name:p.videoFile,size:Math.round((p.videoSize||0)/1024/1024)})})]})]}),"embed"===p.inputType&&t("div",{className:"space-y-2",children:[e(gr,{children:h("embed")}),e(rn,{placeholder:h("embed"),value:p.embedCode||"",onChange:e=>k("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&t("div",{className:"space-y-2",children:[e(gr,{children:h("thumbnail")}),t("div",{className:"flex gap-2",children:[e(pr,{type:"url",placeholder:h("thumbnail"),value:p.thumbnail||"",onChange:e=>k("thumbnail",e.target.value),className:"flex-1"}),e("input",{ref:v,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await w(t),a={...p,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};f(a),n(a)}catch(a){}finally{v.current&&(v.current.value="")}},className:"hidden"}),e(mr,{type:"button",variant:"outline",onClick:()=>v.current?.click(),disabled:x,children:t(a,x?{children:[e(A,{className:"mr-2 h-4 w-4 animate-spin"}),h("video.uploading")]}:{children:[e(fe,{className:"mr-2 h-4 w-4"}),h("upload")]})})]}),p.thumbnailFile&&e("p",{className:"text-xs text-muted-foreground",children:h("video.thumbnailFileInfo",{name:p.thumbnailFile})})]}),t("div",{className:"space-y-2",children:[e(gr,{htmlFor:"title",children:h("title")}),e(pr,{id:"title",placeholder:h("title"),value:p.title||"",onChange:e=>k("title",e.target.value)})]}),t("div",{className:"flex gap-6",children:[t("div",{className:"flex items-center gap-2",children:[e("input",{id:"autoplay",type:"checkbox",checked:p.autoplay||!1,onChange:e=>k("autoplay",e.target.checked),className:"h-4 w-4"}),e(gr,{htmlFor:"autoplay",className:"cursor-pointer",children:h("video.autoplay")})]}),t("div",{className:"flex items-center gap-2",children:[e("input",{id:"controls",type:"checkbox",checked:!1!==p.controls,onChange:e=>k("controls",e.target.checked),className:"h-4 w-4"}),e(gr,{htmlFor:"controls",className:"cursor-pointer",children:h("video.controls")})]})]}),t("div",{className:"space-y-2",children:[e(gr,{children:h("preview")}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const a=p.videoUrl||Sy(p.embedCode)||"";if(!a)return e("div",{className:"text-center py-8 text-muted-foreground",children:h("no_content_preview")});if("file"===N)return t("video",{controls:!1!==p.controls,autoPlay:p.autoplay,poster:p.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e("source",{src:a}),h("unsupported")]});const r="youtube"===N?Ny(a,p.autoplay):Cy(a,p.autoplay);return e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:p.title||h("video"),src:r,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(mr,{variant:"outline",onClick:i,children:h("cancel")}),e(mr,{onClick:()=>{p.videoUrl||p.embedCode?s(p):C.error(h("error"),{description:h("error_no_video")})},disabled:!(p.videoUrl||p.embedCode),children:h("save")})]})]})}function Ry({content:a,className:r="",style:n}){const s=a.videoUrl||Sy(a.embedCode)||"";if(!s)return null;const i=Ey(s),{t:o}=Kn();return e(vr,{className:`overflow-hidden my-4 ${r}`,style:n,children:t(xr,{className:"p-0",children:["file"===i?t("video",{controls:!1!==a.controls,autoPlay:a.autoplay,poster:a.thumbnail,className:"w-full h-auto",playsInline:!0,muted:a.autoplay,children:[e("source",{src:s}),"Seu navegador não suporta vídeos HTML5."]}):e("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e("iframe",{title:a.title||o("video"),src:"youtube"===i?Ny(s,a.autoplay):Cy(s,a.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),a.title&&e("div",{className:"p-4",children:e("p",{className:"text-sm font-medium",children:a.title})})]})})}function Ty({value:r,onChange:n,onSubmit:s,onCancel:i,uploadFunction:o,deleteFunction:c,uploadOptions:u}){const{t:m}=Kn(),[h,p]=d(r||{alignment:"center",allowDownload:!1}),f=l(null),{upload:g,uploading:v}=wy({uploadFunction:o,deleteFunction:c,defaultOptions:{...u,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,t)=>{const a={...h,[e]:t};p(a),n(a)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[e(gr,{children:m("url")}),t("div",{className:"flex gap-2",children:[e(pr,{type:"url",placeholder:m("url_placeholder"),value:h.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),o&&t(a,{children:[e("input",{ref:f,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await g(t),a={...h,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};p(a),n(a)}catch(a){}finally{f.current&&(f.current.value="")}},className:"hidden"}),e(mr,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:t(a,v?{children:[e(A,{className:"mr-2 h-4 w-4 animate-spin"}),m("uploading")]}:{children:[e(fe,{className:"mr-2 h-4 w-4"}),m("upload")]})})]})]}),h.imageFile&&e("p",{className:"text-xs text-muted-foreground",children:m("image.fileInfo",{name:h.imageFile,size:Math.round((h.imageSize||0)/1024)})})]}),h.imageUrl&&t("div",{className:"space-y-2",children:[e(gr,{children:m("preview")}),e("div",{className:"border rounded-lg p-4 bg-muted/30",children:e("div",{className:"flex "+("left"===h.alignment?"justify-start":"right"===h.alignment?"justify-end":"justify-center"),children:e("img",{src:h.imageUrl,alt:h.alt||"Preview",style:{width:h.width?`${h.width}px`:"auto",height:h.height?`${h.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),t("div",{className:"space-y-2",children:[e(gr,{htmlFor:"caption",children:m("caption")}),e(rn,{id:"caption",placeholder:m("caption"),value:h.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),t("div",{className:"space-y-2",children:[e(gr,{htmlFor:"alt",children:m("alt")}),e(pr,{id:"alt",placeholder:m("alt"),value:h.alt||"",onChange:e=>b("alt",e.target.value)})]}),t("div",{className:"space-y-2",children:[e(gr,{children:m("alignment")}),t(qr,{value:h.alignment||"center",onValueChange:e=>b("alignment",e),children:[e(Xr,{children:e(Gr,{})}),t(Yr,{children:[e(en,{value:"left",children:m("left")}),e(en,{value:"center",children:m("center")}),e(en,{value:"right",children:m("right")})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[e(gr,{htmlFor:"width",children:m("width")}),e(pr,{id:"width",type:"number",placeholder:"px",value:h.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),t("div",{className:"space-y-2",children:[e(gr,{htmlFor:"height",children:m("height")}),e(pr,{id:"height",type:"number",placeholder:"px",value:h.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),t("div",{className:"flex items-center gap-2",children:[e("input",{id:"allowDownload",type:"checkbox",checked:h.allowDownload||!1,onChange:e=>b("allowDownload",e.target.checked),className:"h-4 w-4"}),e(gr,{htmlFor:"allowDownload",className:"cursor-pointer",children:m("allow_download")})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e(mr,{variant:"outline",onClick:i,children:m("cancel")}),e(mr,{onClick:()=>{h.imageUrl?s(h):C.error(m("error"),{description:m("error_no_image")})},disabled:!h.imageUrl,children:m("save")})]})]})}function Ay({content:a,className:r="",style:n}){if(!a.imageUrl)return null;const s={left:"justify-start",center:"justify-center",right:"justify-end"}[a.alignment||"center"];return e("div",{className:`flex ${s} my-4 ${r}`,style:n,children:t("div",{className:"space-y-2 max-w-full",children:[e("img",{src:a.imageUrl,alt:a.alt||"",style:{width:a.width?`${a.width}px`:"auto",height:a.height?`${a.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),a.caption&&e("p",{className:"text-sm text-muted-foreground text-center italic",children:a.caption}),a.allowDownload&&a.imageUrl&&t("a",{href:a.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e(ge,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function Iy(e,t){return e/t}function My(e,t,a,r){const n=Iy(e,t);return a&&!r?{width:a,height:Math.round(a/n)}:r&&!a?{width:Math.round(r*n),height:r}:{width:e,height:t}}function Oy(e){const t=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>t.includes(e))}function Ly(e){try{const t=new URL(e),a=t.pathname.split("/");return a[a.length-1]||"image"}catch{const t=e.split("/");return t[t.length-1]||"image"}}function Dy(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}export{Ps as AUTH_CONFIG,bl as Accordion,xl as AccordionContent,yl as AccordionItem,wl as AccordionTrigger,hr as ActionButton,ob as ActionMenu,eo as ActionMenuItems,Uo as Alert,Wo as AlertDescription,Nl as AlertDialog,Al as AlertDialogAction,Il as AlertDialogCancel,El as AlertDialogContent,Tl as AlertDialogDescription,Pl as AlertDialogFooter,_l as AlertDialogHeader,Sl as AlertDialogOverlay,Cl as AlertDialogPortal,Rl as AlertDialogTitle,kl as AlertDialogTrigger,Vo as AlertTitle,Nb as AppHeader,$b as AppLayout,zb as AppSidebar,Ns as AuthErrorInterceptor,Zs as AuthProvider,Qs as AuthService,Ml as Avatar,Ll as AvatarFallback,Ol as AvatarImage,sn as Badge,bo as BaseForm,qc as Blockquote,Dl as Breadcrumb,Vl as BreadcrumbEllipsis,jl as BreadcrumbItem,zl as BreadcrumbLink,Fl as BreadcrumbList,$l as BreadcrumbPage,Ul as BreadcrumbSeparator,xo as BulkActionBar,mr as Button,Bl as ButtonGroup,Rs as CRUD_CONFIG,hc as Calendar,Bo as CallbackPage,vr as Card,xr as CardContent,wr as CardDescription,Nr as CardFooter,br as CardHeader,mi as CardSkeleton,yr as CardTitle,cb as Cards,Gv as ChartContainer,Yv as ChartLegend,Zv as ChartLegendContent,Xv as ChartStyle,Jv as ChartTooltip,Qv as ChartTooltipContent,an as Checkbox,ul as Collapsible,hl as CollapsibleContent,ml as CollapsibleTrigger,co as ColorPicker,Qn as Combobox,pn as Command,fn as CommandDialog,bn as CommandEmpty,yn as CommandGroup,gn as CommandInput,xn as CommandItem,vn as CommandList,wn as CommandSeparator,Nn as CommandShortcut,zi as ContextMenu,Xi as ContextMenuCheckboxItem,Ki as ContextMenuContent,Ui as ContextMenuGroup,Gi as ContextMenuItem,Qi as ContextMenuLabel,Vi as ContextMenuPortal,Bi as ContextMenuRadioGroup,Ji as ContextMenuRadioItem,Yi as ContextMenuSeparator,Zi as ContextMenuShortcut,Wi as ContextMenuSub,qi as ContextMenuSubContent,Hi as ContextMenuSubTrigger,$i as ContextMenuTrigger,vl as CoreProviders,sb as CrudCards,_o as CrudPageInternal,wo as CrudPagination,lb as CrudPrimitiveFilterBar,yo as CrudPrimitivePagination,ib as CrudPrimitiveTable,io as CrudTable,pc as DataList,fc as DatePicker,Cr as Dialog,Ir as DialogBody,_r as DialogClose,Tr as DialogContent,Lr as DialogDescription,Mr as DialogFooter,Ar as DialogHeader,Pr as DialogOverlay,Er as DialogPortal,Or as DialogTitle,Sr as DialogTrigger,gc as Drawer,yc as DrawerClose,xc as DrawerContent,Sc as DrawerDescription,kc as DrawerFooter,Nc as DrawerHeader,wc as DrawerOverlay,bc as DrawerPortal,Cc as DrawerTitle,vc as DrawerTrigger,Ci as DropdownMenu,Oi as DropdownMenuCheckboxItem,Ii as DropdownMenuContent,Ei as DropdownMenuGroup,Mi as DropdownMenuItem,Di as DropdownMenuLabel,_i as DropdownMenuPortal,Ri as DropdownMenuRadioGroup,Li as DropdownMenuRadioItem,Fi as DropdownMenuSeparator,ji as DropdownMenuShortcut,Pi as DropdownMenuSub,Ai as DropdownMenuSubContent,Ti as DropdownMenuSubTrigger,Si as DropdownMenuTrigger,Bb as EmailService,vi as EmptyState,Qn as EntitySelect,gl as ErrorBoundary,Eo as FilterBar,Dr as Form,Wr as FormControl,Br as FormDescription,jr as FormField,Ur as FormItem,Vr as FormLabel,Hr as FormMessage,hi as FormSkeleton,Pc as Grid,Dc as H1,Fc as H2,jc as H3,zc as H4,pi as HeaderSkeleton,Gn as I18nextProvider,po as IconPicker,Ty as ImageEditor,Ay as ImageRenderer,Hc as InlineCode,pr as Input,Rc as InputGroup,Ac as InputGroupAddon,Mc as InputGroupButton,Oc as InputGroupInput,Lc as InputGroupTextarea,Ls as LOGO_CONFIG,gr as Label,Vc as Large,Uc as Lead,cy as LeaderRow,gy as LeadershipDialog,fy as LeadershipForm,yy as LeadershipPage,Kc as List,cn as LoadingState,ll as LocaleProvider,fb as LocaleSelector,Ho as LoginPage,Ds as MESSAGES,qb as ManageAccessModal,Ov as Menubar,$v as MenubarCheckboxItem,jv as MenubarContent,Tv as MenubarGroup,zv as MenubarItem,Vv as MenubarLabel,Rv as MenubarMenu,Av as MenubarPortal,Mv as MenubarRadioGroup,Uv as MenubarRadioItem,Wv as MenubarSeparator,Bv as MenubarShortcut,Iv as MenubarSub,Fv as MenubarSubContent,Dv as MenubarSubTrigger,Lv as MenubarTrigger,Db as ModalStateProvider,Qn as MultiSelect,Bc as Muted,bb as NavigationProvider,$c as P,Gc as PageBreadcrumb,Ko as PageMetadataProvider,Jc as Pagination,Qc as PaginationContent,ad as PaginationEllipsis,Yc as PaginationItem,Zc as PaginationLink,td as PaginationNext,ed as PaginationPrevious,Kb as PlaceCard,Gb as PlacesList,un as Popover,hn as PopoverContent,mn as PopoverTrigger,Mo as Progress,zo as ProtectedRoute,Ms as QUALIEX_CONFIG,Is as QUERY_KEYS,Vs as QualiexEnrichmentService,Cs as QualiexErrorInterceptor,vo as QualiexUserField,rd as RadioGroup,nd as RadioGroupItem,rb as RichTextEditor,Ts as SEARCH_CONFIG,uo as ScrollArea,mo as ScrollBar,qr as Select,Yr as SelectContent,Kr as SelectGroup,en as SelectItem,Zr as SelectLabel,Qr as SelectScrollDownButton,Jr as SelectScrollUpButton,Qn as SelectSearch,tn as SelectSeparator,Xr as SelectTrigger,Gr as SelectValue,kr as Separator,sd as Sheet,hd as SheetBody,od as SheetClose,ud as SheetContent,gd as SheetDescription,pd as SheetFooter,md as SheetHeader,cd as SheetOverlay,ld as SheetPortal,fd as SheetTitle,id as SheetTrigger,xd as Sidebar,Mb as SidebarActionTrigger,Rd as SidebarContent,_d as SidebarFooter,Td as SidebarGroup,Id as SidebarGroupAction,Md as SidebarGroupContent,Ad as SidebarGroupLabel,Ib as SidebarHeader,Sd as SidebarInput,Cd as SidebarInset,Od as SidebarMenu,jd as SidebarMenuAction,zd as SidebarMenuBadge,Fd as SidebarMenuButton,Ld as SidebarMenuItem,$d as SidebarMenuSkeleton,Ud as SidebarMenuSub,Wd as SidebarMenuSubButton,Vd as SidebarMenuSubItem,wd as SidebarProvider,kd as SidebarRail,Pd as SidebarSeparator,fi as SidebarSkeleton,Nd as SidebarTrigger,kn as Skeleton,Bd as Slider,Wc as Small,dn as SonnerToaster,ln as Spinner,nb as SplitButton,So as Stack,fo as Switch,Qd as TabPageContent,Jd as TabPageHeader,Xd as TabPageLayout,ri as Table,si as TableBody,di as TableCaption,ci as TableCell,ii as TableFooter,li as TableHead,ni as TableHeader,ki as TableResizeHandle,oi as TableRow,to as TableRowActions,ui as TableSkeleton,Hd as Tabs,Gd as TabsContent,qd as TabsList,Kd as TabsTrigger,rn as Textarea,dn as Toaster,Zd as Toggle,tu as ToggleGroup,au as ToggleGroupItem,os as TokenManager,Zn as TokenService,yi as Tooltip,xi as TooltipContent,bi as TooltipProvider,wi as TooltipTrigger,dl as TranslationLoader,Ni as TruncatedCell,Py as VideoEditor,Ry as VideoRenderer,Lo as WizardBreadcrumb,Fo as WizardButtons,jo as WizardForm,Do as WizardProgressBar,Oo as WizardStepper,Rb as assets,nn as badgeVariants,Zb as buildHierarchy,Wl as buttonGroupVariants,ur as buttonVariants,Iy as calculateAspectRatio,sr as cn,Po as createCrudPage,ub as createCrudRoutingConfig,db as createRoutingHandlers,Hs as createService,Ro as createSimpleSaveHandler,ai as createSimpleService,cr as debounce,js as deriveEmailField,Fs as deriveNameField,zs as deriveUsernameField,Ey as detectVideoProvider,Hb as emailService,ds as errorService,Ly as extractImageFileName,ky as extractVimeoId,xy as extractYouTubeId,Yb as filterAndPromoteOrphans,ey as flattenTree,lr as formatCurrency,Vb as formatDate,or as formatDatetime,Dy as formatFileSize,To as generateCrudConfig,Os as getQualiexConfig,vs as getSupabaseClient,nr as handleExternalLink,rr as i18n,Tc as inputGroupAddonVariants,Ic as inputGroupButtonVariants,As as isDevEnvironment,Oy as isImageUrl,Tb as logoSrc,_y as normalizeVideoUrl,Cy as normalizeVimeoUrl,Ny as normalizeYouTubeUrl,Sy as parseIframeSrc,Qb as placeService,_s as qualiexApi,My as resizeKeepingAspect,$s as resolveFieldMappings,Jo as setupQualiexCore,dr as slugify,Ab as smallLogoSrc,Yd as toggleVariants,al as translationService,ir as trimTextFields,Cb as useActiveModules,ei as useAuth,oo as useBaseForm,ro as useColumnResize,ay as useCreateLeaderMutation,ny as useCreateMultipleLeadersMutation,ry as useCreateSingleLeaderMutation,ti as useCrud,xb as useDebounce,zr as useFormField,jb as useHasOpenModal,Wb as useI18nFormatters,ty as useLeadershipApi,cl as useLocale,wy as useMediaUpload,Fb as useModalState,yb as useNavigation,Xo as usePageMetadata,Go as usePageMetadataContext,wb as usePageTitle,kb as usePermissionQuery,go as useQualiexUsers,iy as useRemoveLeaderMutation,Xc as useRouteBreadcrumbs,no as useRowResize,yd as useSidebar,Ob as useSidebarResize,oy as useSyncSubordinatesMutation,Kn as useTranslation,sy as useUpdateLeaderMutation};