forlogic-core 1.10.0 → 1.10.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.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("@radix-ui/react-slot"),s=require("class-variance-authority"),r=require("clsx"),n=require("tailwind-merge"),i=require("date-fns"),o=require("sonner"),l=require("lucide-react"),c=require("@radix-ui/react-label"),d=require("@radix-ui/react-dialog"),u=require("react-hook-form"),m=require("@radix-ui/react-select"),p=require("@radix-ui/react-checkbox"),h=require("@radix-ui/react-toast"),f=require("@radix-ui/react-popover"),g=require("@supabase/supabase-js"),x=require("@tanstack/react-query"),b=require("react-router-dom"),v=require("@radix-ui/react-alert-dialog"),y=require("@radix-ui/react-dropdown-menu"),N=require("@radix-ui/react-scroll-area"),j=require("@radix-ui/react-progress"),w=require("@radix-ui/react-accordion"),k=require("@radix-ui/react-aspect-ratio"),S=require("@radix-ui/react-avatar"),C=require("react-day-picker"),P=require("@radix-ui/react-collapsible"),E=require("@radix-ui/react-radio-group"),T=require("@radix-ui/react-separator"),A=require("@radix-ui/react-tooltip"),_=require("@radix-ui/react-slider"),I=require("next-themes"),R=require("@radix-ui/react-switch"),L=require("@radix-ui/react-tabs"),O=require("@radix-ui/react-toggle"),F=require("@radix-ui/react-toggle-group"),D=require("react-markdown"),M=require("remark-gfm"),z=require("zod"),$=require("@hookform/resolvers");function U(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,Object.freeze(t)}var V=U(t),q=U(c),B=U(d),W=U(m),H=U(p),K=U(h),Q=U(f),G=U(v),X=U(y),J=U(N),Y=U(j),Z=U(w),ee=U(k),te=U(S),ae=U(P),se=U(E),re=U(T),ne=U(A),ie=U(_),oe=U(R),le=U(L),ce=U(O),de=U(F);const ue=e=>"string"==typeof e,me=()=>{let e,t;const a=new Promise((a,s)=>{e=a,t=s});return a.resolve=e,a.reject=t,a},pe=e=>null==e?"":""+e,he=/###/g,fe=e=>e&&e.indexOf("###")>-1?e.replace(he,"."):e,ge=e=>!e||ue(e),xe=(e,t,a)=>{const s=ue(t)?t.split("."):t;let r=0;for(;r<s.length-1;){if(ge(e))return{};const t=fe(s[r]);!e[t]&&a&&(e[t]=new a),e=Object.prototype.hasOwnProperty.call(e,t)?e[t]:{},++r}return ge(e)?{}:{obj:e,k:fe(s[r])}},be=(e,t,a)=>{const{obj:s,k:r}=xe(e,t,Object);if(void 0!==s||1===t.length)return void(s[r]=a);let n=t[t.length-1],i=t.slice(0,t.length-1),o=xe(e,i,Object);for(;void 0===o.obj&&i.length;)n=`${i[i.length-1]}.${n}`,i=i.slice(0,i.length-1),o=xe(e,i,Object),o?.obj&&void 0!==o.obj[`${o.k}.${n}`]&&(o.obj=void 0);o.obj[`${o.k}.${n}`]=a},ve=(e,t)=>{const{obj:a,k:s}=xe(e,t);if(a&&Object.prototype.hasOwnProperty.call(a,s))return a[s]},ye=(e,t,a)=>{for(const s in t)"__proto__"!==s&&"constructor"!==s&&(s in e?ue(e[s])||e[s]instanceof String||ue(t[s])||t[s]instanceof String?a&&(e[s]=t[s]):ye(e[s],t[s],a):e[s]=t[s]);return e},Ne=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var je={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const we=e=>ue(e)?e.replace(/[&<>"'\/]/g,e=>je[e]):e;const ke=[" ",",","?","!",";"],Se=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),Ce=(e,t,a=".")=>{if(!e)return;if(e[t]){if(!Object.prototype.hasOwnProperty.call(e,t))return;return e[t]}const s=t.split(a);let r=e;for(let n=0;n<s.length;){if(!r||"object"!=typeof r)return;let e,t="";for(let i=n;i<s.length;++i)if(i!==n&&(t+=a),t+=s[i],e=r[t],void 0!==e){if(["string","number","boolean"].indexOf(typeof e)>-1&&i<s.length-1)continue;n+=i-n+1;break}r=e}return r},Pe=e=>e?.replace("_","-"),Ee={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){}};class Te{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||Ee,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,s){return s&&!this.debug?null:(ue(e[0])&&(e[0]=`${a}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new Te(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return(e=e||this.options).prefix=e.prefix||this.prefix,new Te(this.logger,e)}}var Ae=new Te;class _e{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 s=0;s<a;s++)e(...t)})}if(this.observers["*"]){Array.from(this.observers["*"].entries()).forEach(([a,s])=>{for(let r=0;r<s;r++)a.apply(a,[e,...t])})}}}class Ie extends _e{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,s={}){const r=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator,n=void 0!==s.ignoreJSONStructure?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let i;e.indexOf(".")>-1?i=e.split("."):(i=[e,t],a&&(Array.isArray(a)?i.push(...a):ue(a)&&r?i.push(...a.split(r)):i.push(a)));const o=ve(this.data,i);return!o&&!t&&!a&&e.indexOf(".")>-1&&(e=i[0],t=i[1],a=i.slice(2).join(".")),!o&&n&&ue(a)?Ce(this.data?.[e]?.[t],a,r):o}addResource(e,t,a,s,r={silent:!1}){const n=void 0!==r.keySeparator?r.keySeparator:this.options.keySeparator;let i=[e,t];a&&(i=i.concat(n?a.split(n):a)),e.indexOf(".")>-1&&(i=e.split("."),s=t,t=i[1]),this.addNamespaces(t),be(this.data,i,s),r.silent||this.emit("added",e,t,a,s)}addResources(e,t,a,s={silent:!1}){for(const r in a)(ue(a[r])||Array.isArray(a[r]))&&this.addResource(e,t,r,a[r],{silent:!0});s.silent||this.emit("added",e,t,a)}addResourceBundle(e,t,a,s,r,n={silent:!1,skipCopy:!1}){let i=[e,t];e.indexOf(".")>-1&&(i=e.split("."),s=a,a=t,t=i[1]),this.addNamespaces(t);let o=ve(this.data,i)||{};n.skipCopy||(a=JSON.parse(JSON.stringify(a))),s?ye(o,a,r):o={...o,...a},be(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 Re={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,a,s,r){return e.forEach(e=>{t=this.processors[e]?.process(t,a,s,r)??t}),t}};const Le=Symbol("i18next/PATH_KEY");function Oe(e,t){const{[Le]:a}=e(function(){const e=[],t=Object.create(null);let a;return t.get=(s,r)=>(a?.revoke?.(),r===Le?e:(e.push(r),a=Proxy.revocable(s,t),a.proxy)),Proxy.revocable(Object.create(null),t).proxy}());return a.join(t?.keySeparator??".")}const Fe={},De=e=>!ue(e)&&"boolean"!=typeof e&&"number"!=typeof e;class Me extends _e{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=Ae.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const a={...t};if(null==e)return!1;const s=this.resolve(e,a);if(void 0===s?.res)return!1;const r=De(s.res);return!1!==a.returnObjects||!r}extractFromKey(e,t){let a=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===a&&(a=":");const s=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator;let r=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 s=ke.filter(e=>t.indexOf(e)<0&&a.indexOf(e)<0);if(0===s.length)return!0;const r=Se.getRegExp(`(${s.map(e=>"?"===e?"\\?":e).join("|")})`);let n=!r.test(e);if(!n){const t=e.indexOf(a);t>0&&!r.test(e.substring(0,t))&&(n=!0)}return n})(e,a,s));if(n&&!i){const t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:ue(r)?[r]:r};const n=e.split(a);(a!==s||a===s&&this.options.ns.indexOf(n[0])>-1)&&(r=n.shift()),e=n.join(s)}return{key:e,namespaces:ue(r)?[r]:r}}translate(e,t,a){let s="object"==typeof t?{...t}:t;if("object"!=typeof s&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof s&&(s={...s}),s||(s={}),null==e)return"";"function"==typeof e&&(e=Oe(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]);const r=void 0!==s.returnDetails?s.returnDetails:this.options.returnDetails,n=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator,{key:i,namespaces:o}=this.extractFromKey(e[e.length-1],s),l=o[o.length-1];let c=void 0!==s.nsSeparator?s.nsSeparator:this.options.nsSeparator;void 0===c&&(c=":");const d=s.lng||this.language,u=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if("cimode"===d?.toLowerCase())return u?r?{res:`${l}${c}${i}`,usedKey:i,exactUsedKey:i,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(s)}:`${l}${c}${i}`:r?{res:i,usedKey:i,exactUsedKey:i,usedLng:d,usedNS:l,usedParams:this.getUsedParamsDetails(s)}:i;const m=this.resolve(e,s);let p=m?.res;const h=m?.usedKey||i,f=m?.exactUsedKey||i,g=void 0!==s.joinArrays?s.joinArrays:this.options.joinArrays,x=!this.i18nFormat||this.i18nFormat.handleAsObject,b=void 0!==s.count&&!ue(s.count),v=Me.hasDefaultValue(s),y=b?this.pluralResolver.getSuffix(d,s.count,s):"",N=s.ordinal&&b?this.pluralResolver.getSuffix(d,s.count,{ordinal:!1}):"",j=b&&!s.ordinal&&0===s.count,w=j&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${y}`]||s[`defaultValue${N}`]||s.defaultValue;let k=p;x&&!p&&v&&(k=w);const S=De(k),C=Object.prototype.toString.apply(k);if(!(x&&k&&S&&["[object Number]","[object Function]","[object RegExp]"].indexOf(C)<0)||ue(g)&&Array.isArray(k))if(x&&ue(g)&&Array.isArray(p))p=p.join(g),p&&(p=this.extendTranslation(p,e,s,a));else{let t=!1,r=!1;!this.isValidLookup(p)&&v&&(t=!0,p=w),this.isValidLookup(p)||(r=!0,p=i);const o=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&r?void 0:p,u=v&&w!==p&&this.options.updateMissing;if(r||t||u){if(this.logger.log(u?"updateKey":"missingKey",d,l,i,u?w:p),n){const e=this.resolve(i,{...s,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,s.lng||this.language);if("fallback"===this.options.saveMissingTo&&t&&t[0])for(let s=0;s<t.length;s++)e.push(t[s]);else"all"===this.options.saveMissingTo?e=this.languageUtils.toResolveHierarchy(s.lng||this.language):e.push(s.lng||this.language);const a=(e,t,a)=>{const r=v&&a!==p?a:o;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,r,u,s):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,r,u,s),this.emit("missingKey",e,l,t,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&b?e.forEach(e=>{const t=this.pluralResolver.getSuffixes(e,s);j&&s[`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,s[`defaultValue${t}`]||w)})}):a(e,i,w))}p=this.extendTranslation(p,e,s,m,a),r&&p===i&&this.options.appendNamespaceToMissingKey&&(p=`${l}${c}${i}`),(r||t)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${c}${i}`:i,t?p:void 0,s))}else{if(!s.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(h,k,{...s,ns:o}):`key '${i} (${this.language})' returned an object instead of string.`;return r?(m.res=e,m.usedParams=this.getUsedParamsDetails(s),m):e}if(n){const e=Array.isArray(k),t=e?[]:{},a=e?f:h;for(const r in k)if(Object.prototype.hasOwnProperty.call(k,r)){const e=`${a}${n}${r}`;t[r]=v&&!p?this.translate(e,{...s,defaultValue:De(w)?w[r]:void 0,joinArrays:!1,ns:o}):this.translate(e,{...s,joinArrays:!1,ns:o}),t[r]===e&&(t[r]=k[r])}p=t}}return r?(m.res=p,m.usedParams=this.getUsedParamsDetails(s),m):p}extendTranslation(e,t,a,s,r){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...a},a.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init({...a,interpolation:{...this.options.interpolation,...a.interpolation}});const n=ue(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&&!ue(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||s.usedLng,a),n){const t=e.match(this.interpolator.nestingRegexp);i<(t&&t.length)&&(a.nest=!1)}!a.lng&&s&&s.res&&(a.lng=this.language||s.usedLng),!1!==a.nest&&(e=this.interpolator.nest(e,(...e)=>r?.[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=ue(n)?[n]:n;return null!=e&&i?.length&&!1!==a.applyPostProcessor&&(e=Re.handle(i,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(a)},...a}:a,this)),e}resolve(e,t={}){let a,s,r,n,i;return ue(e)&&(e=[e]),e.forEach(e=>{if(this.isValidLookup(a))return;const o=this.extractFromKey(e,t),l=o.key;s=l;let c=o.namespaces;this.options.fallbackNS&&(c=c.concat(this.options.fallbackNS));const d=void 0!==t.count&&!ue(t.count),u=d&&!t.ordinal&&0===t.count,m=void 0!==t.context&&(ue(t.context)||"number"==typeof t.context)&&""!==t.context,p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);c.forEach(e=>{this.isValidLookup(a)||(i=e,Fe[`${p[0]}-${e}`]||!this.utils?.hasLoadedNamespace||this.utils?.hasLoadedNamespace(i)||(Fe[`${p[0]}-${e}`]=!0,this.logger.warn(`key "${s}" for languages "${p.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!!!")),p.forEach(s=>{if(this.isValidLookup(a))return;n=s;const i=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(i,l,s,e,t);else{let e;d&&(e=this.pluralResolver.getSuffix(s,t.count,t));const a=`${this.options.pluralSeparator}zero`,r=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(t.ordinal&&0===e.indexOf(r)&&i.push(l+e.replace(r,this.options.pluralSeparator)),i.push(l+e),u&&i.push(l+a)),m){const s=`${l}${this.options.contextSeparator||"_"}${t.context}`;i.push(s),d&&(t.ordinal&&0===e.indexOf(r)&&i.push(s+e.replace(r,this.options.pluralSeparator)),i.push(s+e),u&&i.push(s+a))}}let o;for(;o=i.pop();)this.isValidLookup(a)||(r=o,a=this.getResource(s,e,o,t))}))})}),{res:a,usedKey:s,exactUsedKey:r,usedLng:n,usedNS:i}}isValidLookup(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}getResource(e,t,a,s={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,a,s):this.resourceStore.getResource(e,t,a,s)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],a=e.replace&&!ue(e.replace);let s=a?e.replace:e;if(a&&void 0!==e.count&&(s.count=e.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!a){s={...s};for(const e of t)delete s[e]}return s}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 ze{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Ae.create("languageUtils")}getScriptPartFromCode(e){if(!(e=Pe(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=Pe(e))||e.indexOf("-")<0)return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(ue(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 s=this.getLanguagePartFromCode(e);if(this.isSupportedCode(s))return t=s;t=this.options.supportedLngs.find(e=>e===s?e:e.indexOf("-")<0&&s.indexOf("-")<0?void 0:e.indexOf("-")>0&&s.indexOf("-")<0&&e.substring(0,e.indexOf("-"))===s||0===e.indexOf(s)&&s.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)),ue(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),s=[],r=e=>{e&&(this.isSupportedCode(e)?s.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return ue(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?("languageOnly"!==this.options.load&&r(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&r(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&r(this.getLanguagePartFromCode(e))):ue(e)&&r(this.formatLanguageCode(e)),a.forEach(e=>{s.indexOf(e)<0&&r(this.formatLanguageCode(e))}),s}}const $e={zero:0,one:1,two:2,few:3,many:4,other:5},Ue={select:e=>1===e?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Ve{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=Ae.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,t){this.rules[e]=t}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const a=Pe("dev"===e?"en":e),s=t.ordinal?"ordinal":"cardinal",r=JSON.stringify({cleanedCode:a,type:s});if(r in this.pluralRulesCache)return this.pluralRulesCache[r];let n;try{n=new Intl.PluralRules(a,{type:s})}catch(i){if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),Ue;if(!e.match(/-|_/))return Ue;const a=this.languageUtils.getLanguagePartFromCode(e);n=this.getRule(a,t)}return this.pluralRulesCache[r]=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)=>$e[e]-$e[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${e}`):[]}getSuffix(e,t,a={}){const s=this.getRule(e,a);return s?`${this.options.prepend}${a.ordinal?`ordinal${this.options.prepend}`:""}${s.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,a))}}const qe=(e,t,a,s=".",r=!0)=>{let n=((e,t,a)=>{const s=ve(e,a);return void 0!==s?s:ve(t,a)})(e,t,a);return!n&&r&&ue(a)&&(n=Ce(e,a,s),void 0===n&&(n=Ce(t,a,s))),n},Be=e=>e.replace(/\$/g,"$$$$");class We{constructor(e={}){this.logger=Ae.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:s,prefix:r,prefixEscaped:n,suffix:i,suffixEscaped:o,formatSeparator:l,unescapeSuffix:c,unescapePrefix:d,nestingPrefix:u,nestingPrefixEscaped:m,nestingSuffix:p,nestingSuffixEscaped:h,nestingOptionsSeparator:f,maxReplaces:g,alwaysFormat:x}=e.interpolation;this.escape=void 0!==t?t:we,this.escapeValue=void 0===a||a,this.useRawValueToEscape=void 0!==s&&s,this.prefix=r?Ne(r):n||"{{",this.suffix=i?Ne(i):o||"}}",this.formatSeparator=l||",",this.unescapePrefix=c?"":d||"-",this.unescapeSuffix=this.unescapePrefix?"":c||"",this.nestingPrefix=u?Ne(u):m||Ne("$t("),this.nestingSuffix=p?Ne(p):h||Ne(")"),this.nestingOptionsSeparator=f||",",this.maxReplaces=g||1e3,this.alwaysFormat=void 0!==x&&x,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,s){let r,n,i;const o=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=e=>{if(e.indexOf(this.formatSeparator)<0){const r=qe(t,o,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(r,void 0,a,{...s,...t,interpolationkey:e}):r}const r=e.split(this.formatSeparator),n=r.shift().trim(),i=r.join(this.formatSeparator).trim();return this.format(qe(t,o,n,this.options.keySeparator,this.options.ignoreJSONStructure),i,a,{...s,...t,interpolationkey:n})};this.resetRegExp();const c=s?.missingInterpolationHandler||this.options.missingInterpolationHandler,d=void 0!==s?.interpolation?.skipOnVariables?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>Be(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?Be(this.escape(e)):Be(e)}].forEach(t=>{for(i=0;r=t.regex.exec(e);){const a=r[1].trim();if(n=l(a),void 0===n)if("function"==typeof c){const t=c(e,r,s);n=ue(t)?t:""}else if(s&&Object.prototype.hasOwnProperty.call(s,a))n="";else{if(d){n=r[0];continue}this.logger.warn(`missed to pass in variable ${a} for interpolating ${e}`),n=""}else ue(n)||this.useRawValueToEscape||(n=pe(n));const o=t.safeValue(n);if(e=e.replace(r[0],o),d?(t.regex.lastIndex+=n.length,t.regex.lastIndex-=r[0].length):t.regex.lastIndex=0,i++,i>=this.maxReplaces)break}}),e}nest(e,t,a={}){let s,r,n;const i=(e,t)=>{const a=this.nestingOptionsSeparator;if(e.indexOf(a)<0)return e;const s=e.split(new RegExp(`${a}[ ]*{`));let r=`{${s[1]}`;e=s[0],r=this.interpolate(r,n);const i=r.match(/'/g),o=r.match(/"/g);((i?.length??0)%2==0&&!o||o.length%2!=0)&&(r=r.replace(/'/g,'"'));try{n=JSON.parse(r),t&&(n={...t,...n})}catch(l){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,l),`${e}${a}${r}`}return n.defaultValue&&n.defaultValue.indexOf(this.prefix)>-1&&delete n.defaultValue,e};for(;s=this.nestingRegexp.exec(e);){let o=[];n={...a},n=n.replace&&!ue(n.replace)?n.replace:n,n.applyPostProcessor=!1,delete n.defaultValue;const l=/{.*}/.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(-1!==l&&(o=s[1].slice(l).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),s[1]=s[1].slice(0,l)),r=t(i.call(this,s[1].trim(),n),n),r&&s[0]===e&&!ue(r))return r;ue(r)||(r=pe(r)),r||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),r=""),o.length&&(r=o.reduce((e,t)=>this.format(e,t,a.lng,{...a,interpolationkey:s[1].trim()}),r.trim())),e=e.replace(s[0],r),this.regexp.lastIndex=0}return e}}const He=e=>{const t={};return(a,s,r)=>{let n=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(n={...n,[r.interpolationkey]:void 0});const i=s+JSON.stringify(n);let o=t[i];return o||(o=e(Pe(s),r),t[i]=o),o(a)}},Ke=e=>(t,a,s)=>e(Pe(a),s)(t);class Qe{constructor(e={}){this.logger=Ae.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const a=t.cacheInBuiltFormats?He:Ke;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()]=He(t)}format(e,t,a,s={}){const r=t.split(this.formatSeparator);if(r.length>1&&r[0].indexOf("(")>1&&r[0].indexOf(")")<0&&r.find(e=>e.indexOf(")")>-1)){const e=r.findIndex(e=>e.indexOf(")")>-1);r[0]=[r[0],...r.splice(1,e)].join(this.formatSeparator)}return r.reduce((e,t)=>{const{formatName:r,formatOptions:n}=(e=>{let t=e.toLowerCase().trim();const a={};if(e.indexOf("(")>-1){const s=e.split("(");t=s[0].toLowerCase().trim();const r=s[1].substring(0,s[1].length-1);"currency"===t&&r.indexOf(":")<0?a.currency||(a.currency=r.trim()):"relativetime"===t&&r.indexOf(":")<0?a.range||(a.range=r.trim()):r.split(";").forEach(e=>{if(e){const[t,...s]=e.split(":"),r=s.join(":").trim().replace(/^'+|'+$/g,""),n=t.trim();a[n]||(a[n]=r),"false"===r&&(a[n]=!1),"true"===r&&(a[n]=!0),isNaN(r)||(a[n]=parseInt(r,10))}})}return{formatName:t,formatOptions:a}})(t);if(this.formats[r]){let t=e;try{const i=s?.formatParams?.[s.interpolationkey]||{},o=i.locale||i.lng||s.locale||s.lng||a;t=this.formats[r](e,o,{...n,...s,...i})}catch(i){this.logger.warn(i)}return t}return this.logger.warn(`there was no format function for ${r}`),e},e)}}class Ge extends _e{constructor(e,t,a,s={}){super(),this.backend=e,this.store=t,this.services=a,this.languageUtils=a.languageUtils,this.options=s,this.logger=Ae.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(a,s.backend,s)}queueLoad(e,t,a,s){const r={},n={},i={},o={};return e.forEach(e=>{let s=!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,s=!1,void 0===n[i]&&(n[i]=!0),void 0===r[i]&&(r[i]=!0),void 0===o[t]&&(o[t]=!0)))}),s||(i[e]=!0)}),(Object.keys(r).length||Object.keys(n).length)&&this.queue.push({pending:n,pendingCount:Object.keys(n).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(r),pending:Object.keys(n),toLoadLanguages:Object.keys(i),toLoadNamespaces:Object.keys(o)}}loaded(e,t,a){const s=e.split("|"),r=s[0],n=s[1];t&&this.emit("failedLoading",r,n,t),!t&&a&&this.store.addResourceBundle(r,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:s,k:r}=xe(e,t,Object);s[r]=s[r]||[],s[r].push(a)})(a.loaded,[r],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,s=0,r=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:s,wait:r,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&&s<this.maxRetries?setTimeout(()=>{this.read.call(this,e,t,a,s+1,2*r,n)},r):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={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();ue(e)&&(e=this.languageUtils.toResolveHierarchy(e)),ue(t)&&(t=[t]);const r=this.queueLoad(e,t,a,s);if(!r.toLoad.length)return r.pending.length||s(),null;r.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("|"),s=a[0],r=a[1];this.read(s,r,"read",void 0,void 0,(a,n)=>{a&&this.logger.warn(`${t}loading namespace ${r} for language ${s} failed`,a),!a&&n&&this.logger.log(`${t}loaded namespace ${r} for language ${s}`,n),this.loaded(e,a,n)})}saveMissing(e,t,a,s,r,n={},i=()=>{}){if(!this.services?.utils?.hasLoadedNamespace||this.services?.utils?.hasLoadedNamespace(t)){if(null!=a&&""!==a){if(this.backend?.create){const l={...n,isUpdate:r},c=this.backend.create.bind(this.backend);if(c.length<6)try{let r;r=5===c.length?c(e,t,a,s,l):c(e,t,a,s),r&&"function"==typeof r.then?r.then(e=>i(null,e)).catch(i):i(null,r)}catch(o){i(o)}else c(e,t,a,s,i,l)}e&&e[0]&&this.store.addResource(e[0],t,a,s)}}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 Xe=()=>({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]),ue(e[1])&&(t.defaultValue=e[1]),ue(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}),Je=e=>(ue(e.ns)&&(e.ns=[e.ns]),ue(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),ue(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),Ye=()=>{};class Ze extends _e{constructor(e={},t){var a;if(super(),this.options=Je(e),this.services={},this.logger=Ae,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&&(ue(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const a=Xe();this.options={...a,...this.options,...Je(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 s=e=>e?"function"==typeof e?new e:e:null;if(!this.options.isClone){let e;this.modules.logger?Ae.init(s(this.modules.logger),this.options):Ae.init(null,this.options),e=this.modules.formatter?this.modules.formatter:Qe;const t=new ze(this.options);this.store=new Ie(this.options.resources,this.options);const r=this.services;r.logger=Ae,r.resourceStore=this.store,r.languageUtils=t,r.pluralResolver=new Ve(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||(r.formatter=s(e),r.formatter.init&&r.formatter.init(r,this.options),this.options.interpolation.format=r.formatter.format.bind(r.formatter)),r.interpolator=new We(this.options),r.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},r.backendConnector=new Ge(s(this.modules.backend),r.resourceStore,r,this.options),r.backendConnector.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(r.languageDetector=s(this.modules.languageDetector),r.languageDetector.init&&r.languageDetector.init(r,this.options.detection,this.options)),this.modules.i18nFormat&&(r.i18nFormat=s(this.modules.i18nFormat),r.i18nFormat.init&&r.i18nFormat.init(this)),this.translator=new Me(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=Ye),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 r=me(),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),r.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),r}loadResources(e,t=Ye){let a=t;const s=ue(e)?e:this.language;if("function"==typeof e&&(a=e),!this.options.resources||this.options.partialBundledLanguages){if("cimode"===s?.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(s)t(s);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 s=me();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=Ye),this.services.backendConnector.reload(e,t,e=>{s.resolve(),a(e)}),s}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&&Re.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=me();this.emit("languageChanging",e);const s=e=>{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},r=(r,n)=>{n?this.isLanguageChangingTo===e&&(s(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(r,(...e)=>this.t(...e))},n=t=>{e||t||!this.services.languageDetector||(t=[]);const a=ue(t)?t:t&&t[0],n=this.store.hasLanguageSomeTranslations(a)?a:this.services.languageUtils.getBestMatchFromCodes(ue(t)?[t]:t);n&&(this.language||s(n),this.translator.language||this.translator.changeLanguage(n),this.services.languageDetector?.cacheUserLanguage?.(n)),this.loadResources(n,e=>{r(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 s=(e,t,...r)=>{let n;n="object"!=typeof t?this.options.overloadTranslationOptionHandler([e,t].concat(r)):{...t},n.lng=n.lng||s.lng,n.lngs=n.lngs||s.lngs,n.ns=n.ns||s.ns,""!==n.keyPrefix&&(n.keyPrefix=n.keyPrefix||a||s.keyPrefix);const i=this.options.keySeparator||".";let o;return n.keyPrefix&&Array.isArray(e)?o=e.map(e=>("function"==typeof e&&(e=Oe(e,{...this.options,...t})),`${n.keyPrefix}${i}${e}`)):("function"==typeof e&&(e=Oe(e,{...this.options,...t})),o=n.keyPrefix?`${n.keyPrefix}${i}${e}`:e),this.t(o,n)};return ue(e)?s.lng=e:s.lngs=e,s.ns=t,s.keyPrefix=a,s}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],s=!!this.options&&this.options.fallbackLng,r=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)||s&&!n(r,e)))}loadNamespaces(e,t){const a=me();return this.options.ns?(ue(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=me();ue(e)&&(e=[e]);const s=this.options.preload||[],r=e.filter(e=>s.indexOf(e)<0&&this.services.languageUtils.isSupportedCode(e));return r.length?(this.options.preload=s.concat(r),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 ze(Xe());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 Ze(e,t);return a.createInstance=Ze.createInstance,a}cloneInstance(e={},t=Ye){const a=e.forkResourceStore;a&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},r=new Ze(s);void 0===e.debug&&void 0===e.prefix||(r.logger=r.logger.clone(e));if(["store","services","language"].forEach(e=>{r[e]=this[e]}),r.services={...this.services},r.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},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,s)=>(a[s]={...e[t][s]},a),e[t]),e),{});r.store=new Ie(e,s),r.services.resourceStore=r.store}return r.translator=new Me(r.services,s),r.translator.on("*",(e,...t)=>{r.emit(e,...t)}),r.init(s,t),r.translator.options=s,r.translator.backendConnector.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},r}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const et=Ze.createInstance();function tt(e,t){t?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{o.toast.info(et.t("link_copied"))})}function at(...e){return n.twMerge(r.clsx(e))}et.createInstance,et.dir,et.init,et.loadResources,et.reloadResources,et.use,et.changeLanguage,et.getFixedT,et.t,et.exists,et.setDefaultNamespace,et.hasLoadedNamespace,et.loadNamespaces,et.loadLanguages;const st=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(st);if("object"==typeof e&&e.constructor===Object){const t={};for(const[a,s]of Object.entries(e))t[a]=st(s);return t}return e},rt=s.cva("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"}}),nt=V.forwardRef(({className:t,variant:s,size:r,asChild:n=!1,...i},o)=>{const l=n?a.Slot:"button";return e.jsx(l,{className:at(rt({variant:s,size:r,className:t})),ref:o,...i})});nt.displayName="Button";const it=t.forwardRef(({variant:t="default",className:a,children:s,...r},n)=>e.jsx(nt,{ref:n,variant:"action",size:"sm",className:at("h-7 px-2 text-xs",a),...r,children:s||e.jsx(l.EllipsisVertical,{size:12})}));it.displayName="ActionButton";const ot=V.forwardRef(({className:t,type:a,...s},r)=>e.jsx("input",{type:a,className:at("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:r,...s}));ot.displayName="Input";const lt=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ct=V.forwardRef(({className:t,...a},s)=>e.jsx(q.Root,{ref:s,className:at(lt(),t),...a}));ct.displayName=q.Root.displayName;const dt=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));dt.displayName="Card";const ut=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("flex flex-col space-y-1.5 p-6",t),...a}));ut.displayName="CardHeader";const mt=V.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:at("text-2xl font-semibold leading-none tracking-tight",t),...a}));mt.displayName="CardTitle";const pt=V.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:at("text-sm text-muted-foreground",t),...a}));pt.displayName="CardDescription";const ht=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("p-6 pt-0",t),...a}));ht.displayName="CardContent";const ft=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("flex items-center p-6 pt-0",t),...a}));ft.displayName="CardFooter";const gt=B.Root,xt=B.Trigger,bt=B.Portal,vt=B.Close,yt=V.forwardRef(({className:t,...a},s)=>e.jsx(B.Overlay,{ref:s,className:at("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}));yt.displayName=B.Overlay.displayName;const Nt=V.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(bt,{children:[e.jsx(yt,{}),e.jsxs(B.Content,{ref:r,className:at("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",t),...s,children:[a,e.jsxs(B.Close,{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 data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Nt.displayName=B.Content.displayName;const jt=({className:t,...a})=>e.jsx("div",{className:at("flex flex-col space-y-1.5 text-center sm:text-left",t),...a});jt.displayName="DialogHeader";const wt=({className:t,...a})=>e.jsx("div",{className:at("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});wt.displayName="DialogFooter";const kt=V.forwardRef(({className:t,...a},s)=>e.jsx(B.Title,{ref:s,className:at("text-lg font-semibold leading-none tracking-tight",t),...a}));kt.displayName=B.Title.displayName;const St=V.forwardRef(({className:t,...a},s)=>e.jsx(B.Description,{ref:s,className:at("text-sm text-muted-foreground",t),...a}));St.displayName=B.Description.displayName;const Ct=u.FormProvider,Pt=V.createContext({}),Et=()=>{const e=V.useContext(Pt),t=V.useContext(Tt),{getFieldState:a,formState:s}=u.useFormContext(),r=a(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=t;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},Tt=V.createContext({}),At=V.forwardRef(({className:t,...a},s)=>{const r=V.useId();return e.jsx(Tt.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:at("space-y-2",t),...a})})});At.displayName="FormItem";const _t=V.forwardRef(({className:t,...a},s)=>{const{error:r,formItemId:n}=Et();return e.jsx(ct,{ref:s,className:at(r&&"text-destructive",t),htmlFor:n,...a})});_t.displayName="FormLabel";const It=V.forwardRef(({...t},s)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=Et();return e.jsx(a.Slot,{ref:s,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...t})});It.displayName="FormControl";const Rt=V.forwardRef(({className:t,...a},s)=>{const{formDescriptionId:r}=Et();return e.jsx("p",{ref:s,id:r,className:at("text-sm text-muted-foreground",t),...a})});Rt.displayName="FormDescription";const Lt=V.forwardRef(({className:t,children:a,...s},r)=>{const{error:n,formMessageId:i}=Et(),o=n?String(n?.message):a;return o?e.jsx("p",{ref:r,id:i,className:at("text-sm font-medium text-destructive",t),...s,children:o}):null});Lt.displayName="FormMessage";const Ot=W.Root,Ft=W.Group,Dt=W.Value,Mt=V.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(W.Trigger,{ref:r,className:at("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",t),...s,children:[a,e.jsx(W.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Mt.displayName=W.Trigger.displayName;const zt=V.forwardRef(({className:t,...a},s)=>e.jsx(W.ScrollUpButton,{ref:s,className:at("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));zt.displayName=W.ScrollUpButton.displayName;const $t=V.forwardRef(({className:t,...a},s)=>e.jsx(W.ScrollDownButton,{ref:s,className:at("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));$t.displayName=W.ScrollDownButton.displayName;const Ut=V.forwardRef(({className:t,children:a,position:s="popper",container:r,collisionBoundary:n,...i},o)=>e.jsx(W.Portal,{container:r,children:e.jsxs(W.Content,{ref:o,className:at("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",t),position:s,collisionBoundary:n,...i,children:[e.jsx(zt,{}),e.jsx(W.Viewport,{className:at("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:a}),e.jsx($t,{})]})}));Ut.displayName=W.Content.displayName;const Vt=V.forwardRef(({className:t,...a},s)=>e.jsx(W.Label,{ref:s,className:at("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a}));Vt.displayName=W.Label.displayName;const qt=V.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(W.Item,{ref:r,className:at("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",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(W.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),e.jsx(W.ItemText,{children:a})]}));qt.displayName=W.Item.displayName;const Bt=V.forwardRef(({className:t,...a},s)=>e.jsx(W.Separator,{ref:s,className:at("-mx-1 my-1 h-px bg-muted",t),...a}));Bt.displayName=W.Separator.displayName;const Wt=V.forwardRef(({className:t,...a},s)=>e.jsx(H.Root,{ref:s,className:at("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.jsx(H.Indicator,{className:at("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));Wt.displayName=H.Root.displayName;const Ht=V.forwardRef(({className:t,...a},s)=>e.jsx("textarea",{className:at("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:s,...a}));Ht.displayName="Textarea";const Kt=s.cva("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",info:"border-transparent bg-blue-500 text-white hover:bg-blue-600"}},defaultVariants:{variant:"default"}}),Qt=V.forwardRef(({className:t,variant:a,...s},r)=>e.jsx("div",{ref:r,className:at(Kt({variant:a}),t),...s}));Qt.displayName="Badge";const Gt={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Xt({size:t="md",className:a}){return e.jsx(l.Loader2,{className:at("animate-spin text-muted-foreground",Gt[t],a)})}let Jt=0;const Yt=new Map,Zt=e=>{if(Yt.has(e))return;const t=setTimeout(()=>{Yt.delete(e),sa({type:"REMOVE_TOAST",toastId:e})},1e6);Yt.set(e,t)},ea=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{const{toastId:a}=t;return a?Zt(a):e.toasts.forEach(e=>{Zt(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===a||void 0===a?{...e,open:!1}:e)}}case"REMOVE_TOAST":return void 0===t.toastId?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},ta=[];let aa={toasts:[]};function sa(e){aa=ea(aa,e),ta.forEach(e=>{e(aa)})}function ra({...e}){const t=(Jt=(Jt+1)%Number.MAX_SAFE_INTEGER,Jt.toString()),a=()=>sa({type:"DISMISS_TOAST",toastId:t});return sa({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||a()}}}),{id:t,dismiss:a,update:e=>sa({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function na(){const[e,t]=V.useState(aa);return V.useEffect(()=>(ta.push(t),()=>{const e=ta.indexOf(t);e>-1&&ta.splice(e,1)}),[e]),{...e,toast:ra,dismiss:e=>sa({type:"DISMISS_TOAST",toastId:e})}}const ia=K.Provider,oa=V.forwardRef(({className:t,...a},s)=>e.jsx(K.Viewport,{ref:s,className:at("fixed top-4 left-1/2 transform -translate-x-1/2 z-[100] flex max-h-screen w-full max-w-[420px] flex-col p-4",t),...a}));oa.displayName=K.Viewport.displayName;const la=s.cva("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),ca=V.forwardRef(({className:t,variant:a,...s},r)=>e.jsx(K.Root,{ref:r,className:at(la({variant:a}),t),...s}));ca.displayName=K.Root.displayName;const da=V.forwardRef(({className:t,...a},s)=>e.jsx(K.Action,{ref:s,className:at("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",t),...a}));da.displayName=K.Action.displayName;const ua=V.forwardRef(({className:t,...a},s)=>e.jsx(K.Close,{ref:s,className:at("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...a,children:e.jsx(l.X,{className:"h-4 w-4"})}));ua.displayName=K.Close.displayName;const ma=V.forwardRef(({className:t,...a},s)=>e.jsx(K.Title,{ref:s,className:at("text-sm font-semibold",t),...a}));ma.displayName=K.Title.displayName;const pa=V.forwardRef(({className:t,...a},s)=>e.jsx(K.Description,{ref:s,className:at("text-sm opacity-90",t),...a}));pa.displayName=K.Description.displayName;const ha=Q.Root,fa=Q.Trigger,ga=V.forwardRef(({className:t,align:a="center",sideOffset:s=4,container:r,...n},i)=>e.jsx(Q.Portal,{container:r,children:e.jsx(Q.Content,{ref:i,align:a,sideOffset:s,className:at("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})}));ga.displayName=Q.Content.displayName;const xa=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...a}));xa.displayName="Command";const ba=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:at("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})}));ba.displayName="CommandInput";const va=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...a}));va.displayName="CommandList";const ya=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("py-6 text-center text-sm text-muted-foreground",t),...a}));ya.displayName="CommandEmpty";const Na=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("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}));Na.displayName="CommandGroup";const ja=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("-mx-1 h-px bg-border",t),...a}));ja.displayName="CommandSeparator";const wa=V.forwardRef(({className:t,disabled:a,onSelect:s,value:r,...n},i)=>e.jsx("div",{ref:i,className:at("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&&s?.(r||""),...n}));wa.displayName="CommandItem";const ka=({className:t,...a})=>e.jsx("span",{className:at("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});function Sa({className:t,...a}){return e.jsx("div",{className:at("animate-pulse rounded-md bg-muted",t),...a})}ka.displayName="CommandShortcut";const Ca={},Pa=(e,t,a,s)=>{_a(a)&&Ca[a]||(_a(a)&&(Ca[a]=new Date),((e,t,a,s)=>{const r=[a,{code:t,...s||{}}];if(e?.services?.logger?.forward)return e.services.logger.forward(r,"warn","react-i18next::",!0);_a(r[0])&&(r[0]=`react-i18next:: ${r[0]}`),e?.services?.logger?.warn?e.services.logger.warn(...r):console})(e,t,a,s))},Ea=(e,t)=>()=>{if(e.isInitialized)t();else{const a=()=>{setTimeout(()=>{e.off("initialized",a)},0),t()};e.on("initialized",a)}},Ta=(e,t,a)=>{e.loadNamespaces(t,Ea(e,a))},Aa=(e,t,a,s)=>{if(_a(a)&&(a=[a]),e.options.preload&&e.options.preload.indexOf(t)>-1)return Ta(e,a,s);a.forEach(t=>{e.options.ns.indexOf(t)<0&&e.options.ns.push(t)}),e.loadLanguages(t,Ea(e,s))},_a=e=>"string"==typeof e,Ia=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Ra={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},La=e=>Ra[e];let Oa={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:e=>e.replace(Ia,La)};let Fa;const Da={type:"3rdParty",init(e){((e={})=>{Oa={...Oa,...e}})(e.options.react),(e=>{Fa=e})(e)}},Ma=t.createContext();class za{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(e=>{this.usedNamespaces[e]||(this.usedNamespaces[e]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var $a,Ua={exports:{}},Va={};var qa,Ba,Wa={};
1
+ "use strict";var e=require("react/jsx-runtime"),t=require("react"),a=require("@radix-ui/react-slot"),s=require("class-variance-authority"),r=require("clsx"),n=require("tailwind-merge"),i=require("date-fns"),o=require("sonner"),l=require("lucide-react"),d=require("@radix-ui/react-label"),c=require("@radix-ui/react-dialog"),u=require("react-hook-form"),m=require("@radix-ui/react-select"),p=require("@radix-ui/react-checkbox"),h=require("@radix-ui/react-toast"),f=require("@radix-ui/react-popover"),x=require("@supabase/supabase-js"),g=require("@tanstack/react-query"),b=require("react-router-dom"),v=require("@radix-ui/react-alert-dialog"),y=require("@radix-ui/react-dropdown-menu"),N=require("@radix-ui/react-context-menu"),j=require("@radix-ui/react-scroll-area"),w=require("@radix-ui/react-switch"),k=require("@radix-ui/react-progress"),C=require("@radix-ui/react-accordion"),S=require("@radix-ui/react-aspect-ratio"),P=require("@radix-ui/react-avatar"),E=require("react-day-picker"),T=require("@radix-ui/react-collapsible"),A=require("vaul"),_=require("@radix-ui/react-radio-group"),I=require("@radix-ui/react-separator"),R=require("@radix-ui/react-tooltip"),L=require("@radix-ui/react-slider"),M=require("next-themes"),O=require("@radix-ui/react-tabs"),D=require("@radix-ui/react-toggle"),F=require("@radix-ui/react-toggle-group"),z=require("react-markdown"),$=require("remark-gfm"),U=require("zod"),V=require("@hookform/resolvers");function q(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(a){if("default"!==a){var s=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(t,a,s.get?s:{enumerable:!0,get:function(){return e[a]}})}}),t.default=e,Object.freeze(t)}var B=q(t),W=q(d),H=q(c),K=q(m),G=q(p),Q=q(h),X=q(f),J=q(v),Y=q(y),Z=q(N),ee=q(j),te=q(w),ae=q(k),se=q(C),re=q(S),ne=q(P),ie=q(T),oe=q(_),le=q(I),de=q(R),ce=q(L),ue=q(O),me=q(D),pe=q(F);const he=e=>"string"==typeof e,fe=()=>{let e,t;const a=new Promise((a,s)=>{e=a,t=s});return a.resolve=e,a.reject=t,a},xe=e=>null==e?"":""+e,ge=/###/g,be=e=>e&&e.indexOf("###")>-1?e.replace(ge,"."):e,ve=e=>!e||he(e),ye=(e,t,a)=>{const s=he(t)?t.split("."):t;let r=0;for(;r<s.length-1;){if(ve(e))return{};const t=be(s[r]);!e[t]&&a&&(e[t]=new a),e=Object.prototype.hasOwnProperty.call(e,t)?e[t]:{},++r}return ve(e)?{}:{obj:e,k:be(s[r])}},Ne=(e,t,a)=>{const{obj:s,k:r}=ye(e,t,Object);if(void 0!==s||1===t.length)return void(s[r]=a);let n=t[t.length-1],i=t.slice(0,t.length-1),o=ye(e,i,Object);for(;void 0===o.obj&&i.length;)n=`${i[i.length-1]}.${n}`,i=i.slice(0,i.length-1),o=ye(e,i,Object),o?.obj&&void 0!==o.obj[`${o.k}.${n}`]&&(o.obj=void 0);o.obj[`${o.k}.${n}`]=a},je=(e,t)=>{const{obj:a,k:s}=ye(e,t);if(a&&Object.prototype.hasOwnProperty.call(a,s))return a[s]},we=(e,t,a)=>{for(const s in t)"__proto__"!==s&&"constructor"!==s&&(s in e?he(e[s])||e[s]instanceof String||he(t[s])||t[s]instanceof String?a&&(e[s]=t[s]):we(e[s],t[s],a):e[s]=t[s]);return e},ke=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var Ce={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const Se=e=>he(e)?e.replace(/[&<>"'\/]/g,e=>Ce[e]):e;const Pe=[" ",",","?","!",";"],Ee=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),Te=(e,t,a=".")=>{if(!e)return;if(e[t]){if(!Object.prototype.hasOwnProperty.call(e,t))return;return e[t]}const s=t.split(a);let r=e;for(let n=0;n<s.length;){if(!r||"object"!=typeof r)return;let e,t="";for(let i=n;i<s.length;++i)if(i!==n&&(t+=a),t+=s[i],e=r[t],void 0!==e){if(["string","number","boolean"].indexOf(typeof e)>-1&&i<s.length-1)continue;n+=i-n+1;break}r=e}return r},Ae=e=>e?.replace("_","-"),_e={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){}};class Ie{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||_e,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,s){return s&&!this.debug?null:(he(e[0])&&(e[0]=`${a}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new Ie(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return(e=e||this.options).prefix=e.prefix||this.prefix,new Ie(this.logger,e)}}var Re=new Ie;class Le{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 s=0;s<a;s++)e(...t)})}if(this.observers["*"]){Array.from(this.observers["*"].entries()).forEach(([a,s])=>{for(let r=0;r<s;r++)a.apply(a,[e,...t])})}}}class Me extends Le{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,s={}){const r=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator,n=void 0!==s.ignoreJSONStructure?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let i;e.indexOf(".")>-1?i=e.split("."):(i=[e,t],a&&(Array.isArray(a)?i.push(...a):he(a)&&r?i.push(...a.split(r)):i.push(a)));const o=je(this.data,i);return!o&&!t&&!a&&e.indexOf(".")>-1&&(e=i[0],t=i[1],a=i.slice(2).join(".")),!o&&n&&he(a)?Te(this.data?.[e]?.[t],a,r):o}addResource(e,t,a,s,r={silent:!1}){const n=void 0!==r.keySeparator?r.keySeparator:this.options.keySeparator;let i=[e,t];a&&(i=i.concat(n?a.split(n):a)),e.indexOf(".")>-1&&(i=e.split("."),s=t,t=i[1]),this.addNamespaces(t),Ne(this.data,i,s),r.silent||this.emit("added",e,t,a,s)}addResources(e,t,a,s={silent:!1}){for(const r in a)(he(a[r])||Array.isArray(a[r]))&&this.addResource(e,t,r,a[r],{silent:!0});s.silent||this.emit("added",e,t,a)}addResourceBundle(e,t,a,s,r,n={silent:!1,skipCopy:!1}){let i=[e,t];e.indexOf(".")>-1&&(i=e.split("."),s=a,a=t,t=i[1]),this.addNamespaces(t);let o=je(this.data,i)||{};n.skipCopy||(a=JSON.parse(JSON.stringify(a))),s?we(o,a,r):o={...o,...a},Ne(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 Oe={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,a,s,r){return e.forEach(e=>{t=this.processors[e]?.process(t,a,s,r)??t}),t}};const De=Symbol("i18next/PATH_KEY");function Fe(e,t){const{[De]:a}=e(function(){const e=[],t=Object.create(null);let a;return t.get=(s,r)=>(a?.revoke?.(),r===De?e:(e.push(r),a=Proxy.revocable(s,t),a.proxy)),Proxy.revocable(Object.create(null),t).proxy}());return a.join(t?.keySeparator??".")}const ze={},$e=e=>!he(e)&&"boolean"!=typeof e&&"number"!=typeof e;class Ue extends Le{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=Re.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const a={...t};if(null==e)return!1;const s=this.resolve(e,a);if(void 0===s?.res)return!1;const r=$e(s.res);return!1!==a.returnObjects||!r}extractFromKey(e,t){let a=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===a&&(a=":");const s=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator;let r=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 s=Pe.filter(e=>t.indexOf(e)<0&&a.indexOf(e)<0);if(0===s.length)return!0;const r=Ee.getRegExp(`(${s.map(e=>"?"===e?"\\?":e).join("|")})`);let n=!r.test(e);if(!n){const t=e.indexOf(a);t>0&&!r.test(e.substring(0,t))&&(n=!0)}return n})(e,a,s));if(n&&!i){const t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:he(r)?[r]:r};const n=e.split(a);(a!==s||a===s&&this.options.ns.indexOf(n[0])>-1)&&(r=n.shift()),e=n.join(s)}return{key:e,namespaces:he(r)?[r]:r}}translate(e,t,a){let s="object"==typeof t?{...t}:t;if("object"!=typeof s&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof s&&(s={...s}),s||(s={}),null==e)return"";"function"==typeof e&&(e=Fe(e,{...this.options,...s})),Array.isArray(e)||(e=[String(e)]);const r=void 0!==s.returnDetails?s.returnDetails:this.options.returnDetails,n=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator,{key:i,namespaces:o}=this.extractFromKey(e[e.length-1],s),l=o[o.length-1];let d=void 0!==s.nsSeparator?s.nsSeparator:this.options.nsSeparator;void 0===d&&(d=":");const c=s.lng||this.language,u=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if("cimode"===c?.toLowerCase())return u?r?{res:`${l}${d}${i}`,usedKey:i,exactUsedKey:i,usedLng:c,usedNS:l,usedParams:this.getUsedParamsDetails(s)}:`${l}${d}${i}`:r?{res:i,usedKey:i,exactUsedKey:i,usedLng:c,usedNS:l,usedParams:this.getUsedParamsDetails(s)}:i;const m=this.resolve(e,s);let p=m?.res;const h=m?.usedKey||i,f=m?.exactUsedKey||i,x=void 0!==s.joinArrays?s.joinArrays:this.options.joinArrays,g=!this.i18nFormat||this.i18nFormat.handleAsObject,b=void 0!==s.count&&!he(s.count),v=Ue.hasDefaultValue(s),y=b?this.pluralResolver.getSuffix(c,s.count,s):"",N=s.ordinal&&b?this.pluralResolver.getSuffix(c,s.count,{ordinal:!1}):"",j=b&&!s.ordinal&&0===s.count,w=j&&s[`defaultValue${this.options.pluralSeparator}zero`]||s[`defaultValue${y}`]||s[`defaultValue${N}`]||s.defaultValue;let k=p;g&&!p&&v&&(k=w);const C=$e(k),S=Object.prototype.toString.apply(k);if(!(g&&k&&C&&["[object Number]","[object Function]","[object RegExp]"].indexOf(S)<0)||he(x)&&Array.isArray(k))if(g&&he(x)&&Array.isArray(p))p=p.join(x),p&&(p=this.extendTranslation(p,e,s,a));else{let t=!1,r=!1;!this.isValidLookup(p)&&v&&(t=!0,p=w),this.isValidLookup(p)||(r=!0,p=i);const o=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&r?void 0:p,u=v&&w!==p&&this.options.updateMissing;if(r||t||u){if(this.logger.log(u?"updateKey":"missingKey",c,l,i,u?w:p),n){const e=this.resolve(i,{...s,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,s.lng||this.language);if("fallback"===this.options.saveMissingTo&&t&&t[0])for(let s=0;s<t.length;s++)e.push(t[s]);else"all"===this.options.saveMissingTo?e=this.languageUtils.toResolveHierarchy(s.lng||this.language):e.push(s.lng||this.language);const a=(e,t,a)=>{const r=v&&a!==p?a:o;this.options.missingKeyHandler?this.options.missingKeyHandler(e,l,t,r,u,s):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,l,t,r,u,s),this.emit("missingKey",e,l,t,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&b?e.forEach(e=>{const t=this.pluralResolver.getSuffixes(e,s);j&&s[`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,s[`defaultValue${t}`]||w)})}):a(e,i,w))}p=this.extendTranslation(p,e,s,m,a),r&&p===i&&this.options.appendNamespaceToMissingKey&&(p=`${l}${d}${i}`),(r||t)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${d}${i}`:i,t?p:void 0,s))}else{if(!s.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(h,k,{...s,ns:o}):`key '${i} (${this.language})' returned an object instead of string.`;return r?(m.res=e,m.usedParams=this.getUsedParamsDetails(s),m):e}if(n){const e=Array.isArray(k),t=e?[]:{},a=e?f:h;for(const r in k)if(Object.prototype.hasOwnProperty.call(k,r)){const e=`${a}${n}${r}`;t[r]=v&&!p?this.translate(e,{...s,defaultValue:$e(w)?w[r]:void 0,joinArrays:!1,ns:o}):this.translate(e,{...s,joinArrays:!1,ns:o}),t[r]===e&&(t[r]=k[r])}p=t}}return r?(m.res=p,m.usedParams=this.getUsedParamsDetails(s),m):p}extendTranslation(e,t,a,s,r){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...a},a.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!a.skipInterpolation){a.interpolation&&this.interpolator.init({...a,interpolation:{...this.options.interpolation,...a.interpolation}});const n=he(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&&!he(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||s.usedLng,a),n){const t=e.match(this.interpolator.nestingRegexp);i<(t&&t.length)&&(a.nest=!1)}!a.lng&&s&&s.res&&(a.lng=this.language||s.usedLng),!1!==a.nest&&(e=this.interpolator.nest(e,(...e)=>r?.[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=he(n)?[n]:n;return null!=e&&i?.length&&!1!==a.applyPostProcessor&&(e=Oe.handle(i,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...s,usedParams:this.getUsedParamsDetails(a)},...a}:a,this)),e}resolve(e,t={}){let a,s,r,n,i;return he(e)&&(e=[e]),e.forEach(e=>{if(this.isValidLookup(a))return;const o=this.extractFromKey(e,t),l=o.key;s=l;let d=o.namespaces;this.options.fallbackNS&&(d=d.concat(this.options.fallbackNS));const c=void 0!==t.count&&!he(t.count),u=c&&!t.ordinal&&0===t.count,m=void 0!==t.context&&(he(t.context)||"number"==typeof t.context)&&""!==t.context,p=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);d.forEach(e=>{this.isValidLookup(a)||(i=e,ze[`${p[0]}-${e}`]||!this.utils?.hasLoadedNamespace||this.utils?.hasLoadedNamespace(i)||(ze[`${p[0]}-${e}`]=!0,this.logger.warn(`key "${s}" for languages "${p.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!!!")),p.forEach(s=>{if(this.isValidLookup(a))return;n=s;const i=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(i,l,s,e,t);else{let e;c&&(e=this.pluralResolver.getSuffix(s,t.count,t));const a=`${this.options.pluralSeparator}zero`,r=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(c&&(t.ordinal&&0===e.indexOf(r)&&i.push(l+e.replace(r,this.options.pluralSeparator)),i.push(l+e),u&&i.push(l+a)),m){const s=`${l}${this.options.contextSeparator||"_"}${t.context}`;i.push(s),c&&(t.ordinal&&0===e.indexOf(r)&&i.push(s+e.replace(r,this.options.pluralSeparator)),i.push(s+e),u&&i.push(s+a))}}let o;for(;o=i.pop();)this.isValidLookup(a)||(r=o,a=this.getResource(s,e,o,t))}))})}),{res:a,usedKey:s,exactUsedKey:r,usedLng:n,usedNS:i}}isValidLookup(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}getResource(e,t,a,s={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,a,s):this.resourceStore.getResource(e,t,a,s)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],a=e.replace&&!he(e.replace);let s=a?e.replace:e;if(a&&void 0!==e.count&&(s.count=e.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!a){s={...s};for(const e of t)delete s[e]}return s}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 Ve{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Re.create("languageUtils")}getScriptPartFromCode(e){if(!(e=Ae(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=Ae(e))||e.indexOf("-")<0)return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(he(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 s=this.getLanguagePartFromCode(e);if(this.isSupportedCode(s))return t=s;t=this.options.supportedLngs.find(e=>e===s?e:e.indexOf("-")<0&&s.indexOf("-")<0?void 0:e.indexOf("-")>0&&s.indexOf("-")<0&&e.substring(0,e.indexOf("-"))===s||0===e.indexOf(s)&&s.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)),he(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),s=[],r=e=>{e&&(this.isSupportedCode(e)?s.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return he(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?("languageOnly"!==this.options.load&&r(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&r(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&r(this.getLanguagePartFromCode(e))):he(e)&&r(this.formatLanguageCode(e)),a.forEach(e=>{s.indexOf(e)<0&&r(this.formatLanguageCode(e))}),s}}const qe={zero:0,one:1,two:2,few:3,many:4,other:5},Be={select:e=>1===e?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class We{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=Re.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,t){this.rules[e]=t}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const a=Ae("dev"===e?"en":e),s=t.ordinal?"ordinal":"cardinal",r=JSON.stringify({cleanedCode:a,type:s});if(r in this.pluralRulesCache)return this.pluralRulesCache[r];let n;try{n=new Intl.PluralRules(a,{type:s})}catch(i){if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),Be;if(!e.match(/-|_/))return Be;const a=this.languageUtils.getLanguagePartFromCode(e);n=this.getRule(a,t)}return this.pluralRulesCache[r]=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)=>qe[e]-qe[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${e}`):[]}getSuffix(e,t,a={}){const s=this.getRule(e,a);return s?`${this.options.prepend}${a.ordinal?`ordinal${this.options.prepend}`:""}${s.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,a))}}const He=(e,t,a,s=".",r=!0)=>{let n=((e,t,a)=>{const s=je(e,a);return void 0!==s?s:je(t,a)})(e,t,a);return!n&&r&&he(a)&&(n=Te(e,a,s),void 0===n&&(n=Te(t,a,s))),n},Ke=e=>e.replace(/\$/g,"$$$$");class Ge{constructor(e={}){this.logger=Re.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:s,prefix:r,prefixEscaped:n,suffix:i,suffixEscaped:o,formatSeparator:l,unescapeSuffix:d,unescapePrefix:c,nestingPrefix:u,nestingPrefixEscaped:m,nestingSuffix:p,nestingSuffixEscaped:h,nestingOptionsSeparator:f,maxReplaces:x,alwaysFormat:g}=e.interpolation;this.escape=void 0!==t?t:Se,this.escapeValue=void 0===a||a,this.useRawValueToEscape=void 0!==s&&s,this.prefix=r?ke(r):n||"{{",this.suffix=i?ke(i):o||"}}",this.formatSeparator=l||",",this.unescapePrefix=d?"":c||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=u?ke(u):m||ke("$t("),this.nestingSuffix=p?ke(p):h||ke(")"),this.nestingOptionsSeparator=f||",",this.maxReplaces=x||1e3,this.alwaysFormat=void 0!==g&&g,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,s){let r,n,i;const o=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},l=e=>{if(e.indexOf(this.formatSeparator)<0){const r=He(t,o,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(r,void 0,a,{...s,...t,interpolationkey:e}):r}const r=e.split(this.formatSeparator),n=r.shift().trim(),i=r.join(this.formatSeparator).trim();return this.format(He(t,o,n,this.options.keySeparator,this.options.ignoreJSONStructure),i,a,{...s,...t,interpolationkey:n})};this.resetRegExp();const d=s?.missingInterpolationHandler||this.options.missingInterpolationHandler,c=void 0!==s?.interpolation?.skipOnVariables?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>Ke(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?Ke(this.escape(e)):Ke(e)}].forEach(t=>{for(i=0;r=t.regex.exec(e);){const a=r[1].trim();if(n=l(a),void 0===n)if("function"==typeof d){const t=d(e,r,s);n=he(t)?t:""}else if(s&&Object.prototype.hasOwnProperty.call(s,a))n="";else{if(c){n=r[0];continue}this.logger.warn(`missed to pass in variable ${a} for interpolating ${e}`),n=""}else he(n)||this.useRawValueToEscape||(n=xe(n));const o=t.safeValue(n);if(e=e.replace(r[0],o),c?(t.regex.lastIndex+=n.length,t.regex.lastIndex-=r[0].length):t.regex.lastIndex=0,i++,i>=this.maxReplaces)break}}),e}nest(e,t,a={}){let s,r,n;const i=(e,t)=>{const a=this.nestingOptionsSeparator;if(e.indexOf(a)<0)return e;const s=e.split(new RegExp(`${a}[ ]*{`));let r=`{${s[1]}`;e=s[0],r=this.interpolate(r,n);const i=r.match(/'/g),o=r.match(/"/g);((i?.length??0)%2==0&&!o||o.length%2!=0)&&(r=r.replace(/'/g,'"'));try{n=JSON.parse(r),t&&(n={...t,...n})}catch(l){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,l),`${e}${a}${r}`}return n.defaultValue&&n.defaultValue.indexOf(this.prefix)>-1&&delete n.defaultValue,e};for(;s=this.nestingRegexp.exec(e);){let o=[];n={...a},n=n.replace&&!he(n.replace)?n.replace:n,n.applyPostProcessor=!1,delete n.defaultValue;const l=/{.*}/.test(s[1])?s[1].lastIndexOf("}")+1:s[1].indexOf(this.formatSeparator);if(-1!==l&&(o=s[1].slice(l).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),s[1]=s[1].slice(0,l)),r=t(i.call(this,s[1].trim(),n),n),r&&s[0]===e&&!he(r))return r;he(r)||(r=xe(r)),r||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${e}`),r=""),o.length&&(r=o.reduce((e,t)=>this.format(e,t,a.lng,{...a,interpolationkey:s[1].trim()}),r.trim())),e=e.replace(s[0],r),this.regexp.lastIndex=0}return e}}const Qe=e=>{const t={};return(a,s,r)=>{let n=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(n={...n,[r.interpolationkey]:void 0});const i=s+JSON.stringify(n);let o=t[i];return o||(o=e(Ae(s),r),t[i]=o),o(a)}},Xe=e=>(t,a,s)=>e(Ae(a),s)(t);class Je{constructor(e={}){this.logger=Re.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const a=t.cacheInBuiltFormats?Qe:Xe;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()]=Qe(t)}format(e,t,a,s={}){const r=t.split(this.formatSeparator);if(r.length>1&&r[0].indexOf("(")>1&&r[0].indexOf(")")<0&&r.find(e=>e.indexOf(")")>-1)){const e=r.findIndex(e=>e.indexOf(")")>-1);r[0]=[r[0],...r.splice(1,e)].join(this.formatSeparator)}return r.reduce((e,t)=>{const{formatName:r,formatOptions:n}=(e=>{let t=e.toLowerCase().trim();const a={};if(e.indexOf("(")>-1){const s=e.split("(");t=s[0].toLowerCase().trim();const r=s[1].substring(0,s[1].length-1);"currency"===t&&r.indexOf(":")<0?a.currency||(a.currency=r.trim()):"relativetime"===t&&r.indexOf(":")<0?a.range||(a.range=r.trim()):r.split(";").forEach(e=>{if(e){const[t,...s]=e.split(":"),r=s.join(":").trim().replace(/^'+|'+$/g,""),n=t.trim();a[n]||(a[n]=r),"false"===r&&(a[n]=!1),"true"===r&&(a[n]=!0),isNaN(r)||(a[n]=parseInt(r,10))}})}return{formatName:t,formatOptions:a}})(t);if(this.formats[r]){let t=e;try{const i=s?.formatParams?.[s.interpolationkey]||{},o=i.locale||i.lng||s.locale||s.lng||a;t=this.formats[r](e,o,{...n,...s,...i})}catch(i){this.logger.warn(i)}return t}return this.logger.warn(`there was no format function for ${r}`),e},e)}}class Ye extends Le{constructor(e,t,a,s={}){super(),this.backend=e,this.store=t,this.services=a,this.languageUtils=a.languageUtils,this.options=s,this.logger=Re.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(a,s.backend,s)}queueLoad(e,t,a,s){const r={},n={},i={},o={};return e.forEach(e=>{let s=!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,s=!1,void 0===n[i]&&(n[i]=!0),void 0===r[i]&&(r[i]=!0),void 0===o[t]&&(o[t]=!0)))}),s||(i[e]=!0)}),(Object.keys(r).length||Object.keys(n).length)&&this.queue.push({pending:n,pendingCount:Object.keys(n).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(r),pending:Object.keys(n),toLoadLanguages:Object.keys(i),toLoadNamespaces:Object.keys(o)}}loaded(e,t,a){const s=e.split("|"),r=s[0],n=s[1];t&&this.emit("failedLoading",r,n,t),!t&&a&&this.store.addResourceBundle(r,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:s,k:r}=ye(e,t,Object);s[r]=s[r]||[],s[r].push(a)})(a.loaded,[r],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,s=0,r=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:s,wait:r,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&&s<this.maxRetries?setTimeout(()=>{this.read.call(this,e,t,a,s+1,2*r,n)},r):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={},s){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();he(e)&&(e=this.languageUtils.toResolveHierarchy(e)),he(t)&&(t=[t]);const r=this.queueLoad(e,t,a,s);if(!r.toLoad.length)return r.pending.length||s(),null;r.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("|"),s=a[0],r=a[1];this.read(s,r,"read",void 0,void 0,(a,n)=>{a&&this.logger.warn(`${t}loading namespace ${r} for language ${s} failed`,a),!a&&n&&this.logger.log(`${t}loaded namespace ${r} for language ${s}`,n),this.loaded(e,a,n)})}saveMissing(e,t,a,s,r,n={},i=()=>{}){if(!this.services?.utils?.hasLoadedNamespace||this.services?.utils?.hasLoadedNamespace(t)){if(null!=a&&""!==a){if(this.backend?.create){const l={...n,isUpdate:r},d=this.backend.create.bind(this.backend);if(d.length<6)try{let r;r=5===d.length?d(e,t,a,s,l):d(e,t,a,s),r&&"function"==typeof r.then?r.then(e=>i(null,e)).catch(i):i(null,r)}catch(o){i(o)}else d(e,t,a,s,i,l)}e&&e[0]&&this.store.addResource(e[0],t,a,s)}}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 Ze=()=>({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]),he(e[1])&&(t.defaultValue=e[1]),he(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}),et=e=>(he(e.ns)&&(e.ns=[e.ns]),he(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),he(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),tt=()=>{};class at extends Le{constructor(e={},t){var a;if(super(),this.options=et(e),this.services={},this.logger=Re,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&&(he(e.ns)?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const a=Ze();this.options={...a,...this.options,...et(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 s=e=>e?"function"==typeof e?new e:e:null;if(!this.options.isClone){let e;this.modules.logger?Re.init(s(this.modules.logger),this.options):Re.init(null,this.options),e=this.modules.formatter?this.modules.formatter:Je;const t=new Ve(this.options);this.store=new Me(this.options.resources,this.options);const r=this.services;r.logger=Re,r.resourceStore=this.store,r.languageUtils=t,r.pluralResolver=new We(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||(r.formatter=s(e),r.formatter.init&&r.formatter.init(r,this.options),this.options.interpolation.format=r.formatter.format.bind(r.formatter)),r.interpolator=new Ge(this.options),r.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},r.backendConnector=new Ye(s(this.modules.backend),r.resourceStore,r,this.options),r.backendConnector.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(r.languageDetector=s(this.modules.languageDetector),r.languageDetector.init&&r.languageDetector.init(r,this.options.detection,this.options)),this.modules.i18nFormat&&(r.i18nFormat=s(this.modules.i18nFormat),r.i18nFormat.init&&r.i18nFormat.init(this)),this.translator=new Ue(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=tt),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 r=fe(),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),r.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),r}loadResources(e,t=tt){let a=t;const s=he(e)?e:this.language;if("function"==typeof e&&(a=e),!this.options.resources||this.options.partialBundledLanguages){if("cimode"===s?.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(s)t(s);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 s=fe();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=tt),this.services.backendConnector.reload(e,t,e=>{s.resolve(),a(e)}),s}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&&Oe.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=fe();this.emit("languageChanging",e);const s=e=>{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},r=(r,n)=>{n?this.isLanguageChangingTo===e&&(s(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(r,(...e)=>this.t(...e))},n=t=>{e||t||!this.services.languageDetector||(t=[]);const a=he(t)?t:t&&t[0],n=this.store.hasLanguageSomeTranslations(a)?a:this.services.languageUtils.getBestMatchFromCodes(he(t)?[t]:t);n&&(this.language||s(n),this.translator.language||this.translator.changeLanguage(n),this.services.languageDetector?.cacheUserLanguage?.(n)),this.loadResources(n,e=>{r(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 s=(e,t,...r)=>{let n;n="object"!=typeof t?this.options.overloadTranslationOptionHandler([e,t].concat(r)):{...t},n.lng=n.lng||s.lng,n.lngs=n.lngs||s.lngs,n.ns=n.ns||s.ns,""!==n.keyPrefix&&(n.keyPrefix=n.keyPrefix||a||s.keyPrefix);const i=this.options.keySeparator||".";let o;return n.keyPrefix&&Array.isArray(e)?o=e.map(e=>("function"==typeof e&&(e=Fe(e,{...this.options,...t})),`${n.keyPrefix}${i}${e}`)):("function"==typeof e&&(e=Fe(e,{...this.options,...t})),o=n.keyPrefix?`${n.keyPrefix}${i}${e}`:e),this.t(o,n)};return he(e)?s.lng=e:s.lngs=e,s.ns=t,s.keyPrefix=a,s}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],s=!!this.options&&this.options.fallbackLng,r=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)||s&&!n(r,e)))}loadNamespaces(e,t){const a=fe();return this.options.ns?(he(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=fe();he(e)&&(e=[e]);const s=this.options.preload||[],r=e.filter(e=>s.indexOf(e)<0&&this.services.languageUtils.isSupportedCode(e));return r.length?(this.options.preload=s.concat(r),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 Ve(Ze());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 at(e,t);return a.createInstance=at.createInstance,a}cloneInstance(e={},t=tt){const a=e.forkResourceStore;a&&delete e.forkResourceStore;const s={...this.options,...e,isClone:!0},r=new at(s);void 0===e.debug&&void 0===e.prefix||(r.logger=r.logger.clone(e));if(["store","services","language"].forEach(e=>{r[e]=this[e]}),r.services={...this.services},r.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},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,s)=>(a[s]={...e[t][s]},a),e[t]),e),{});r.store=new Me(e,s),r.services.resourceStore=r.store}return r.translator=new Ue(r.services,s),r.translator.on("*",(e,...t)=>{r.emit(e,...t)}),r.init(s,t),r.translator.options=s,r.translator.backendConnector.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},r}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const st=at.createInstance();function rt(e,t){t?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{o.toast.info(st.t("link_copied"))})}function nt(...e){return n.twMerge(r.clsx(e))}st.createInstance,st.dir,st.init,st.loadResources,st.reloadResources,st.use,st.changeLanguage,st.getFixedT,st.t,st.exists,st.setDefaultNamespace,st.hasLoadedNamespace,st.loadNamespaces,st.loadLanguages;const it=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(it);if("object"==typeof e&&e.constructor===Object){const t={};for(const[a,s]of Object.entries(e))t[a]=it(s);return t}return e},ot=s.cva("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"}}),lt=B.forwardRef(({className:t,variant:s,size:r,asChild:n=!1,...i},o)=>{const l=n?a.Slot:"button";return e.jsx(l,{className:nt(ot({variant:s,size:r,className:t})),ref:o,...i})});lt.displayName="Button";const dt=t.forwardRef(({variant:t="default",className:a,children:s,...r},n)=>e.jsx(lt,{ref:n,variant:"action",size:"sm",className:nt("h-7 px-2 text-xs",a),...r,children:s||e.jsx(l.EllipsisVertical,{size:12})}));dt.displayName="ActionButton";const ct=B.forwardRef(({className:t,type:a,...s},r)=>e.jsx("input",{type:a,className:nt("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:r,...s}));ct.displayName="Input";const ut=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),mt=B.forwardRef(({className:t,...a},s)=>e.jsx(W.Root,{ref:s,className:nt(ut(),t),...a}));mt.displayName=W.Root.displayName;const pt=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("rounded-lg border bg-card text-card-foreground shadow-sm",t),...a}));pt.displayName="Card";const ht=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("flex flex-col space-y-1.5 p-6",t),...a}));ht.displayName="CardHeader";const ft=B.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:nt("text-2xl font-semibold leading-none tracking-tight",t),...a}));ft.displayName="CardTitle";const xt=B.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:nt("text-sm text-muted-foreground",t),...a}));xt.displayName="CardDescription";const gt=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("p-6 pt-0",t),...a}));gt.displayName="CardContent";const bt=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("flex items-center p-6 pt-0",t),...a}));bt.displayName="CardFooter";const vt=H.Root,yt=H.Trigger,Nt=H.Portal,jt=H.Close,wt=B.forwardRef(({className:t,...a},s)=>e.jsx(H.Overlay,{ref:s,className:nt("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}));wt.displayName=H.Overlay.displayName;const kt=B.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Nt,{children:[e.jsx(wt,{}),e.jsxs(H.Content,{ref:r,className:nt("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",t),...s,children:[a,e.jsxs(H.Close,{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 data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));kt.displayName=H.Content.displayName;const Ct=({className:t,...a})=>e.jsx("div",{className:nt("flex flex-col space-y-1.5 text-center sm:text-left",t),...a});Ct.displayName="DialogHeader";const St=({className:t,...a})=>e.jsx("div",{className:nt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});St.displayName="DialogFooter";const Pt=B.forwardRef(({className:t,...a},s)=>e.jsx(H.Title,{ref:s,className:nt("text-lg font-semibold leading-none tracking-tight",t),...a}));Pt.displayName=H.Title.displayName;const Et=B.forwardRef(({className:t,...a},s)=>e.jsx(H.Description,{ref:s,className:nt("text-sm text-muted-foreground",t),...a}));Et.displayName=H.Description.displayName;const Tt=u.FormProvider,At=B.createContext({}),_t=()=>{const e=B.useContext(At),t=B.useContext(It),{getFieldState:a,formState:s}=u.useFormContext(),r=a(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=t;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},It=B.createContext({}),Rt=B.forwardRef(({className:t,...a},s)=>{const r=B.useId();return e.jsx(It.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:nt("space-y-2",t),...a})})});Rt.displayName="FormItem";const Lt=B.forwardRef(({className:t,...a},s)=>{const{error:r,formItemId:n}=_t();return e.jsx(mt,{ref:s,className:nt(r&&"text-destructive",t),htmlFor:n,...a})});Lt.displayName="FormLabel";const Mt=B.forwardRef(({...t},s)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=_t();return e.jsx(a.Slot,{ref:s,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...t})});Mt.displayName="FormControl";const Ot=B.forwardRef(({className:t,...a},s)=>{const{formDescriptionId:r}=_t();return e.jsx("p",{ref:s,id:r,className:nt("text-sm text-muted-foreground",t),...a})});Ot.displayName="FormDescription";const Dt=B.forwardRef(({className:t,children:a,...s},r)=>{const{error:n,formMessageId:i}=_t(),o=n?String(n?.message):a;return o?e.jsx("p",{ref:r,id:i,className:nt("text-sm font-medium text-destructive",t),...s,children:o}):null});Dt.displayName="FormMessage";const Ft=K.Root,zt=K.Group,$t=K.Value,Ut=B.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(K.Trigger,{ref:r,className:nt("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",t),...s,children:[a,e.jsx(K.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ut.displayName=K.Trigger.displayName;const Vt=B.forwardRef(({className:t,...a},s)=>e.jsx(K.ScrollUpButton,{ref:s,className:nt("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));Vt.displayName=K.ScrollUpButton.displayName;const qt=B.forwardRef(({className:t,...a},s)=>e.jsx(K.ScrollDownButton,{ref:s,className:nt("flex cursor-default items-center justify-center py-1",t),...a,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));qt.displayName=K.ScrollDownButton.displayName;const Bt=B.forwardRef(({className:t,children:a,position:s="popper",container:r,collisionBoundary:n,...i},o)=>e.jsx(K.Portal,{container:r,children:e.jsxs(K.Content,{ref:o,className:nt("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",t),position:s,collisionBoundary:n,...i,children:[e.jsx(Vt,{}),e.jsx(K.Viewport,{className:nt("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:a}),e.jsx(qt,{})]})}));Bt.displayName=K.Content.displayName;const Wt=B.forwardRef(({className:t,...a},s)=>e.jsx(K.Label,{ref:s,className:nt("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...a}));Wt.displayName=K.Label.displayName;const Ht=B.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(K.Item,{ref:r,className:nt("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",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(K.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),e.jsx(K.ItemText,{children:a})]}));Ht.displayName=K.Item.displayName;const Kt=B.forwardRef(({className:t,...a},s)=>e.jsx(K.Separator,{ref:s,className:nt("-mx-1 my-1 h-px bg-muted",t),...a}));Kt.displayName=K.Separator.displayName;const Gt=B.forwardRef(({className:t,...a},s)=>e.jsx(G.Root,{ref:s,className:nt("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.jsx(G.Indicator,{className:nt("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));Gt.displayName=G.Root.displayName;const Qt=B.forwardRef(({className:t,...a},s)=>e.jsx("textarea",{className:nt("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:s,...a}));Qt.displayName="Textarea";const Xt=s.cva("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"}}),Jt=B.forwardRef(({className:t,variant:a,...s},r)=>e.jsx("div",{ref:r,className:nt(Xt({variant:a}),t),...s}));Jt.displayName="Badge";const Yt={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Zt({size:t="md",className:a}){return e.jsx(l.Loader2,{className:nt("animate-spin text-muted-foreground",Yt[t],a)})}let ea=0;const ta=new Map,aa=e=>{if(ta.has(e))return;const t=setTimeout(()=>{ta.delete(e),ia({type:"REMOVE_TOAST",toastId:e})},1e6);ta.set(e,t)},sa=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{const{toastId:a}=t;return a?aa(a):e.toasts.forEach(e=>{aa(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===a||void 0===a?{...e,open:!1}:e)}}case"REMOVE_TOAST":return void 0===t.toastId?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},ra=[];let na={toasts:[]};function ia(e){na=sa(na,e),ra.forEach(e=>{e(na)})}function oa({...e}){const t=(ea=(ea+1)%Number.MAX_SAFE_INTEGER,ea.toString()),a=()=>ia({type:"DISMISS_TOAST",toastId:t});return ia({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||a()}}}),{id:t,dismiss:a,update:e=>ia({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function la(){const[e,t]=B.useState(na);return B.useEffect(()=>(ra.push(t),()=>{const e=ra.indexOf(t);e>-1&&ra.splice(e,1)}),[e]),{...e,toast:oa,dismiss:e=>ia({type:"DISMISS_TOAST",toastId:e})}}const da=Q.Provider,ca=B.forwardRef(({className:t,...a},s)=>e.jsx(Q.Viewport,{ref:s,className:nt("fixed top-4 left-1/2 transform -translate-x-1/2 z-[100] flex max-h-screen w-full max-w-[420px] flex-col p-4",t),...a}));ca.displayName=Q.Viewport.displayName;const ua=s.cva("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),ma=B.forwardRef(({className:t,variant:a,...s},r)=>e.jsx(Q.Root,{ref:r,className:nt(ua({variant:a}),t),...s}));ma.displayName=Q.Root.displayName;const pa=B.forwardRef(({className:t,...a},s)=>e.jsx(Q.Action,{ref:s,className:nt("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",t),...a}));pa.displayName=Q.Action.displayName;const ha=B.forwardRef(({className:t,...a},s)=>e.jsx(Q.Close,{ref:s,className:nt("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...a,children:e.jsx(l.X,{className:"h-4 w-4"})}));ha.displayName=Q.Close.displayName;const fa=B.forwardRef(({className:t,...a},s)=>e.jsx(Q.Title,{ref:s,className:nt("text-sm font-semibold",t),...a}));fa.displayName=Q.Title.displayName;const xa=B.forwardRef(({className:t,...a},s)=>e.jsx(Q.Description,{ref:s,className:nt("text-sm opacity-90",t),...a}));xa.displayName=Q.Description.displayName;const ga=X.Root,ba=X.Trigger,va=B.forwardRef(({className:t,align:a="center",sideOffset:s=4,container:r,...n},i)=>e.jsx(X.Portal,{container:r,children:e.jsx(X.Content,{ref:i,align:a,sideOffset:s,className:nt("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})}));va.displayName=X.Content.displayName;const ya=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...a}));ya.displayName="Command";const Na=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:nt("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})}));Na.displayName="CommandInput";const ja=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...a}));ja.displayName="CommandList";const wa=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("py-6 text-center text-sm text-muted-foreground",t),...a}));wa.displayName="CommandEmpty";const ka=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("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}));ka.displayName="CommandGroup";const Ca=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("-mx-1 h-px bg-border",t),...a}));Ca.displayName="CommandSeparator";const Sa=B.forwardRef(({className:t,disabled:a,onSelect:s,value:r,...n},i)=>e.jsx("div",{ref:i,className:nt("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&&s?.(r||""),...n}));Sa.displayName="CommandItem";const Pa=({className:t,...a})=>e.jsx("span",{className:nt("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});function Ea({className:t,...a}){return e.jsx("div",{className:nt("animate-pulse rounded-md bg-muted",t),...a})}Pa.displayName="CommandShortcut";const Ta={},Aa=(e,t,a,s)=>{La(a)&&Ta[a]||(La(a)&&(Ta[a]=new Date),((e,t,a,s)=>{const r=[a,{code:t,...s||{}}];if(e?.services?.logger?.forward)return e.services.logger.forward(r,"warn","react-i18next::",!0);La(r[0])&&(r[0]=`react-i18next:: ${r[0]}`),e?.services?.logger?.warn?e.services.logger.warn(...r):console})(e,t,a,s))},_a=(e,t)=>()=>{if(e.isInitialized)t();else{const a=()=>{setTimeout(()=>{e.off("initialized",a)},0),t()};e.on("initialized",a)}},Ia=(e,t,a)=>{e.loadNamespaces(t,_a(e,a))},Ra=(e,t,a,s)=>{if(La(a)&&(a=[a]),e.options.preload&&e.options.preload.indexOf(t)>-1)return Ia(e,a,s);a.forEach(t=>{e.options.ns.indexOf(t)<0&&e.options.ns.push(t)}),e.loadLanguages(t,_a(e,s))},La=e=>"string"==typeof e,Ma=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Oa={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},Da=e=>Oa[e];let Fa={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:e=>e.replace(Ma,Da)};let za;const $a={type:"3rdParty",init(e){((e={})=>{Fa={...Fa,...e}})(e.options.react),(e=>{za=e})(e)}},Ua=t.createContext();class Va{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(e=>{this.usedNamespaces[e]||(this.usedNamespaces[e]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}var qa,Ba={exports:{}},Wa={};var Ha,Ka,Ga={};
2
2
  /**
3
3
  * @license React
4
4
  * use-sync-external-store-shim.development.js
@@ -7,4 +7,4 @@
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 Ha=(Ba||(Ba=1,"production"===process.env.NODE_ENV?Ua.exports=function(){if($a)return Va;$a=1;var e=t,a="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},s=e.useState,r=e.useEffect,n=e.useLayoutEffect,i=e.useDebugValue;function o(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!a(e,s)}catch(r){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 a=t(),l=s({inst:{value:a,getSnapshot:t}}),c=l[0].inst,d=l[1];return n(function(){c.value=a,c.getSnapshot=t,o(c)&&d({inst:c})},[e,a,t]),r(function(){return o(c)&&d({inst:c}),e(function(){o(c)&&d({inst:c})})},[e]),i(a),a};return Va.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:l,Va}():Ua.exports=(qa||(qa=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var a=t();return!s(e,a)}catch(r){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var a=t,s="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=a.useState,n=a.useEffect,i=a.useLayoutEffect,o=a.useDebugValue,l=!1,c=!1,d="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,d){l||void 0===a.startTransition||(l=!0);var u=d();if(!c){var m=d();s(u,m)||(c=!0)}var p=(m=r({inst:{value:u,getSnapshot:d}}))[0].inst,h=m[1];return i(function(){p.value=u,p.getSnapshot=d,e(p)&&h({inst:p})},[t,u,d]),n(function(){return e(p)&&h({inst:p}),t(function(){e(p)&&h({inst:p})})},[t]),o(u),u};Wa.useSyncExternalStore=void 0!==a.useSyncExternalStore?a.useSyncExternalStore:d,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Wa)),Ua.exports);const Ka={t:(e,t)=>{return _a(t)?t:"object"==typeof(a=t)&&null!==a&&_a(t.defaultValue)?t.defaultValue:Array.isArray(e)?e[e.length-1]:e;var a},ready:!1},Qa=()=>()=>{},Ga=(e,a={})=>{const{i18n:s}=a,{i18n:r,defaultNS:n}=t.useContext(Ma)||{},i=s||r||Fa;i&&!i.reportNamespaces&&(i.reportNamespaces=new za),i||Pa(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=t.useMemo(()=>({...Oa,...i?.options?.react,...a}),[i,a]),{useSuspense:l,keyPrefix:c}=o,d=e||n||i?.options?.defaultNS,u=_a(d)?[d]:d||["translation"],m=t.useMemo(()=>u,u);i?.reportNamespaces?.addUsedNamespaces?.(m);const p=t.useRef(0),h=t.useCallback(e=>{if(!i)return Qa;const{bindI18n:t,bindI18nStore:a}=o,s=()=>{p.current+=1,e()};return t&&i.on(t,s),a&&i.store.on(a,s),()=>{t&&t.split(" ").forEach(e=>i.off(e,s)),a&&a.split(" ").forEach(e=>i.store.off(e,s))}},[i,o]),f=t.useRef(),g=t.useCallback(()=>{if(!i)return Ka;const e=!(!i.isInitialized&&!i.initializedStoreOnce)&&m.every(e=>((e,t,a={})=>t.languages&&t.languages.length?t.hasLoadedNamespace(e,{lng:a.lng,precheck:(t,s)=>{if(a.bindI18n&&a.bindI18n.indexOf("languageChanging")>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!s(t.isLanguageChangingTo,e))return!1}}):(Pa(t,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:t.languages}),!0))(e,i,o)),t=a.lng||i.language,s=p.current,r=f.current;if(r&&r.ready===e&&r.lng===t&&r.keyPrefix===c&&r.revision===s)return r;const n={t:i.getFixedT(t,"fallback"===o.nsMode?m:m[0],c),ready:e,lng:t,keyPrefix:c,revision:s};return f.current=n,n},[i,m,c,o,a.lng]),[x,b]=t.useState(0),{t:v,ready:y}=Ha.useSyncExternalStore(h,g,g);t.useEffect(()=>{if(i&&!y&&!l){const e=()=>b(e=>e+1);a.lng?Aa(i,a.lng,m,e):Ta(i,m,e)}},[i,a.lng,m,y,l,x]);const N=i||{},j=t.useRef(null),w=t.useRef(),k=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(s){}return a},S=t.useMemo(()=>{const e=N,t=e?.language;let a=e;e&&(j.current&&j.current.__original===e?w.current!==t?(a=k(e),j.current=a,w.current=t):a=j.current:(a=k(e),j.current=a,w.current=t));const s=[v,a,y];return s.t=v,s.i18n=a,s.ready=y,s},[v,N,y,N.resolvedLanguage,N.language,N.languages]);if(i&&l&&!y)throw new Promise(e=>{const t=()=>e();a.lng?Aa(i,a.lng,m,t):Ta(i,m,t)});return S};const Xa=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ja({multiple:a,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:c,label:d,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:f,className:g,sortOptions:x,maxDisplayedBadges:b,popoverContainer:v,onOpen:y,onClose:N}){const{t:j}=Ga(),[w,k]=t.useState(!1),[S,C]=t.useState(""),P=t.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=t.useMemo(()=>{if(!v)return;let e=v,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),s=a.overflowY||a.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,t++}}catch{}return e??void 0},[v]),T=t.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return x?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,x]),A=t.useMemo(()=>{if(!S)return T;const e=Xa(S);return T.filter(t=>Xa(t.label).includes(e))},[T,S]),_=t.useMemo(()=>T.filter(e=>P.includes(e.value)),[T,P]),I=(e,t)=>{t.preventDefault(),t.stopPropagation(),n&&n(a?P.filter(t=>t!==e):"")},R=b?_.slice(0,b):_,L=b&&_.length>b?_.length-b:0;return e.jsxs("div",{className:at("space-y-2",g),children:[d&&e.jsxs(ct,{children:[d,f&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(ha,{open:w,onOpenChange:e=>{k(e),e?y?.():(C(""),N?.())},modal:!1,children:[e.jsx(fa,{asChild:!0,children:e.jsxs(nt,{variant:"outline",role:"combobox","aria-expanded":w,disabled:h,className:at("w-full justify-between min-h-10 h-auto",0===_.length&&"text-muted-foreground"),children:[0===_.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),c]}):a?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[R.map(t=>e.jsxs(Qt,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e.jsx("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&&I(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>I(t.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),L>0&&e.jsxs(Qt,{variant:"outline",className:"gap-1",children:["+",L]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),_[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(ga,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(xa,{children:[e.jsx(ba,{placeholder:p,value:S,onChange:e=>C(e.target.value)}),e.jsx(va,{children:0===s.length?e.jsx(ya,{children:m}):0===A.length?e.jsx(ya,{children:j("no_results")}):e.jsx(Na,{children:A.map(t=>e.jsxs(wa,{value:t.value,onSelect:()=>(e=>{if(n)if(a){const t=P.includes(e)?P.filter(t=>t!==e):[...P,e];n(t)}else n(e),k(!1)})(t.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:at("mr-2 h-4 w-4",P.includes(t.value)?"opacity-100":"opacity-0")}),t.label]},t.value))})})]})})]})]})}function Ya({multiple:t=!1,options:a,items:s,value:r,onChange:n,onValueChange:i,getOptionValue:o=e=>e.value,getOptionLabel:c=e=>e.label,placeholder:d,label:u,icon:m,emptyMessage:p,searchPlaceholder:h,disabled:f=!1,required:g=!1,isLoading:x=!1,error:b,className:v,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:j,onOpen:w,onClose:k}){const{t:S}=Ga(),C=s||a||[],P=i||n,E=d||S("select_placeholder"),T=p||S("no_results"),A=h||S("search_placeholder");if(x)return e.jsxs("div",{className:at("space-y-2",v),children:[u&&e.jsxs(ct,{children:[u,g&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Sa,{className:"h-10 w-full"})]});const _="string"==typeof b?b:b instanceof Error?b.message:b?"Erro ao carregar dados":void 0;return _?e.jsxs("div",{className:at("space-y-2",v),children:[u&&e.jsxs(ct,{children:[u,g&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:_})]})]}):e.jsx(Ja,{multiple:t,options:C,value:r||(t?[]:""),onChange:P,getOptionValue:o,getOptionLabel:c,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:A,disabled:f,required:g,className:v,sortOptions:y,maxDisplayedBadges:N,popoverContainer:j,onOpen:w,onClose:k})}var Za=Object.defineProperty;class es{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 r=e.split(".");if(3!==r.length)return null;const n=r[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),t=atob(e),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);const s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}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(s){throw s}}}}catch(r){return null}}static validateTokens(e,t){const a=[],s=[];try{t.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(t),n=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}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(r.exp&&r.exp<o){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:a,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:a,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}}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?Za(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a})(es,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const ts="qualiex_access_token",as="qualiex_id_token",ss="supabase_token",rs="oauth_state",ns="oauth_nonce",is="selected_alias",os="manual_logout",ls={setAccessToken:e=>localStorage.setItem(ts,e),getAccessToken:()=>localStorage.getItem(ts),setIdToken:e=>localStorage.setItem(as,e),getIdToken:()=>localStorage.getItem(as),getSupabaseToken:()=>localStorage.getItem(ss),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(is,e),getSelectedAlias:()=>localStorage.getItem(is),clearSelectedAlias:()=>localStorage.removeItem(is),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!ls.getAccessToken()||!ls.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(ss,e),ls._clearValidationCache()},areAllTokensValid:()=>{const e=ls.getAccessToken(),t=ls.getIdToken();if(!e||!t)return!1;try{const a=es.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=ls.getAccessToken(),a=ls.getIdToken(),s=ls.getSupabaseToken();return t&&ls.isTokenExpired(t)&&(localStorage.removeItem(ts),e=!0),a&&ls.isTokenExpired(a)&&(localStorage.removeItem(as),e=!0),s&&ls.isTokenExpired(s)&&(localStorage.removeItem(ss),e=!0),e},clearAll:()=>{localStorage.removeItem(ts),localStorage.removeItem(as),localStorage.removeItem(ss),localStorage.removeItem(is),localStorage.removeItem(os),sessionStorage.removeItem(rs),sessionStorage.removeItem(ns)},setManualLogout:()=>localStorage.setItem(os,"true"),isManualLogout:()=>"true"===localStorage.getItem(os),clearManualLogout:()=>localStorage.removeItem(os),isTokenExpired:e=>{try{return es.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{ls._validationCache.isValid=!1,ls._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=ls.getSupabaseToken();if(!e)return!1;if(ls.isTokenExpired(e))return ls._clearValidationCache(),ls._handleExpiredToken(),!1;const t=Date.now();return t-ls._validationCache.timestamp<ls._validationCache.cacheValidityMs?ls._validationCache.isValid:(ls._validationCache.isValid=!0,ls._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>ls.isSupabaseTokenValid()?ls.getSupabaseToken():null,_handleExpiredToken:()=>{ls.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!ls.isSupabaseTokenValid())return null;const e=ls.getSupabaseToken();if(!e)return null;try{const t=es.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,s=t.place_id||null,r=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 s=t[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===a){n=e[7];break}}}return{alias:a,companyId:n,placeId:s,placeName:r,payload:t}}catch(t){return ls._handleExpiredToken(),null}},getCompanyId:e=>{const t=ls.getAccessToken();if(t)try{const a=es.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}const a=ls.extractTokenData();if(a?.companyId)return a.companyId;const s=ls.getIdToken();if(s)try{const t=es.parseJwtPayload(s);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}return null},getCurrentCompanyId:()=>{const e=ls.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=ls.getIdToken();if(!e)return[];try{const t=es.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.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 cs=Object.defineProperty,ds=(e,t,a)=>((e,t,a)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const us=new class{constructor(){ds(this,"errors",[]),ds(this,"toastCount",0),ds(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()){ra({title:this.getErrorTitle(a),description:a,variant:"destructive"})}}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){ra({title:e,description:t,variant:"default"})}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 ms=Object.defineProperty,ps=(e,t,a)=>((e,t,a)=>t in e?ms(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const hs=(void 0).VITE_SUPABASE_URL,fs=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY,gs=class e{constructor(){ps(this,"client"),ps(this,"currentToken",null),ps(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:fs};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return g.createClient(hs,fs,{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=ls.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 us.handleError(t instanceof Error?t:"❌ Supabase - Error validating token",!1),!1}}};ps(gs,"instance");let xs=gs;function bs(){return xs.getInstance().getClient()}class vs{static async generateToken(e,t,a,s=!1){try{if(!s){const e=ls.getSupabaseToken();if(e&&ls.isSupabaseTokenValid())return e}const r=bs(),{data:n,error:i}=await r.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?(ls.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&a?.(),null}}}var ys=Object.defineProperty,Ns=(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 js{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=ls.getAccessToken(),t=ls.getSelectedAlias();if(!e||!t)return null;const a=await vs.generateToken(e,t,this.onLogoutCallback||void 0,!1);return a?(ls.setSupabaseToken(a),a):null}catch(e){return null}finally{this.isRegenerating=!1}}}Ns(js,"isRegenerating",!1),Ns(js,"onLogoutCallback",null);class ws{static handleError(e){if(!e)return!1;const t=e.message||e.toString();return!!this.isAuthenticationError(e,t)&&(ls.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 Ss{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 js.attemptRegeneration()?(this.isRetrying=!1,!0):(ws.handleError(e),this.isRetrying=!1,!1)}catch(s){return ws.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=ls.getAccessToken();return e?ls.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)})(Ss,"isRetrying",!1);var Cs=Object.defineProperty,Ps=(e,t,a)=>((e,t,a)=>t in e?Cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const Es=new class{constructor(){Ps(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const s=Ss.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=ls.getAccessToken();if(!r)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 ${r}`,"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){const t=e.status||e.userStatus||"",a=void 0!==e.isActive?e.isActive:"active"===t.toLowerCase()||"ACTIVE"===t.toUpperCase();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,isActive:a,status:t||void 0}}async fetchUsers(e,t){try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return us.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];s=a}if(!Array.isArray(s))return us.handleError("[QualiexApi] Resposta não é um array",!1),[];return s.map(this.mapToQualiexUser)}catch(a){if(await Ss.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return us.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];s=a}return Array.isArray(s)?s.map(this.mapToQualiexUser):(us.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(s){return us.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}const r=a instanceof Error?a.message:"Erro ao buscar usuários da API Qualiex";return us.handleError(r,!0),[]}}async fetchUserById(e,t,a){try{return(await this.fetchUsers(t,a)).find(t=>t.userId===e)||null}catch(s){return us.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,t){const a=await this.fetchUsers(e,t),s=new Map;return a.forEach(e=>{s.set(e.userId,e)}),s}async fetchAllUsers(e,t){try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"all"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return us.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];s=a}return Array.isArray(s)?s.map(this.mapToQualiexUser):(us.handleError("[QualiexApi] Resposta não é um array",!1),[])}catch(a){if(await Ss.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"all"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return us.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];s=a}return Array.isArray(s)?s.map(this.mapToQualiexUser):(us.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(s){return us.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}return us.handleError(a instanceof Error?a.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async getUsers(e){const t=ls.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId):[]}async getAllUsers(e){const t=ls.extractTokenData();return t&&t.companyId?this.fetchAllUsers(e,t.companyId):[]}},Ts={oauth:{authUrl:(void 0).VITE_OAUTH_AUTH_URL,clientId:(void 0).VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},As={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},_s={debounceDelay:500},Is=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||(void 0).DEV},Rs={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Ls=()=>Rs,Os={isQualiex:"true"===(void 0).VITE_IS_QUALIEX},Fs={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 Ds(e,t){const a=Ls(),s=t||a.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function Ms(e,t){const a=Ls(),s=t||a.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function zs(e,t){const a=Ls(),s=t||a.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function $s(e,t){return t&&t.length>0?t.map(e=>({idField:e.idField,nameField:e.nameField||Ds(e.idField),emailField:e.emailField||Ms(e.idField),usernameField:e.usernameField||zs(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Ds(e),emailField:Ms(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}`,s=Us.get(a);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await Es.fetchUsers(e,t);return Us.set(a,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,t){const a=new Set;for(const s of e)for(const e of t){const t=s[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 s={...e};for(const r of t){const t=e[r.idField];if(!t)continue;const n=a.get(t);if(n){if(r.nameField){s[r.nameField]||(s[r.nameField]=n.userName||n.displayName||null)}if(r.emailField){s[r.emailField]||(s[r.emailField]=n.userEmail||null)}if(r.usernameField){s[r.usernameField]||(s[r.usernameField]=n.userName||null)}}}return s}static async enrichWithUserData(e,t){if(!Array.isArray(e)||0===e.length)return e;try{const a=ls.extractTokenData();if(!a)return e;const{alias:s,companyId:r}=a;if(!s||!r)return e;const n=$s(t.userIdFields,t.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const i=await this.fetchQualiexUsers(s,r),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,n,o))}catch(a){return us.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 qs=["responsible_name"],Bs=e=>qs.includes(e);function Ws(e,t,a){const s="string"==typeof e?{tableName:e,searchFields:t||[],schemaName:a||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:c=!1}=s,d=()=>{if(!ls.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return bs().schema(o).from(r)},u=(e,t,a,s)=>{let r=d().select(i||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,t])=>{void 0!==t&&""!==t&&(Array.isArray(t)?r=r.in(e,t):"object"==typeof t&&t&&"operator"in t?"not_null"===t.operator?r=r.not(e,"is",null):"is_null"===t.operator&&(r=r.is(e,null)):null!==t&&(r=r.eq(e,t)))}),r=((e,t)=>{if(t&&n.length>0){const a=n.map(e=>`${e}.ilike.%${t}%`).join(",");return e.or(a)}return e})(r,e);const o=t.includes(".");return o||Bs(t)||(r=r.order(t,{ascending:"asc"===a})),{query:r,isForeignKey:o}},m=async(e,t,a,r,n)=>{const i=$s(s.userIdFields,s.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:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let d;d=o?c.sort((e,s)=>{const r=t.split(".").reduce((e,t)=>e?.[t],e)||"",n=t.split(".").reduce((e,t)=>e?.[t],s)||"",i=String(r).localeCompare(String(n),"pt-BR");return"asc"===a?i:-i}):((e,t,a)=>[...e].sort((e,s)=>{const r=e[t]||"",n=s[t]||"",i=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===a?i:-i}))(c,t,a);const u=((e,t=1,a=25)=>{const s=(t-1)*a,r=s+a,n=e.slice(s,r);return{data:n,pagination:{currentPage:t,totalPages:Math.ceil(e.length/a),totalItems:n.length,totalCount:e.length,itemsPerPage:a,hasNextPage:r<e.length,hasPreviousPage:t>1}}})(d,r,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 Vs.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping})};return{async getAll(e={}){const{search:t,sortField:a,sortDirection:n,page:i,limit:o,additionalFilters:d}=(e=>{const{search:t="",sortField:a="updated_at",sortDirection:s="desc",page:r=1,limit:n=25,...i}=e;return{search:t,sortField:a,sortDirection:s,page:r,limit:n,additionalFilters:i}})(e),{query:p}=u(t,a,n,d),h=((e,t,a)=>{const s=(t-1)*a,r=s+a-1;return e.range(s,r)})(p,i,o),{data:f,error:g,count:x}=await h;if(g)throw new Error(`Error fetching ${r}: ${g.message}`);let b=((e,t,a,s)=>{const r=Math.ceil((t||0)/s);return{data:e,currentPage:a,totalPages:r,totalItems:t||0,itemsPerPage:s,hasNextPage:a<r,hasPreviousPage:a>1}})(f||[],x,i,o);if((e=>{if(!c||!l||0===e.length)return!1;const t=$s(s.userIdFields,s.userFieldsMapping);return e.some(e=>t.some(t=>e[t.idField]))})(b.data)){const e=await m(b.data,a,n,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 ${r}: ${a.message}`);return t},async create(e){const t=st(e),a=Object.entries(t).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),{data:s,error:n}=await d().insert(a).select().single();if(n)throw new Error(`Error creating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from create ${r} operation`);return s},async update(e,t){const a={...st(t),updated_at:(new Date).toISOString()},{data:s,error:n}=await d().update(a).eq("id",e).select().single();if(n)throw new Error(`Error updating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from update ${r} operation`);return s},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 ${r}: ${a.message}`)}}}const Hs=()=>{ls.clearManualLogout()},Ks=e=>e?.placeId||null,Qs=e=>e?.placeName||null,Gs=e=>({placeId:Ks(e),placeName:Qs(e)}),Xs=class{static async initialize(){try{if(!ls.hasAllTokens()||!ls.areAllTokensValid())return ls.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=ls.getAccessToken(),a=ls.getIdToken();Hs();const s=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(t),i=ls.extractTokenData(),o=i?.alias;let l=null;if(o&&r.some(e=>e.alias===o))l=o;else{const e=ls.getSelectedAlias(),t=e&&r.some(t=>t.alias===e);l=t?e:n||r[0]?.alias||null}!ls.isSupabaseTokenValid()&&l&&await js.attemptRegeneration();let c=null;if(l){const e=ls.getCompanyId(l),t=r.find(e=>e.alias===l);t&&(c={id:e||t.id,name:t.name,alias:t.alias})}let d=null,u=null;if(s?.id&&l){const t=ls.getCompanyId(l);if(t)try{const e=(await Es.fetchActiveUsersMap(l,t)).get(s.id);if(e){const t=Gs(e);d=t.placeId,u=t.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:s,alias:l,companies:r,selectedUnit:c,userId:s?.id||null,userAlias:s?.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=bs(),{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 s=new URL("/callback",window.location.origin);return s.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=ls.generateOAuthState();ls.setOAuthState(e);const t=ls.generateOAuthNonce();ls.setOAuthNonce(t);const a=`${window.location.origin}/callback`,s=new URL(Ts.oauth.authUrl);s.searchParams.set("client_id",Ts.oauth.clientId),s.searchParams.set("response_type",Ts.oauth.responseType),s.searchParams.set("scope",Ts.oauth.scope),s.searchParams.set("redirect_uri",a),s.searchParams.set("state",e),s.searchParams.set("nonce",t),s.searchParams.set("response_mode","fragment"),Is(),window.location.href=s.toString()}static async processCallback(){try{if(ls.hasAllTokens()){if(!ls.getValidSupabaseToken()){ls.getAccessToken();await js.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),s=a("access_token"),r=a("id_token"),n=a("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!s||!r)throw new Error("Tokens não encontrados na URL de callback");ls.setAccessToken(s),ls.setIdToken(r),Hs();const i=this.extractAliasFromAccessToken(s);if(i)ls.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(r);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");ls.setSelectedAlias(e[0].alias)}if(!await js.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return ls.clearOAuthState(),ls.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){ls.setManualLogout(),ls.clearAll(),window.location.href="/login"}static decodeToken(e){return es.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 s=t[e].split(";");if(s.length>=4)a.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=t[e].split("|");s&&r&&a.push({id:"",alias:s.trim(),name:r.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}};js.setLogoutCallback(()=>{Xs.logout()});let Js=Xs;const Ys=t.createContext(void 0),Zs=()=>{const e=t.useContext(Ys);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function er({queryKey:e,service:a,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:i}){const[l,c]=b.useSearchParams(),d=x.useQueryClient(),{alias:u,userId:m}=Zs(),p=t.useCallback(t=>{const a=`${e}_${t}`,s=l.get(a);return s||(l.get(t)||"")},[l,e]),h=p("search"),f=p("sortField")||As.sorting.defaultField,g=p("sortDirection")||As.sorting.defaultDirection,v=parseInt(p("page")||"1"),y=parseInt(p("limit")||String(As.pagination.defaultPageSize)),N=h,j=t.useMemo(()=>({search:N,sortField:f,sortDirection:g,page:v,limit:y,...n}),[N,f,g,v,y,n]),w=t.useCallback(()=>a.getAll(j),[a,j]),k=x.useQuery({queryKey:[e,u,m,j],queryFn:w});if(!k)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const S=x.useMutation({mutationFn:a.create,onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),o.toast.success(Fs.success.created(s)),i?.()},onError:e=>{o.toast.error(`${Fs.error.create(s)}: ${e.message}`)}}),C=x.useMutation({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),o.toast.success(Fs.success.updated(s)),i?.()},onError:e=>{o.toast.error(`${Fs.error.update(s)}: ${e.message}`)}}),P=x.useMutation({mutationFn:a.delete,onSuccess:()=>{d.invalidateQueries({queryKey:[e]}),o.toast.success(Fs.success.deleted(s))},onError:e=>{o.toast.error(`${Fs.error.delete(s)}: ${e.message}`)}}),E=t.useCallback(t=>{const a={...Object.fromEntries(l)};Object.entries(t).forEach(([t,s])=>{const r=`${e}_${t}`;""===s||0===s?delete a[r]:a[r]=String(s)}),delete a.sortField,delete a.sortDirection,c(a)},[l,c,e]),T=t.useCallback(e=>{E({search:e,page:1})},[E]),A=t.useCallback(e=>{E({sortField:e,sortDirection:f===e&&"asc"===g?"desc":"asc",page:1})},[f,g,E]),_=t.useCallback(e=>{E({page:e})},[E]),I=t.useCallback(e=>{E({limit:e,page:1})},[E]),R=t.useCallback(()=>{const t=Object.fromEntries(l),a=`${e}_`,s=Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith(a)));c(s)},[c,l,e]),[L,O]=t.useState([]),F=t.useCallback(e=>{O(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),D=t.useCallback(()=>{const e=k?.data?.data.map(e=>e.id)||[];O(t=>t.length===e.length?[]:e)},[k?.data?.data]),M=t.useCallback(()=>{O([])},[]),z=t.useMemo(()=>{const e=k?.data?.data.map(e=>e.id)||[];return e.length>0&&L.length===e.length},[L,k?.data?.data]),$=x.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(t,a)=>{d.invalidateQueries({queryKey:[e]}),o.toast.success(`${a.length} ${s}(s) deletado(s) com sucesso`),M()},onError:e=>{o.toast.error(`Erro ao deletar itens: ${e.message}`)}}),U=t.useCallback((e,t)=>{const a=t?t(e):e;e.id?C.mutate({id:e.id,data:a}):S.mutate({...a,alias:u})},[u,S,C]);return{entities:k?.data?.data||[],pagination:{data:k?.data?.data||[],currentPage:k?.data?.currentPage||1,totalPages:k?.data?.totalPages||1,totalItems:k?.data?.totalItems||0,itemsPerPage:k?.data?.itemsPerPage||As.pagination.defaultPageSize,hasNextPage:k?.data?.hasNextPage||!1,hasPreviousPage:k?.data?.hasPreviousPage||!1},isLoading:k?.isLoading??!0,isCreating:S?.isPending??!1,isUpdating:C?.isPending??!1,isDeleting:P?.isPending??!1,error:k?.error||null,searchTerm:h,sortField:f,sortDirection:g,currentPage:v,itemsPerPage:y,queryKey:e,createEntity:S.mutate,updateEntity:(e,t)=>C.mutate({id:e,data:t}),deleteEntity:P.mutate,save:U,handleSearch:T,handleSort:A,handlePageChange:_,handleItemsPerPageChange:I,clearFilters:R,refetch:k.refetch,selectedIds:L,selectItem:F,selectAll:D,clearSelection:M,isAllSelected:z,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}const tr=G.Root,ar=G.Trigger,sr=G.Portal,rr=V.forwardRef(({className:t,...a},s)=>e.jsx(G.Overlay,{className:at("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:s}));rr.displayName=G.Overlay.displayName;const nr=V.forwardRef(({className:t,...a},s)=>e.jsxs(sr,{children:[e.jsx(rr,{}),e.jsx(G.Content,{ref:s,className:at("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",t),...a})]}));nr.displayName=G.Content.displayName;const ir=({className:t,...a})=>e.jsx("div",{className:at("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});ir.displayName="AlertDialogHeader";const or=({className:t,...a})=>e.jsx("div",{className:at("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});or.displayName="AlertDialogFooter";const lr=V.forwardRef(({className:t,...a},s)=>e.jsx(G.Title,{ref:s,className:at("text-lg font-semibold",t),...a}));lr.displayName=G.Title.displayName;const cr=V.forwardRef(({className:t,...a},s)=>e.jsx(G.Description,{ref:s,className:at("text-sm text-muted-foreground",t),...a}));cr.displayName=G.Description.displayName;const dr=V.forwardRef(({className:t,...a},s)=>e.jsx(G.Action,{ref:s,className:at(rt(),t),...a}));dr.displayName=G.Action.displayName;const ur=V.forwardRef(({className:t,...a},s)=>e.jsx(G.Cancel,{ref:s,className:at(rt({variant:"outline"}),"mt-2 sm:mt-0",t),...a}));ur.displayName=G.Cancel.displayName;const mr=({open:t,onOpenChange:a,item:s,onConfirm:r,entityName:n="item",isDeleting:i=!1})=>{const{t:o}=Ga(),c=()=>{a(!1)};return s?e.jsx(tr,{open:t,onOpenChange:c,children:e.jsxs(nr,{className:"sm:max-w-[420px] bg-white",children:[e.jsxs("button",{onClick:c,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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Fechar"})]}),e.jsxs("div",{className:"flex flex-col items-center text-center space-y-3 py-2",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx(l.AlertTriangle,{className:"w-8 h-8 text-destructive"})}),e.jsx(lr,{className:"text-xl font-semibold",children:"Tem certeza?"}),e.jsx(cr,{asChild:!0,children:e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{children:"Você está prestes a excluir este registro."}),e.jsx("p",{children:"Esta ação não pode ser desfeita."})]})})]}),e.jsxs("div",{className:"flex flex-row gap-2 justify-center mt-6",children:[e.jsx(dr,{onClick:()=>{s&&(r(s),a(!1))},disabled:i,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:o(i?"deleting":"confirm_delete")}),e.jsx(ur,{onClick:c,className:"mt-0 border-none bg-transparent hover:bg-muted text-foreground shadow-none",children:"Cancelar"})]})]})}):null},pr=V.forwardRef(({className:t,...a},s)=>e.jsx("table",{ref:s,className:at("w-full caption-bottom text-sm",t),...a}));pr.displayName="Table";const hr=V.forwardRef(({className:t,...a},s)=>e.jsx("thead",{ref:s,className:at("[&_tr]:border-b sticky top-0 z-[1] bg-background",t),...a}));hr.displayName="TableHeader";const fr=V.forwardRef(({className:t,...a},s)=>e.jsx("tbody",{ref:s,className:at("[&_tr:last-child]:border-0",t),...a}));fr.displayName="TableBody";const gr=V.forwardRef(({className:t,...a},s)=>e.jsx("tfoot",{ref:s,className:at("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...a}));gr.displayName="TableFooter";const xr=V.forwardRef(({className:t,...a},s)=>e.jsx("tr",{ref:s,className:at("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",t),...a}));xr.displayName="TableRow";const br=V.forwardRef(({className:t,...a},s)=>e.jsx("th",{ref:s,className:at("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}));br.displayName="TableHead";const vr=V.forwardRef(({className:t,...a},s)=>e.jsx("td",{ref:s,className:at("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",t),...a}));vr.displayName="TableCell";const yr=V.forwardRef(({className:t,...a},s)=>e.jsx("caption",{ref:s,className:at("mt-4 text-sm text-muted-foreground",t),...a}));function Nr({rows:t=5,columns:a=4}){return e.jsx("div",{className:"w-full",children:e.jsxs("div",{className:"rounded-md border",children:[e.jsx("div",{className:"border-b bg-muted/50 px-4 py-3",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:a}).map((t,a)=>e.jsx(Sa,{className:"h-4 w-24"},a))})}),e.jsx("div",{children:Array.from({length:t}).map((t,s)=>e.jsx("div",{className:"border-b px-4 py-3 last:border-0",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:a}).map((t,a)=>e.jsx(Sa,{className:"h-4 w-20"},a))})},s))})]})})}function jr({count:t=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:t}).map((t,a)=>e.jsxs(dt,{children:[e.jsxs(ut,{children:[e.jsx(Sa,{className:"h-4 w-3/4"}),e.jsx(Sa,{className:"h-3 w-1/2"})]}),e.jsx(ht,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Sa,{className:"h-3 w-full"}),e.jsx(Sa,{className:"h-3 w-2/3"})]})})]},a))})}yr.displayName="TableCaption";const wr={default:l.FileX,search:l.Search,error:l.AlertCircle};function kr({icon:t,title:a,description:s,action:r,className:n,variant:i="default"}){const o=t?()=>t:wr[i];return e.jsxs("div",{className:at("flex flex-col items-center justify-center py-12 px-4 text-center",n),children:[e.jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e.jsx(o,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:a}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(nt,{onClick:r.onClick,variant:"outline",children:r.label})]})}const Sr=X.Root,Cr=X.Trigger,Pr=X.Group,Er=X.Portal,Tr=X.Sub,Ar=X.RadioGroup,_r=V.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(X.SubTrigger,{ref:n,className:at("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));_r.displayName=X.SubTrigger.displayName;const Ir=V.forwardRef(({className:t,...a},s)=>e.jsx(X.SubContent,{ref:s,className:at("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}));Ir.displayName=X.SubContent.displayName;const Rr=V.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(X.Portal,{children:e.jsx(X.Content,{ref:r,sideOffset:a,className:at("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-white 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),...s})}));Rr.displayName=X.Content.displayName;const Lr=V.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(X.Item,{ref:r,className:at("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),...s}));Lr.displayName=X.Item.displayName;const Or=V.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(X.CheckboxItem,{ref:n,className:at("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",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(X.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));Or.displayName=X.CheckboxItem.displayName;const Fr=V.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(X.RadioItem,{ref:r,className:at("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",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(X.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));Fr.displayName=X.RadioItem.displayName;const Dr=V.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(X.Label,{ref:r,className:at("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...s}));Dr.displayName=X.Label.displayName;const Mr=V.forwardRef(({className:t,...a},s)=>e.jsx(X.Separator,{ref:s,className:at("-mx-1 my-1 h-px bg-muted",t),...a}));Mr.displayName=X.Separator.displayName;const zr=({className:t,...a})=>e.jsx("span",{className:at("ml-auto text-xs tracking-widest opacity-60",t),...a});zr.displayName="DropdownMenuShortcut";const $r=({onEdit:t,onDelete:a,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:i=[],renderAs:o})=>{const{t:c}=Ga(),d=[];if(t){const e={icon:l.Edit,label:c("edit"),onClick:t};d.push(e)}if(i.forEach(e=>{d.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:c(r?"deactivate":"activate"),onClick:s};d.push(e)}if(n&&a){const e={icon:l.Trash2,label:c("delete"),onClick:a,destructive:!0};d.push(e)}return"dropdown"===o?e.jsx(e.Fragment,{children:d.map((t,a)=>e.jsxs(Lr,{onClick:t.onClick,className:t.destructive?"text-destructive":"",children:[e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},a))}):e.jsx(e.Fragment,{children:d.map((t,a)=>e.jsxs(nt,{variant:"ghost",size:"sm",onClick:t.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(t.destructive?"text-destructive hover:text-destructive":""),children:[e.jsx(t.icon,{className:"h-4 w-4 mr-2"}),t.label]},a))})},Ur=({onEdit:t,onDelete:a,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:i=[]})=>e.jsxs(Sr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(nt,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(Rr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:e.jsx($r,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:a?e=>{e?.stopPropagation(),a?.()}:void 0,onToggleStatus:r?e=>{e?.stopPropagation(),r?.()}:void 0,isActive:n,canDelete:s&&!!a,customActions:i,renderAs:"dropdown"})})]}),Vr=({contextMenu:a,onClose:s,onEdit:r,onDelete:n,onToggleStatus:i,customActions:o})=>(t.useEffect(()=>{const e=()=>s();if(a)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[a,s]),a?e.jsx("div",{className:"fixed bg-background border border-border rounded-md shadow-lg py-1 z-50 min-w-[120px]",style:{left:a.x,top:a.y},onClick:e=>e.stopPropagation(),children:e.jsx($r,{onEdit:r?()=>{r(a.item),s()}:void 0,onDelete:n?()=>{n(a.item),s()}:void 0,onToggleStatus:i?()=>{i(a.item),s()}:void 0,isActive:a.item.is_actived,canDelete:!!n,customActions:o?o(a.item):[],renderAs:"context"})}):null),qr=t.memo(({checked:t,onCheckedChange:a})=>e.jsx(Wt,{checked:t,onCheckedChange:a}),(e,t)=>e.checked===t.checked),Br=({manager:a,columns:s,onEdit:r,onView:n,onToggleStatus:i,onDelete:o,renderActions:c,customRowActions:d,enableBulkActions:u=!1,onNew:m,newButtonLabel:p,showNewButton:h=!0,customActions:f=[],hideActionBar:g=!1})=>{const{t:x}=Ga(),{setSearchVisible:b}=Zs(),[v,y]=t.useState(!1),[N,j]=t.useState(null);t.useEffect(()=>(b(!0),()=>b(!1)),[b]),t.useEffect(()=>{const e=()=>y(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),t.useEffect(()=>{const e=()=>j(null);if(N)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[N]);const w=t.useMemo(()=>(()=>{s.length;let e=0;const t=s.map(t=>{if(t.width)return e+=t.width,{...t,calculatedWidth:t.width,isFixed:!0};{const a=t.minWidth||120,s=t.weight||1;return e+=a,{...t,calculatedWidth:a,weight:s,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`}})})(),[s]),k=!g&&(m||f.length>0);return v?a.isLoading?e.jsx(jr,{count:3}):0===a.entities.length?e.jsx(kr,{title:x("empty_title"),description:x("empty_description"),variant:"search"}):e.jsxs("div",{className:"flex flex-col h-full",children:[k&&e.jsx("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[m&&h&&e.jsxs(nt,{onClick:m,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),p||x("new")]}),f.map((t,a)=>{const s=t.icon;return e.jsxs(nt,{onClick:t.action,variant:t.variant||"outline",children:[s&&e.jsx(s,{size:16,className:"mr-2"}),t.label]},a)})]})}),e.jsxs("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:[a.entities.map(t=>e.jsx(dt,{className:at("overflow-hidden cursor-pointer hover:bg-muted/50",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),j({x:e.clientX,y:e.clientY,item:t})},children:e.jsx(ht,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[u&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(qr,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),e.jsxs("div",{className:"flex-1",children:[s.map(a=>e.jsxs("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key))),(r||n||c)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(t):e.jsx(Ur,{onEdit:r?()=>{r(t)}:void 0,onDelete:o?()=>o(t):void 0,onToggleStatus:i?()=>i(t):void 0,isActive:t.is_actived,customActions:d?d(t):[]})})]})]})})},t.id)),e.jsx(Vr,{contextMenu:N,onClose:()=>j(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:d})]})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[k&&e.jsx("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[m&&h&&e.jsxs(nt,{onClick:m,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),p||x("new")]}),f.map((t,a)=>{const s=t.icon;return e.jsxs(nt,{onClick:t.action,variant:t.variant||"outline",children:[s&&e.jsx(s,{size:16,className:"mr-2"}),t.label]},a)})]})}),a.isLoading?e.jsx(Nr,{rows:5,columns:s.length}):e.jsx("div",{className:"flex flex-col h-full overflow-hidden",children:e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(pr,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),w.map((t,a)=>e.jsx("col",{style:t.style},a)),e.jsx("col",{style:{width:"50px"}})]}),e.jsx(hr,{children:e.jsxs(xr,{children:[u&&e.jsx(br,{className:"w-[50px]",children:e.jsx(qr,{checked:a.isAllSelected,onCheckedChange:a.selectAll})}),s.map(t=>{return e.jsx(br,{className:`${t.className||""} ${t.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:t.sortable?()=>a.handleSort(String(t.key)):void 0,children:e.jsxs("div",{className:"flex items-center "+(t.className?.includes("text-center")?"justify-center":""),children:[t.header,t.sortable&&(s=String(t.key),a.sortField!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===a.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]})},String(t.key));var s}),e.jsx(br,{className:"w-[50px] text-center",children:x("actions")})]})}),e.jsx(fr,{children:0===a.entities.length?e.jsx(xr,{children:e.jsx(vr,{colSpan:u?s.length+2:s.length+1,className:"h-32",children:e.jsx(kr,{title:x("empty_title"),description:x("empty_description"),variant:"search"})})}):a.entities.map(t=>e.jsxs(xr,{className:at("cursor-pointer hover:bg-muted/50",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),j({x:e.clientX,y:e.clientY,item:t})},children:[u&&e.jsx(vr,{onClick:e=>e.stopPropagation(),children:e.jsx(qr,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),s.map(a=>e.jsx(vr,{className:a.className,children:a.render?a.render(t):String(t[a.key]??"")},String(a.key))),e.jsx(vr,{className:"text-center",children:c?c(t):e.jsx(Ur,{onEdit:r?()=>r(t):void 0,onDelete:o?()=>o(t):void 0,onToggleStatus:i?()=>i(t):void 0,isActive:t.is_actived,customActions:d?d(t):[]})})]},t.id))})]})})}),e.jsx(Vr,{contextMenu:N,onClose:()=>j(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:d})]})};function Wr(e,a,s,r){const[n,i]=t.useState({}),[o,l]=t.useState({}),c=t.useMemo(()=>e,[e]),d=e=>e instanceof Date&&!isNaN(e.getTime()),u=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{}}},m=(e,t)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(t)}catch(a){return u(e)}},p=(e,t,a)=>{if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length))return`${e.label} é obrigatório`;if(e.validation){let r;if("function"==typeof e.validation?r=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(r=e.validation.custom),r)try{const e=r(t,a);if(e)return e}catch(s){}}};t.useEffect(()=>{if(!r)return;const e=t=>{const a=[];return t.forEach(t=>{a.push(t),t.fields&&a.push(...e(t.fields))}),a},t=e(c),n={};t.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);d(e)&&(t=e.toISOString().split("T")[0])}else d(t)&&(t=t.toISOString().split("T")[0])}else t=u(e);n[e.name]=t}),t.forEach(e=>{const t=m(e,n);void 0!==t&&(n[e.name]=t)}),a&&Object.keys(a).forEach(e=>{t.find(t=>t.name===e)||void 0===a[e]||(n[e]=a[e])}),i(n),l({}),s&&s(n)},[c,a,s,r]);const h=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...h(e.fields))}),t},f=()=>{const e=h(c),t={};return e.forEach(e=>{const a=p(e,n[e.name],n);a&&(t[e.name]=a)}),l(t),0===Object.keys(t).length};return{formData:n,errors:o,updateField:(e,t)=>{i(a=>{const r={...a,[e]:t},n=((e,t)=>{let a={...t};const s=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...s(e.fields))}),t};return s(c).filter(t=>t.dependsOn===e).forEach(e=>{const t=m(e,a);void 0!==t&&(a={...a,[e.name]:t})}),a})(e,r);return s&&s(n),n}),o[e]&&l(t=>{const a={...t};return delete a[e],a});const a=h(c).find(t=>t.name===e);if(a){const s=p(a,t,n);s&&l(t=>({...t,[e]:s}))}},validateForm:f,handleSubmit:e=>t=>{t&&(t.preventDefault(),t.stopPropagation()),f()&&e(n)}}}const Hr=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Kr=({value:t="#3b82f6",onChange:a,label:s})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(ct,{children:s}),e.jsxs(ha,{children:[e.jsx(fa,{asChild:!0,children:e.jsxs(nt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e.jsx(ga,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ct,{htmlFor:"color-input",children:"Cor personalizada"}),e.jsx(ot,{id:"color-input",type:"color",value:t,onChange:e=>a?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(ct,{children:"Cores predefinidas"}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Hr.map(t=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:t},onClick:()=>a?.(t),"aria-label":`Selecionar cor ${t}`},t))})]})]})})]})]}),Qr=V.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(J.Root,{ref:r,className:at("relative overflow-hidden",t),...s,children:[e.jsx(J.Viewport,{className:"h-full w-full rounded-[inherit]",children:a}),e.jsx(Gr,{}),e.jsx(J.Corner,{})]}));Qr.displayName=J.Root.displayName;const Gr=V.forwardRef(({className:t,orientation:a="vertical",...s},r)=>e.jsx(J.ScrollAreaScrollbar,{ref:r,orientation:a,className:at("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),...s,children:e.jsx(J.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Gr.displayName=J.ScrollAreaScrollbar.displayName;const Xr={Star:l.Star,Heart:l.Heart,Home:l.Home,User:l.User,Settings:l.Settings,Mail:l.Mail,Phone:l.Phone,Calendar:l.Calendar,MapPin:l.MapPin,Camera:l.Camera,Image:l.Image,Music:l.Music,Video:l.Video,Book:l.Book,Bookmark:l.Bookmark,Search:l.Search,Filter:l.Filter,Edit:l.Edit,Trash2:l.Trash2,Plus:l.Plus,Minus:l.Minus,Check:l.Check,X:l.X,ChevronDown:l.ChevronDown,ChevronUp:l.ChevronUp,ChevronLeft:l.ChevronLeft,ChevronRight:l.ChevronRight,ArrowUp:l.ArrowUp,ArrowDown:l.ArrowDown,ArrowLeft:l.ArrowLeft,ArrowRight:l.ArrowRight,Clock:l.Clock,Bell:l.Bell,AlertCircle:l.AlertCircle,Info:l.Info,HelpCircle:l.HelpCircle,Download:l.Download,Upload:l.Upload,Share:l.Share,Copy:l.Copy,Save:l.Save,FileText:l.FileText,Folder:l.Folder,FolderOpen:l.FolderOpen,Archive:l.Archive,Lock:l.Lock,Unlock:l.Unlock,Eye:l.Eye,EyeOff:l.EyeOff,Shield:l.Shield,Key:l.Key,Zap:l.Zap,Flame:l.Flame,Sparkles:l.Sparkles,Award:l.Award,Trophy:l.Trophy,Target:l.Target},Jr=({value:a="Star",onChange:s,label:r})=>{const{t:n}=Ga(),[i,o]=t.useState(""),c=Object.entries(Xr).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),d=Xr[a]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(ct,{children:r}),e.jsxs(ha,{children:[e.jsx(fa,{asChild:!0,children:e.jsxs(nt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(d,{className:"h-4 w-4 mr-2"}),a]})}),e.jsx(ga,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ct,{htmlFor:"icon-search",children:n("search")}),e.jsx(ot,{id:"icon-search",placeholder:n("search"),value:i,onChange:e=>o(e.target.value)})]}),e.jsx(Qr,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:c.map(([t,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(a===t?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(t),title:t,children:e.jsx(r,{className:"h-4 w-4"})},t))})})]})})]})]})},Yr=(e={})=>{const{user:t,alias:a}=Zs(),{enabled:s=!0}=e;return x.useQuery({queryKey:["qualiex-users",a],queryFn:()=>Es.getUsers(a),enabled:s&&!!a&&!!t,retry:2,retryDelay:1e3})},Zr=({value:t="",onChange:a,placeholder:s,disabled:r,className:n,enabled:i})=>{const{t:o}=Ga(),{data:l=[],isLoading:c,error:d}=Yr({enabled:i});return e.jsx(Ya,{value:t,onChange:a,options:l,isLoading:c,error:d,getOptionValue:e=>e.userId,getOptionLabel:e=>e.userName,placeholder:s||o("search_placeholder"),searchPlaceholder:o("search_placeholder"),emptyMessage:o("no_results"),disabled:r,className:n})};function en({title:a,sections:s,initialData:r,onSubmit:n,onCancel:i,open:o,submitButtonText:l,isLoading:c=!1,usersData:d}){const{t:u}=Ga(),[m,p]=t.useState(s?.[0]?.id||""),h=t.useRef(null),[f,g]=t.useState(null),x=t.useCallback(e=>{h.current=e,g(e)},[]),b=t.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:v,errors:y,updateField:N,handleSubmit:j}=Wr(b,r,void 0,o),w=t.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(v):e.disabled||!1})):[],[s,v]),k=t.useMemo(()=>{const e=w.find(e=>e.id===m);if(e&&!e.disabled)return m;const t=w.find(e=>!e.disabled);return t?.id||m},[w,m]);t.useEffect(()=>{k!==m&&p(k)},[k,m]);const S=w.find(e=>e.id===k),C=t=>{const a=(t.computedValue,v[t.name]),s=void 0!==a?a:"",r=y[t.name];switch(t.type){case"group":return e.jsxs("div",{className:"space-y-2",children:[t.label,e.jsx("div",{className:t.className||("horizontal"===t.layout?"flex gap-3":"space-y-3"),children:t.fields?.map(e=>C(e))})]},t.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(ct,{htmlFor:t.name,children:t.label}),e.jsx(Zr,{value:s||"",onChange:e=>N(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:r?"border-red-500":""}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(ct,{htmlFor:t.name,children:t.label}),e.jsx(Ht,{id:t.name,value:s||"",onChange:e=>{N(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(ct,{htmlFor:t.name,children:t.label}),e.jsxs(Ot,{value:String(s),onValueChange:e=>{N(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e.jsx(Mt,{className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e.jsx(Dt,{placeholder:t.placeholder})}),e.jsx(Ut,{children:t.options?.map(t=>e.jsx(qt,{value:t.value,children:t.label},t.value))})]}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx(Ya,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>N(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:r,popoverContainer:f,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"date":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(ct,{htmlFor:t.name,children:t.label}),e.jsx(ot,{id:t.name,type:"date",value:String(s),onChange:e=>N(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:at("w-full",r?"border-red-500":"",t.disabled?"bg-gray-100 cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"color":return e.jsxs("div",{children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label," ",t.required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(ot,{id:t.name,type:"color",value:s||t.defaultValue||"#000000",onChange:e=>N(t.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"color-picker":return e.jsxs("div",{children:[e.jsx(Kr,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"#3b82f6",onChange:e=>N(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"icon-picker":return e.jsxs("div",{children:[e.jsx(Jr,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"Star",onChange:e=>N(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"custom":if(!t.component)return null;const a=t.component;return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&e.jsx(ct,{htmlFor:t.name,children:t.label}),e.jsx(a,{value:s,onChange:e=>{N(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:r,popoverContainer:f,...t.componentProps||{}}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"number":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(ct,{htmlFor:t.name,children:t.label}),e.jsx(ot,{id:t.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const a=e.target.value,s=""===a?null:Number(a);N(t.name,s)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);default:return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(ct,{htmlFor:t.name,children:t.label}),e.jsx(ot,{id:t.name,type:"text",value:s||"",onChange:e=>{N(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:t.disabled}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name)}},P=t.useCallback(()=>{if(!S)return null;if(S.disabled)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-3 mb-4",children:e.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e.jsx("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(S.component){const t=S.component;return e.jsx(t,{formData:v,updateField:N,errors:y,users:d,disabled:S.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:S.fields.map(C)})},[S,v,N,y,d,C]),E=e.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[w.length>1&&e.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:e.jsx("div",{className:"flex space-x-2",children:w.map(t=>e.jsx(nt,{variant:k===t.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const t=w.find(t=>t.id===e);t&&!t.disabled&&p(e)})(t.id),disabled:t.disabled,className:t.disabled?"opacity-50 cursor-not-allowed":"",children:t.title},t.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:c?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"text-muted-foreground",children:u("loading")})}):e.jsxs("form",{onSubmit:j(n),className:"space-y-3 md:space-y-4",children:[P(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(nt,{type:"button",variant:"outline",onClick:i,children:u("cancel")}),e.jsx(nt,{type:"submit",disabled:c,children:l||u("save")})]})]})})]});return e.jsx(gt,{open:o,onOpenChange:e=>{!1===e&&!0===o&&i()},children:e.jsxs(Nt,{ref:x,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(jt,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e.jsx(kt,{className:"text-white",children:a}),e.jsx(St,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),E]})})}function tn({currentPage:t,totalPages:a,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:i,variant:o="full"}){const c=(t-1)*r+1,d=Math.min(t*r,s);return e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:"full"===o&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),e.jsxs(Ot,{value:String(r),onValueChange:e=>i(Number(e)),children:[e.jsx(Mt,{className:"h-8 w-[70px]",children:e.jsx(Dt,{})}),e.jsxs(Ut,{children:[e.jsx(qt,{value:"10",children:"10"}),e.jsx(qt,{value:"25",children:"25"}),e.jsx(qt,{value:"50",children:"50"}),e.jsx(qt,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[c,"-",d," de ",s," itens"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(nt,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(nt,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:1===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronLeft,{size:16})}),e.jsxs("div",{className:"flex items-center gap-1 px-2",children:[e.jsx("span",{className:"text-sm font-medium",children:t}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"de"}),e.jsx("span",{className:"text-sm font-medium",children:a})]}),e.jsx(nt,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(nt,{variant:"outline",size:"sm",onClick:()=>n(a),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function an({manager:t}){return e.jsx(tn,{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 sn=({selectedCount:t,onClearSelection:a,onBulkDelete:s,customActions:r=[],isLoading:n=!1})=>{const{t:i}=Ga();return e.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:i("selected",{count:t})}),e.jsxs(nt,{variant:"ghost",size:"sm",onClick:a,className:"h-7 px-2",children:[e.jsx(l.X,{size:14,className:"mr-1"}),i("clear")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.map((t,a)=>{const s=t.icon;return e.jsxs(nt,{variant:t.variant||"outline",size:"sm",onClick:()=>t.action([]),disabled:n,className:"h-7",children:[s&&e.jsx(s,{size:14,className:"mr-1"}),t.label]},a)}),s&&e.jsxs(nt,{variant:"destructive",size:"sm",onClick:s,disabled:n,className:"h-7",children:[e.jsx(l.Trash2,{size:14,className:"mr-1"}),i("delete")]})]})]})},rn={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},nn={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},on={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function ln({children:t,direction:a="column",gap:s="md",align:r="stretch",justify:n="start",wrap:i=!1,className:o}){return e.jsx("div",{className:at("flex","column"===a?"flex-col":"flex-row",rn[s],nn[r],on[n],i&&"flex-wrap",o),children:t})}function cn({manager:t,filters:a,inline:s=!1}){const{t:r}=Ga(),{isSearchVisible:n}=Zs(),i=t.searchTerm,o=e.jsxs(e.Fragment,{children:[a.some(e=>"search"===e.type)&&!n&&e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ot,{placeholder:r("search"),value:t.searchTerm,onChange:e=>t.handleSearch(e.target.value),className:"pl-10"})]}),a.filter(e=>"select"===e.type&&e.options).map((t,a)=>e.jsxs("select",{value:t.value||"",onChange:e=>t.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:[t.placeholder&&e.jsx("option",{value:"",children:t.placeholder}),t.options.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))]},`select-${a}`)),a.filter(e=>"custom"===e.type&&e.component).map((t,a)=>{const r=t.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...t.props})},`custom-${a}`)}),i&&e.jsxs(nt,{variant:"outline",onClick:t.clearFilters,className:"whitespace-nowrap",children:[e.jsx(l.X,{className:"h-4 w-4 mr-2"}),r("clear")]})]});return s?e.jsx("div",{className:"flex items-center gap-2",children:o}):e.jsx(ln,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(ln,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:o})})}function dn({manager:a,config:s,formSections:r,onSave:n,onToggleStatus:i,defaultSort:o}){a&&a.queryKey;const{t:c}=Ga(),{setSearchVisible:d}=Zs(),[u,m]=b.useSearchParams(),[p,h]=t.useState(!1),[f,g]=t.useState(null),[x,v]=t.useState({isOpen:!1,entityId:null,entityName:""}),[y,N]=t.useState({isOpen:!1,count:0});t.useEffect(()=>(d(!0),()=>{d(!1)}),[d]),t.useEffect(()=>{if(o&&a){const e=`${a.queryKey}_sortField`,t=`${a.queryKey}_sortDirection`;if(!u.has(e)&&!u.has(t)){const a=Object.fromEntries(u);a[e]=o.column,a[t]=o.direction,m(a)}}},[]);return e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[s.enableBulkActions&&a.selectedIds.length>0&&e.jsx(sn,{selectedCount:a.selectedIds.length,onClearSelection:a.clearSelection,onBulkDelete:s.bulkActions&&s.bulkActions.length>0?void 0:()=>{N({isOpen:!0,count:a.selectedIds.length})},customActions:s.bulkActions,isLoading:a.isBulkDeleting}),e.jsxs("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(nt,{onClick:()=>{s.onNew?s.onNew():(g(null),h(!0))},children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),c("new")]}),s.customActions?.map((t,a)=>e.jsxs(nt,{onClick:t.action,variant:t.variant||"outline",children:[t.icon&&e.jsx(t.icon,{size:16,className:"mr-2"}),t.label]},a))]}),s.filters&&s.filters.length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e.jsx(cn,{manager:a,filters:s.filters,inline:!0})})]}),e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:s.customListView?e.jsx("div",{className:"flex-1 overflow-auto p-4",children:s.customListView(a.entities,a)}):e.jsx(Br,{manager:a,columns:s.columns,onEdit:e=>{s.onEdit?s.onEdit(e):(g(e),h(!0))},onDelete:e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:i,enableBulkActions:s.enableBulkActions,customRowActions:s.customRowActions})}),e.jsx("div",{className:"flex-shrink-0 border-t bg-background",children:e.jsx(an,{manager:a})}),!s.useCustomRouting&&e.jsx(en,{open:p,title:f?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:f||void 0,onSubmit:e=>{n(e),h(!1),g(null)},onCancel:()=>{h(!1),g(null)},isLoading:a.isLoading,submitButtonText:c(f?"update":"create")}),e.jsx(mr,{open:x.isOpen,onOpenChange:()=>{v({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{x.entityId&&(a.deleteEntity(x.entityId),v({isOpen:!1,entityId:null,entityName:""}))},item:x.entityId?{id:x.entityId,title:x.entityName}:void 0,entityName:s.entityName,isDeleting:a.isDeleting}),e.jsx(mr,{open:y.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),onConfirm:()=>(a.bulkDelete?.(a.selectedIds),void N({isOpen:!1,count:0})),item:{id:"bulk",title:`${y.count} ${1===y.count?s.entityName:s.entityNamePlural}`},entityName:s.entityNamePlural,isDeleting:a.isBulkDeleting,isBulk:!0,bulkCount:y.count})]})}function un(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 mn(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const pn=V.forwardRef(({className:t,value:a,...s},r)=>e.jsx(Y.Root,{ref:r,className:at("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...s,children:e.jsx(Y.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(a||0)}%)`}})}));function hn({steps:t,currentStepIndex:a,onStepClick:s,className:r}){return e.jsx("div",{className:at("flex items-center justify-between mb-6",r),children:t.map((a,r)=>e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("div",{className:at("flex items-center justify-center w-10 h-10 rounded-full border-2 transition-colors font-medium",a.isActive&&"border-primary bg-primary text-primary-foreground",a.isCompleted&&"border-primary bg-primary text-primary-foreground",!a.isActive&&!a.isCompleted&&"border-muted-foreground/30 text-muted-foreground bg-background",s&&!a.isDisabled&&"cursor-pointer hover:border-primary/50",a.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>s&&!a.isDisabled&&s(r),role:s&&!a.isDisabled?"button":void 0,tabIndex:s&&!a.isDisabled?0:void 0,"aria-label":`${a.label} - ${a.isCompleted?"Completo":a.isActive?"Atual":"Pendente"}`,children:a.isCompleted?e.jsx(l.Check,{className:"w-5 h-5"}):r+1}),r<t.length-1&&e.jsx("div",{className:at("flex-1 h-0.5 mx-2 transition-colors",a.isCompleted?"bg-primary":"bg-muted-foreground/30"),"aria-hidden":"true"})]},a.id))})}function fn({steps:t,currentStepIndex:a,onStepClick:s,className:r}){return e.jsx("div",{className:at("flex items-center gap-2 mb-6 overflow-x-auto",r),children:t.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[e.jsxs("div",{className:at("flex items-center gap-2 px-3 py-2 rounded-md transition-colors",a.isActive&&"bg-primary text-primary-foreground font-medium",a.isCompleted&&"bg-primary/10 text-primary",!a.isActive&&!a.isCompleted&&"bg-muted text-muted-foreground",s&&!a.isDisabled&&"cursor-pointer hover:bg-primary/20",a.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>s&&!a.isDisabled&&s(r),role:s&&!a.isDisabled?"button":void 0,tabIndex:s&&!a.isDisabled?0:void 0,"aria-label":`${a.label} - ${a.isCompleted?"Completo":a.isActive?"Atual":"Pendente"}`,children:[e.jsx("span",{className:"text-sm font-medium",children:r+1}),e.jsx("span",{className:"text-sm",children:a.label}),a.isCompleted&&e.jsx(l.Check,{className:"w-4 h-4 ml-1"})]}),r<t.length-1&&e.jsx("span",{className:"text-muted-foreground","aria-hidden":"true",children:"/"})]},a.id))})}function gn({steps:t,currentStepIndex:a,className:s}){const r=t[a],n=(a+1)/t.length*100;return e.jsxs("div",{className:at("mb-6 space-y-2",s),children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Etapa ",a+1," de ",t.length]}),e.jsx("span",{className:"font-medium",children:r?.label})]}),e.jsx(pn,{value:n,className:"h-2"})]})}function xn({isFirstStep:t,isLastStep:a,canGoNext:s,canGoPrevious:r,isLoading:n,onPrevious:i,onNext:o,onSubmit:l,previousButtonText:c,nextButtonText:d,submitButtonText:u}){const{t:m}=Ga();return e.jsxs(e.Fragment,{children:[e.jsx("div",{children:r&&!t&&e.jsx(nt,{type:"button",variant:"outline",onClick:i,disabled:n,children:c||m("previous")})}),e.jsxs("div",{className:"flex gap-2",children:[s&&!a&&e.jsx(nt,{type:"button",onClick:o,disabled:n,children:d||m("next")}),a&&e.jsx(nt,{type:"button",onClick:l,disabled:n,children:n?m("saving"):u||m("save")})]})]})}pn.displayName=Y.Root.displayName;const bn=s.cva("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"}}),vn=V.forwardRef(({className:t,variant:a,...s},r)=>e.jsx("div",{ref:r,role:"alert",className:at(bn({variant:a}),t),...s}));vn.displayName="Alert";const yn=V.forwardRef(({className:t,...a},s)=>e.jsx("h5",{ref:s,className:at("mb-1 font-medium leading-none tracking-tight",t),...a}));yn.displayName="AlertTitle";const Nn=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("text-sm [&_p]:leading-relaxed",t),...a}));Nn.displayName="AlertDescription";const jn=t.createContext(void 0);function wn({children:a,actions:s}){const[r,n]=t.useState({}),[i,o]=t.useState(s);return t.useEffect(()=>{o(s)},[s]),e.jsx(jn.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:i,setHeaderActions:o},children:a})}function kn(){const e=t.useContext(jn);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}const Sn=Z.Root,Cn=V.forwardRef(({className:t,...a},s)=>e.jsx(Z.Item,{ref:s,className:at("border-b",t),...a}));Cn.displayName="AccordionItem";const Pn=V.forwardRef(({className:t,children:a,...s},r)=>e.jsx(Z.Header,{className:"flex",children:e.jsxs(Z.Trigger,{ref:r,className:at("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...s,children:[a,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Pn.displayName=Z.Trigger.displayName;const En=V.forwardRef(({className:t,children:a,...s},r)=>e.jsx(Z.Content,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...s,children:e.jsx("div",{className:at("pb-4 pt-0",t),children:a})}));En.displayName=Z.Content.displayName;const Tn=ee.Root,An=V.forwardRef(({className:t,...a},s)=>e.jsx(te.Root,{ref:s,className:at("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...a}));An.displayName=te.Root.displayName;const _n=V.forwardRef(({className:t,...a},s)=>e.jsx(te.Image,{ref:s,className:at("aspect-square h-full w-full",t),...a}));_n.displayName=te.Image.displayName;const In=V.forwardRef(({className:t,...a},s)=>e.jsx(te.Fallback,{ref:s,className:at("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...a}));In.displayName=te.Fallback.displayName;const Rn=V.forwardRef(({...t},a)=>e.jsx("nav",{ref:a,"aria-label":"breadcrumb",...t}));Rn.displayName="Breadcrumb";const Ln=V.forwardRef(({className:t,...a},s)=>e.jsx("ol",{ref:s,className:at("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",t),...a}));Ln.displayName="BreadcrumbList";const On=V.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:at("inline-flex items-center gap-1.5",t),...a}));On.displayName="BreadcrumbItem";const Fn=V.forwardRef(({asChild:t,className:a,...s},r)=>{const n=t?V.Fragment:"a";return e.jsx(n,{ref:r,className:at("transition-colors hover:text-foreground",a),...s})});Fn.displayName="BreadcrumbLink";const Dn=V.forwardRef(({className:t,...a},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:at("font-normal text-foreground",t),...a}));Dn.displayName="BreadcrumbPage";const Mn=({children:t,className:a,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:at("[&>svg]:size-3.5",a),...s,children:t??e.jsx(l.ChevronRight,{})});Mn.displayName="BreadcrumbSeparator";const zn=({className:t,...a})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:at("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More"})]});zn.displayName="BreadcrumbEllipsis";const $n=s.cva("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"}}),Un=V.forwardRef(({className:t,orientation:a,...s},r)=>e.jsx("div",{ref:r,className:at($n({orientation:a}),t),...s}));function Vn(e){return(t={})=>{const a=t.width?String(t.width):e.defaultWidth;return e.formats[a]||e.formats[e.defaultWidth]}}function qn(e){return(t,a)=>{let s;if("formatting"===(a?.context?String(a.context):"standalone")&&e.formattingValues){const t=e.defaultFormattingWidth||e.defaultWidth,r=a?.width?String(a.width):t;s=e.formattingValues[r]||e.formattingValues[t]}else{const t=e.defaultWidth,r=a?.width?String(a.width):e.defaultWidth;s=e.values[r]||e.values[t]}return s[e.argumentCallback?e.argumentCallback(t):t]}}function Bn(e){return(t,a={})=>{const s=a.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=t.match(r);if(!n)return null;const i=n[0],o=s&&e.parsePatterns[s]||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 Wn(e){return(t,a={})=>{const s=t.match(e.matchPattern);if(!s)return null;const r=s[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(r.length)}}}Un.displayName="ButtonGroup";const Hn={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"}},Kn={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Qn={ordinalNumber:(e,t)=>{const a=Number(e),s=a%100;if(s>20||s<10)switch(s%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},era:qn({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:qn({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:qn({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:qn({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:qn({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"})},Gn={ordinalNumber:Wn({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Bn({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:Bn({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:Bn({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:Bn({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:Bn({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"})},Xn={code:"en-US",formatDistance:(e,t,a)=>{let s;const r=Hn[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"in "+s:s+" ago":s},formatLong:{date:Vn({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Vn({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:Vn({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,t,a,s)=>Kn[e],localize:Qn,match:Gn,options:{weekStartsOn:0,firstWeekContainsDate:1}},Jn={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"}},Yn={date:Vn({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:Vn({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Vn({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Zn={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"},ei={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"},ti={ordinalNumber:(e,t)=>Number(e)+"º",era:qn({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:qn({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:qn({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:qn({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:qn({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"})},ai={ordinalNumber:Wn({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Bn({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:Bn({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:Bn({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:Bn({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:Bn({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"})},si={code:"es",formatDistance:(e,t,a)=>{let s;const r=Jn[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"en "+s:"hace "+s:s},formatLong:Yn,formatRelative:(e,t,a,s)=>1!==t.getHours()?ei[e]:Zn[e],localize:ti,match:ai,options:{weekStartsOn:1,firstWeekContainsDate:1}},ri={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"}},ni={date:Vn({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:Vn({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Vn({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},ii={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"},oi={ordinalNumber:(e,t)=>{const a=Number(e);return"week"===t?.unit?a+"ª":a+"º"},era:qn({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:qn({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:qn({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:qn({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:qn({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"})},li={ordinalNumber:Wn({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Bn({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:Bn({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:Bn({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:Bn({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:Bn({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"})},ci={code:"pt-BR",formatDistance:(e,t,a)=>{let s;const r=ri[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",String(t)),a?.addSuffix?a.comparison&&a.comparison>0?"em "+s:"há "+s:s},formatLong:ni,formatRelative:(e,t,a,s)=>{const r=ii[e];return"function"==typeof r?r(t):r},localize:oi,match:li,options:{weekStartsOn:0,firstWeekContainsDate:1}};function di({className:t,classNames:a,showOutsideDays:s=!0,...r}){return e.jsx(C.DayPicker,{showOutsideDays:s,className:at("p-3",t),locale:ci,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:at(rt({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:at(rt({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.jsx(l.ChevronLeft,{className:"h-4 w-4"}),IconRight:({...t})=>e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}di.displayName="Calendar";const ui=ae.Root,mi=ae.CollapsibleTrigger,pi=ae.CollapsibleContent;const hi={Root:function({children:t,className:a}){return e.jsx("div",{className:at("space-y-4",a),children:t})},Item:function({children:t,onClick:a,className:s}){return e.jsx(dt,{className:at("transition-colors",a&&"cursor-pointer hover:bg-muted/50",s),onClick:a,children:e.jsx(ht,{className:"p-4",children:t})})},Field:function({label:t,value:a,className:s}){return e.jsxs("div",{className:at("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e.jsx("span",{className:"text-foreground",children:a})]})}};const fi={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))]"},gi={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function xi({children:t,cols:a="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:at("grid",fi[a],gi[s],r),children:t})}const bi=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("flex items-center rounded-md border border-input bg-background focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2",t),...a}));bi.displayName="InputGroup";const vi=V.forwardRef(({className:t,...a},s)=>e.jsx("input",{ref:s,className:at("flex h-10 flex-1 bg-transparent px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",t),...a}));vi.displayName="InputGroupInput";const yi=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("flex items-center justify-center border-l border-input px-3 text-sm text-muted-foreground",t),...a}));yi.displayName="InputGroupAddon";const Ni=V.forwardRef(({className:t,keys:a,children:s,...r},n)=>a&&a.length>0?e.jsxs("span",{className:at("inline-flex items-center gap-1",t),children:[a.map((t,a)=>e.jsx("kbd",{className:at("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.jsx("kbd",{ref:n,className:at("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"),...r,children:s})]}):e.jsx("kbd",{ref:n,className:at("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",t),...r,children:s}));Ni.displayName="Kbd";const ji=V.forwardRef(({className:t,children:a,...s},r)=>e.jsx("select",{ref:r,className:at("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),...s,children:a}));ji.displayName="NativeSelect";const wi=V.forwardRef(({className:t,...a},s)=>e.jsx("h1",{ref:s,className:at("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",t),...a}));wi.displayName="H1";const ki=V.forwardRef(({className:t,...a},s)=>e.jsx("h2",{ref:s,className:at("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",t),...a}));ki.displayName="H2";const Si=V.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:at("scroll-m-20 text-2xl font-semibold tracking-tight",t),...a}));Si.displayName="H3";const Ci=V.forwardRef(({className:t,...a},s)=>e.jsx("h4",{ref:s,className:at("scroll-m-20 text-xl font-semibold tracking-tight",t),...a}));Ci.displayName="H4";const Pi=V.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:at("leading-7 [&:not(:first-child)]:mt-6",t),...a}));Pi.displayName="P";const Ei=V.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:at("text-xl text-muted-foreground",t),...a}));Ei.displayName="Lead";const Ti=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:at("text-lg font-semibold",t),...a}));Ti.displayName="Large";const Ai=V.forwardRef(({className:t,...a},s)=>e.jsx("small",{ref:s,className:at("text-sm font-medium leading-none",t),...a}));Ai.displayName="Small";const _i=V.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:at("text-sm text-muted-foreground",t),...a}));_i.displayName="Muted";const Ii=V.forwardRef(({className:t,...a},s)=>e.jsx("code",{ref:s,className:at("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",t),...a}));Ii.displayName="InlineCode";const Ri=V.forwardRef(({className:t,...a},s)=>e.jsx("blockquote",{ref:s,className:at("mt-6 border-l-2 pl-6 italic",t),...a}));Ri.displayName="Blockquote";const Li=V.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:at("my-6 ml-6 list-disc [&>li]:mt-2",t),...a}));Li.displayName="List";const Oi=({className:t,...a})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:at("mx-auto flex w-full justify-center",t),...a});Oi.displayName="Pagination";const Fi=V.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:at("flex flex-row items-center gap-1",t),...a}));Fi.displayName="PaginationContent";const Di=V.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:at("",t),...a}));Di.displayName="PaginationItem";const Mi=({className:t,isActive:a,size:s="icon",...r})=>e.jsx("a",{"aria-current":a?"page":void 0,className:at(rt({variant:a?"outline":"ghost",size:s}),t),...r});Mi.displayName="PaginationLink";const zi=({className:t,...a})=>e.jsxs(Mi,{"aria-label":"Go to previous page",size:"default",className:at("gap-1 pl-2.5",t),...a,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});zi.displayName="PaginationPrevious";const $i=({className:t,...a})=>e.jsxs(Mi,{"aria-label":"Go to next page",size:"default",className:at("gap-1 pr-2.5",t),...a,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});$i.displayName="PaginationNext";const Ui=({className:t,...a})=>e.jsxs("span",{"aria-hidden":!0,className:at("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});Ui.displayName="PaginationEllipsis";const Vi=V.forwardRef(({className:t,...a},s)=>e.jsx(se.Root,{className:at("grid gap-2",t),...a,ref:s}));Vi.displayName=se.Root.displayName;const qi=V.forwardRef(({className:t,...a},s)=>e.jsx(se.Item,{ref:s,className:at("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.jsx(se.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));qi.displayName=se.Item.displayName;const Bi=s.cva("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"}}),Wi=V.forwardRef(({className:t,variant:a,size:s,onClear:r,showClearButton:n=!0,value:i,...o},c)=>{const d=null!=i&&""!==i;return e.jsxs("div",{className:at(Bi({variant:a,size:s,className:t})),children:[e.jsx(l.Search,{className:"ml-3 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",className:at("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:c,value:i,...o}),n&&d&&r&&e.jsx("button",{type:"button",onClick:r,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.jsx(l.X,{className:"h-4 w-4"})})]})});Wi.displayName="Searchbar";const Hi=V.forwardRef(({className:t,orientation:a="horizontal",decorative:s=!0,...r},n)=>e.jsx(re.Root,{ref:n,decorative:s,orientation:a,className:at("shrink-0 bg-border","horizontal"===a?"h-[1px] w-full":"h-full w-[1px]",t),...r}));Hi.displayName=re.Root.displayName;const Ki=B.Root,Qi=B.Trigger,Gi=B.Close,Xi=B.Portal,Ji=V.forwardRef(({className:t,...a},s)=>e.jsx(B.Overlay,{className:at("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:s}));Ji.displayName=B.Overlay.displayName;const Yi=s.cva("fixed z-50 gap-4 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 data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t 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"}}),Zi=V.forwardRef(({side:t="right",className:a,children:s,...r},n)=>e.jsxs(Xi,{children:[e.jsx(Ji,{}),e.jsxs(B.Content,{ref:n,className:at(Yi({side:t}),a),...r,children:[s,e.jsxs(B.Close,{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 data-[state=open]:bg-secondary",children:[e.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Zi.displayName=B.Content.displayName;const eo=({className:t,...a})=>e.jsx("div",{className:at("flex flex-col space-y-2 text-center sm:text-left",t),...a});eo.displayName="SheetHeader";const to=({className:t,...a})=>e.jsx("div",{className:at("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});to.displayName="SheetFooter";const ao=V.forwardRef(({className:t,...a},s)=>e.jsx(B.Title,{ref:s,className:at("text-lg font-semibold text-foreground",t),...a}));ao.displayName=B.Title.displayName;const so=V.forwardRef(({className:t,...a},s)=>e.jsx(B.Description,{ref:s,className:at("text-sm text-muted-foreground",t),...a}));so.displayName=B.Description.displayName;const ro=ne.Provider,no=ne.Root,io=ne.Trigger,oo=V.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(ne.Content,{ref:r,sideOffset:a,className:at("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),...s}));oo.displayName=ne.Content.displayName;const lo="sidebar:state",co=V.createContext(null);function uo(){const e=V.useContext(co);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const mo=V.forwardRef(({defaultOpen:t=!0,open:a,onOpenChange:s,className:r,style:n,children:i,...o},l)=>{const[c,d]=V.useState(!1);V.useEffect(()=>{const e=()=>d(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,m]=V.useState(!1),[p,h]=V.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(lo);return null!==e?"true"===e:t}return t}),f=a??p,g=V.useCallback(e=>{const t="function"==typeof e?e(f):e;s?s(t):h(t),"undefined"!=typeof window&&localStorage.setItem(lo,String(t))},[s,f]),x=V.useCallback(()=>c?m(e=>!e):g(e=>!e),[c,g,m]);V.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),x())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[x]);const b=f?"expanded":"collapsed",v=V.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:c,openMobile:u,setOpenMobile:m,toggleSidebar:x}),[b,f,g,c,u,m,x]);return e.jsx(co.Provider,{value:v,children:e.jsx(ro,{delayDuration:0,children:e.jsx("div",{className:at("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",r),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...n},ref:l,...o,children:i})})})});mo.displayName="SidebarProvider";const po=V.forwardRef(({side:t="left",variant:a="sidebar",collapsible:s="offcanvas",className:r,children:n,...i},o)=>{const{isMobile:l,state:c,openMobile:d,setOpenMobile:u}=uo();return"none"===s?e.jsx("div",{className:at("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:o,...i,children:n}):l?e.jsx(Ki,{open:d,onOpenChange:u,...i,children:e.jsxs(Zi,{"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:t,children:[e.jsx(ao,{className:"sr-only",children:"Menu de Navegação"}),e.jsx("div",{className:"flex h-full w-full flex-col",children:n})]})}):e.jsxs("div",{ref:o,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?s:"","data-variant":a,"data-side":t,children:[e.jsx("div",{className:at("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"===a||"inset"===a?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:at("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===t?"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"===a||"inset"===a?"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",r),...i,children:e.jsx("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:n})})]})});po.displayName="Sidebar";const ho=V.forwardRef(({className:t,onClick:a,...s},r)=>{const{toggleSidebar:n}=uo();return e.jsxs(nt,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:at("h-7 w-7",t),onClick:e=>{a?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});ho.displayName="SidebarTrigger";const fo=V.forwardRef(({className:t,...a},s)=>{const{toggleSidebar:r}=uo();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:at("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})});fo.displayName="SidebarRail";const go=V.forwardRef(({className:t,...a},s)=>e.jsx("main",{ref:s,className:at("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}));go.displayName="SidebarInset";const xo=V.forwardRef(({className:t,...a},s)=>e.jsx(ot,{ref:s,"data-sidebar":"input",className:at("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),...a}));xo.displayName="SidebarInput";const bo=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:at("flex flex-col gap-2 p-2",t),...a}));bo.displayName="SidebarHeader";const vo=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:at("flex flex-col gap-2 p-2",t),...a}));vo.displayName="SidebarFooter";const yo=V.forwardRef(({className:t,...a},s)=>e.jsx(Hi,{ref:s,"data-sidebar":"separator",className:at("mx-2 w-auto bg-sidebar-border",t),...a}));yo.displayName="SidebarSeparator";const No=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:at("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...a}));No.displayName="SidebarContent";const jo=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:at("relative flex w-full min-w-0 flex-col p-2",t),...a}));jo.displayName="SidebarGroup";const wo=V.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const i=s?a.Slot:"div";return e.jsx(i,{ref:n,"data-sidebar":"group-label",className:at("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})});wo.displayName="SidebarGroupLabel";const ko=V.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const i=s?a.Slot:"button";return e.jsx(i,{ref:n,"data-sidebar":"group-action",className:at("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})});ko.displayName="SidebarGroupAction";const So=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:at("w-full text-sm",t),...a}));So.displayName="SidebarGroupContent";const Co=V.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:at("flex w-full min-w-0 flex-col gap-1",t),...a}));Co.displayName="SidebarMenu";const Po=V.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:at("group/menu-item relative",t),...a}));Po.displayName="SidebarMenuItem";const Eo=s.cva("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"}}),To=V.forwardRef(({asChild:t=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:i,className:o,...l},c)=>{const d=t?a.Slot:"button",{isMobile:u,state:m}=uo(),p=e.jsx(d,{ref:c,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:at(Eo({variant:r,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),e.jsxs(no,{children:[e.jsx(io,{asChild:!0,children:p}),e.jsx(oo,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):p});To.displayName="SidebarMenuButton";const Ao=V.forwardRef(({className:t,asChild:s=!1,showOnHover:r=!1,...n},i)=>{const o=s?a.Slot:"button";return e.jsx(o,{ref:i,"data-sidebar":"menu-action",className:at("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})});Ao.displayName="SidebarMenuAction";const _o=V.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:at("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}));_o.displayName="SidebarMenuBadge";const Io=V.forwardRef(({className:t,showIcon:a=!1,...s},r)=>{const n=V.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:at("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[a&&e.jsx("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});Io.displayName="SidebarMenuSkeleton";const Ro=V.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:at("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}));Ro.displayName="SidebarMenuSub";const Lo=V.forwardRef(({...t},a)=>e.jsx("li",{ref:a,...t}));Lo.displayName="SidebarMenuSubItem";const Oo=V.forwardRef(({asChild:t=!1,size:s="md",isActive:r,className:n,...i},o)=>{const l=t?a.Slot:"a";return e.jsx(l,{ref:o,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:at("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"===s&&"text-xs","md"===s&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i})});Oo.displayName="SidebarMenuSubButton";const Fo=V.forwardRef(({className:t,...a},s)=>e.jsxs(ie.Root,{ref:s,className:at("relative flex w-full touch-none select-none items-center",t),...a,children:[e.jsx(ie.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(ie.Range,{className:"absolute h-full bg-primary"})}),e.jsx(ie.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"})]}));Fo.displayName=ie.Root.displayName;const Do=V.forwardRef(({className:t,...a},s)=>e.jsx(oe.Root,{className:at("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:s,children:e.jsx(oe.Thumb,{className:at("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")})}));Do.displayName=oe.Root.displayName;const Mo=le.Root,zo=V.forwardRef(({className:t,...a},s)=>e.jsx(le.List,{ref:s,className:at("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",t),...a}));zo.displayName=le.List.displayName;const $o=V.forwardRef(({className:t,...a},s)=>e.jsx(le.Trigger,{ref:s,className:at("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}));$o.displayName=le.Trigger.displayName;const Uo=V.forwardRef(({className:t,...a},s)=>e.jsx(le.Content,{ref:s,className:at("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));Uo.displayName=le.Content.displayName;const Vo=s.cva("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"}}),qo=V.forwardRef(({className:t,variant:a,size:s,...r},n)=>e.jsx(ce.Root,{ref:n,className:at(Vo({variant:a,size:s,className:t})),...r}));qo.displayName=ce.Root.displayName;const Bo=V.createContext({size:"default",variant:"default"}),Wo=V.forwardRef(({className:t,variant:a,size:s,children:r,...n},i)=>e.jsx(de.Root,{ref:i,className:at("flex items-center justify-center gap-1",t),...n,children:e.jsx(Bo.Provider,{value:{variant:a,size:s},children:r})}));Wo.displayName=de.Root.displayName;const Ho=V.forwardRef(({className:t,children:a,variant:s,size:r,...n},i)=>{const o=V.useContext(Bo);return e.jsx(de.Item,{ref:i,className:at(Vo({variant:o.variant||s,size:o.size||r}),t),...n,children:a})});function Ko({onEdit:t,onDelete:a,onToggleStatus:s,isActive:r=!0,canEdit:n=!0,canDelete:i=!0,customActions:o=[],renderAs:c="dropdown",variant:d="default"}){const{t:u}=Ga(),m=[];return t&&n&&m.push({icon:l.Edit,label:u("edit"),onClick:t,variant:"default"}),s&&m.push({icon:r?l.PowerOff:l.Power,label:u(r?"deactivate":"activate"),onClick:s,variant:"default"}),o.forEach(e=>{!1!==e.show&&m.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),a&&i&&m.push({icon:l.Trash2,label:u("remove"),onClick:a,variant:"destructive"}),0===m.length?null:"dropdown"===c?e.jsxs(Sr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(nt,{variant:"ghost",size:"compact"===d?"sm":"default",className:"compact"===d?"h-7 px-2":"",children:e.jsx(l.EllipsisVertical,{size:"compact"===d?14:16})})}),e.jsx(Rr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:m.map((t,a)=>e.jsxs(Lr,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},a))})]}):e.jsx("div",{className:"flex items-center gap-1",children:m.map((t,a)=>e.jsxs(nt,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===d?"sm":"default",onClick:t.onClick,className:"compact"===d?"h-7 px-2":"",children:[t.icon&&e.jsx(t.icon,{size:"compact"===d?14:16}),"compact"!==d&&e.jsx("span",{className:"ml-1",children:t.label})]},a))})}function Qo(e){const t=b.useNavigate();return{onNew:()=>{const a=e.newPath||`${e.basePath}/new`;t(a)},onEdit:a=>{const s=e.editPath?e.editPath.replace(":id",a.id):`${e.basePath}/${a.id}/edit`;t(s)}}}Ho.displayName=de.Item.displayName;const Go=new class{async getUserPreferences(e,t){const a=bs();try{const{data:s,error:r}=await a.schema("common").from("user_preferences").select("*").eq("id_user",e).eq("alias",t).maybeSingle();if(r&&"PGRST116"!==r.code)return null;if(!s)return this.createDefaultPreferences(e,t);const n=s;return{locale:n.locale,timezone:n.timezone,currency:n.currency,dateFormat:n.date_format}}catch(s){return null}}async createDefaultPreferences(e,t){const a=bs(),s={id_user:e,locale:"pt-BR",timezone:"America/Sao_Paulo",currency:"BRL",date_format:"DD/MM/YYYY",alias:t};try{const{data:e,error:t}=await a.schema("common").from("user_preferences").insert(s).select().single();if(t)throw t;const r=e;return{locale:r.locale,timezone:r.timezone,currency:r.currency,dateFormat:r.date_format}}catch(r){throw r}}async updatePreferences(e,t,a){const s=bs();try{const{error:r}=await s.schema("common").from("user_preferences").update(a).eq("id_user",e).eq("alias",t);if(r)throw r}catch(r){throw r}}};var Xo=Object.defineProperty,Jo=(e,t,a)=>((e,t,a)=>t in e?Xo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const Yo=new class{constructor(){Jo(this,"cache",{}),Jo(this,"cacheTimestamps",new Map),Jo(this,"CACHE_TTL",3e5),Jo(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){const t=bs(),{data:a,error:s}=await t.schema("common").from("translations").select("key, pt, en, es").eq("is_removed",!1);if(s)return{};const r={};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&&(r[t.key]=a)}),this.cache[e]=r,this.cacheTimestamps.set(e,Date.now()),r}async upsertTranslation(e,t,a,s){const r=bs(),{error:n}=await r.schema("common").from("translations").upsert({key:e,pt:t,en:a,es:s},{onConflict:"key"});if(n)throw n;this.clearCache()}async bulkUpsertTranslations(e){const t=bs(),{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 Zo=Object.defineProperty,el=(e,t,a)=>((e,t,a)=>t in e?Zo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const tl="true"===(void 0).VITE_I18N_DEBUG_MODE;et.use(new class{constructor(e=!1){el(this,"type","backend"),el(this,"isDebugMode"),el(this,"cache",new Map),el(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 s=Yo.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,s),s.then(()=>{a(null,this.cache.get(e)||{})})}create(e,t,a,s){}}(tl)).use(Da).init({fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:(e,t)=>tl?`[${e} ❌]`:`[⚠️ ${e}]`});const al=t.createContext(void 0),sl=()=>{const e=t.useContext(al);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},rl=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],nl=[{value:"BRL",label:"Real (BRL)",symbol:"R$"},{value:"USD",label:"Dollar (USD)",symbol:"$"},{value:"EUR",label:"Euro (EUR)",symbol:"€"}],il=()=>{const{locale:t,currency:a,setLocale:s,setCurrency:r}=sl(),{t:n}=Ga();return e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(l.Globe,{className:"h-4 w-4"}),n("language")]}),e.jsxs(Ot,{value:t,onValueChange:s,children:[e.jsx(Mt,{children:e.jsx(Dt,{})}),e.jsx(Ut,{children:rl.map(t=>e.jsxs(qt,{value:t.value,children:[t.flag," ",t.label]},t.value))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(l.DollarSign,{className:"h-4 w-4"}),n("currency")]}),e.jsxs(Ot,{value:a,onValueChange:r,children:[e.jsx(Mt,{children:e.jsx(Dt,{})}),e.jsx(Ut,{children:nl.map(t=>e.jsxs(qt,{value:t.value,children:[t.symbol," ",t.label]},t.value))})]})]})]})},ol=t.memo(({variant:a="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:i,companies:o,alias:c,isAuthenticated:d,logout:u,switchUnit:m}=Zs(),[p,h]=t.useState(!1),f=o?.[0]||null,g=c?o?.find(e=>e.alias===c):f,x=o||[],b=r||g||f||f,v=t.useCallback(e=>{n?n(e):m(e)},[n,m]),y=t.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===b?.alias),s=t.filter(e=>e.alias!==b?.alias);return s.sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"})),a?[a,...s]:s},[x,b?.alias]);if(!d||!i)return null;const N=()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-5 w-5 text-primary-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e.jsx("div",{className:"mt-3",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:b.name})]})}),y.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",y.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[y.slice(0,3).map(t=>e.jsx(Qt,{variant:t.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(t),children:t.name},t.alias)),y.length>3&&e.jsxs(Qt,{variant:"outline",className:"text-xs",children:["+",y.length-3]})]})]})]});return"dropdown"===a?e.jsxs(Sr,{children:[e.jsx(Cr,{asChild:!0,children:e.jsx(nt,{variant:"ghost",className:`h-auto p-2 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:i.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e.jsx("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-4 w-4 text-primary-foreground"})}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(Rr,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs(Tr,{children:[e.jsxs(_r,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(Ir,{children:y.map(t=>e.jsxs(Lr,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e.jsx(Qt,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e.jsx(Mr,{}),e.jsxs(Lr,{onClick:()=>h(!0),children:[e.jsx(l.Settings,{className:"mr-2 h-4 w-4"}),"Preferências"]}),e.jsxs(Lr,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]}),e.jsx(gt,{open:p,onOpenChange:h,children:e.jsxs(Nt,{children:[e.jsx(jt,{children:e.jsx(kt,{children:"Preferências de Internacionalização"})}),e.jsx(il,{})]})})]}):e.jsxs(dt,{className:s,children:[e.jsx(ut,{children:e.jsx(mt,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(ht,{className:"space-y-4",children:[e.jsx(N,{}),e.jsx(Hi,{}),e.jsxs(nt,{variant:"outline",onClick:()=>h(!0),size:"sm",className:"w-full",children:[e.jsx(l.Settings,{className:"mr-2 h-4 w-4"}),"Preferências"]}),e.jsxs(nt,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]}),e.jsx(gt,{open:p,onOpenChange:h,children:e.jsxs(Nt,{children:[e.jsx(jt,{children:e.jsx(kt,{children:"Preferências de Internacionalização"})}),e.jsx(il,{})]})})]})]})}),ll=t.createContext({});function cl({children:a,config:s}){const r=t.useMemo(()=>({navigation:s?.navigation,appName:s?.appName}),[s?.navigation,s?.appName]);return e.jsx(ll.Provider,{value:r,children:a})}function dl(){return t.useContext(ll)}function ul(){const e=b.useLocation(),{navigation:t}=dl(),{t:a}=Ga();if(!t)return a("page");const s=t.find(t=>t.path===e.pathname);if(s)return s.label;const r=t.find(t=>e.pathname.startsWith(t.path+"/"));return r?.label||a("page")}function ml(e,a){const[s,r]=t.useState(e),n=t.useRef(),i=t.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return t.useEffect(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[s,i]}const pl=t.memo(function({actions:a}){const s=b.useLocation(),r=ul(),{navigation:n,appName:i}=dl(),{metadata:o,headerActions:c}=kn(),{t:d}=Ga(),{companies:u,alias:m,isSearchVisible:p,clearSearch:h,refreshData:f,switchUnit:g}=Zs(),x=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[v,y]=b.useSearchParams(),[N,j]=t.useState(()=>v.get("search")||""),[w,k]=ml(N,_s.debounceDelay);t.useEffect(()=>{if(!p)return;const e=new URLSearchParams(v);w?(e.set("search",w),e.set("page","1")):e.delete("search"),y(e)},[w,y,p]);const S=n?.find(e=>e.path===s.pathname)||n?.find(e=>s.pathname.startsWith(e.path+"/")),C=o.title||r,P=o.subtitle||S?.complementaryText||d("item_details");return e.jsx("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:C}),e.jsx(Qt,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:i||d("module")})]}),P&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:P})]}),p&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ot,{placeholder:d("search"),value:N,onChange:e=>(e=>{j(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e.jsx(nt,{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:()=>{k(),j("");const e=new URLSearchParams(v);e.delete("search"),e.delete("page"),y(e)},title:d("clear_search"),children:e.jsx(l.X,{size:14})})]}),e.jsx(nt,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:d("refresh_data"),children:e.jsx(l.RefreshCw,{size:14})})]}),e.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(c||a)&&e.jsx("div",{className:"flex items-center gap-2",children:c||a}),(void 0).VITE_WIKI_URL&&e.jsx(nt,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>tt((void 0).VITE_WIKI_URL,e),title:d("open_wiki"),children:"Wiki"}),e.jsx("div",{className:"text-sm",children:e.jsx(ol,{variant:"dropdown",selectedUnit:x,onUnitChange:g})})]})]})})}),hl=({key:e,enabled:t,checkFn:a,staleTime:s=3e5,gcTime:r=6e5})=>x.useQuery({queryKey:["permission",e],queryFn:a,enabled:t,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1}),fl=(e={})=>{const{enabled:t=!0}=e,{alias:a}=Zs();return x.useQuery({queryKey:["active-modules",a],queryFn:async()=>{if(!a)return[];const e=bs(),{data:t,error:s}=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(s){if(!ws.handleError(s))throw s;return[]}return t||[]},enabled:t&&!!a})},gl="forlogic-sidebar-pinned",xl=()=>{try{const e=localStorage.getItem(gl);return!!e&&JSON.parse(e)}catch{return!1}},bl=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]},vl=`https://${(void 0).VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,yl={logo:`${vl}/${Os.isQualiex?"logo-qualiex.svg":"logo.svg"}`,smallLogo:`${vl}/${Os.isQualiex?"small-forlogic.svg":"small.svg"}`},Nl=yl.logo,jl=yl.smallLogo;function wl({appName:t,isPinned:a,onPinToggle:s,open:r,dropdownOpen:n,onDropdownChange:i}){const{t:o}=Ga(),{data:c,isLoading:d,error:u}=fl({enabled:n}),m=e=>{((e,t)=>{const a=e?.find(e=>e.url===t);a?.url&&window.open(a.url,"_blank")})(c,e)};return e.jsxs(bo,{className:"p-0 gap-0",children:[e.jsx("div",{className:"flex items-center justify-between h-[34px]",children:r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center pl-[12px]",children:e.jsx("img",{src:yl.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e.jsx("button",{onClick:s,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(a?"bg-primary/20 text-primary":"hover:bg-muted text-muted-foreground"),children:e.jsx(l.PanelLeft,{className:"h-4 w-4"})})]}):e.jsx("div",{className:"flex items-center justify-center w-full h-[34px]",children:e.jsx("img",{src:yl.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e.jsx("div",{className:"mt-2 pt-0",children:e.jsxs(Sr,{onOpenChange:i,children:[e.jsx(Cr,{asChild:!0,children:r?e.jsxs("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:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("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.jsx("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:t})]}),e.jsx(l.ChevronDown,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e.jsx("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.jsx(l.ChevronDown,{className:"h-6 w-6 text-muted-foreground"})})}),e.jsx(Rr,{className:r?"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:r?"start":"center",children:d?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:o("loading")})]}):u?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:o("error")})]}):c&&0!==c.length?e.jsx("div",{className:"space-y-2",children:c.map((t,a)=>e.jsx("div",{onClick:()=>m(t.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${bl(a)} transition-colors duration-200\n `,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-foreground text-sm",children:t.name}),t.url&&e.jsx(l.ExternalLink,{className:"h-4 w-4 text-muted-foreground"})]})},t.id))}):e.jsx("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:o("no_results")})})]})})]})}function kl({direction:e="right",minWidth:a=224,maxWidth:s=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,c]=t.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[d,u]=t.useState(!1),m=t.useRef(null);t.useEffect(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","240px"))},[l,o]);const p=t.useCallback(e=>{e.preventDefault(),u(!0)},[]);return t.useEffect(()=>{if(!d)return;const t=t=>{let r;r="left"===e?window.innerWidth-t.clientX:t.clientX,r=Math.max(a,Math.min(s,r)),c(r),i?.(r)},r=()=>{u(!1),localStorage.setItem(n,l.toString())};return document.addEventListener("mousemove",t),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",r)}},[d,e,a,s,l,n,i]),t.useEffect(()=>{d?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[d,e]),{width:l,isDragging:d,dragRef:m,handleMouseDown:p}}const Sl=t.forwardRef(({className:t,onMouseDown:a,isDragging:s,...r},n)=>e.jsx("div",{ref:n,onMouseDown:a,className:at("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-['']",s&&"bg-primary/40",t),...r}));function Cl({config:a,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:i=384}={}){const{t:o}=Ga(),{open:c,setOpen:d}=uo(),u=b.useLocation(),{alias:m,user:p}=Zs(),[h,f]=t.useState(!1),[g,x]=t.useState(xl),[v,y]=t.useState(!1),N=t.useRef(!1),j=r?kl({minWidth:n,maxWidth:i,storageKey:"app-sidebar-width",isOpen:c}):null;t.useEffect(()=>{d(!!g||!(!v&&!h))},[g,v,h,d]);return e.jsxs(po,{collapsible:"icon",onMouseEnter:()=>{g||N.current||y(!0)},onMouseLeave:()=>{g||y(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:j&&c?{width:`${j.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e.jsx(wl,{appName:a?.appName||o("module_title"),isPinned:g,onPinToggle:()=>{const e=!g;x(e),(e=>{try{localStorage.setItem(gl,JSON.stringify(e))}catch{}})(e),e||(N.current=!0,y(!1),d(!1),setTimeout(()=>{N.current=!1},300))},open:c,dropdownOpen:h,onDropdownChange:f}),e.jsx(No,{children:s||e.jsx(jo,{className:"p-0 mt-6",children:e.jsx(So,{children:e.jsx(Co,{className:"space-y-2",children:e.jsx(ro,{children:a?.navigation?.map((t,a)=>{const s=({item:t,index:a})=>{const r=`${t.path}-${a}-${m??"noalias"}-${p?.id??"nouser"}`,{data:n=!0,isLoading:i}=hl({key:r,enabled:Boolean(t.permissionCheck&&m&&p?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),c=t.permissionCheck&&!n;if(c&&"Admin"===t.label)return null;const d=i?l.Loader2:c?l.Lock:t.icon;c?o("restricted_access"):t.complementaryText;return t.children&&t.children.length>0?e.jsx(ui,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Po,{children:[e.jsx(mi,{asChild:!0,children:e.jsx(To,{size:"lg",className:"h-10",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e.jsx(pi,{children:e.jsx(Ro,{children:t.children.map((t,a)=>e.jsx(s,{item:t,index:a},t.path))})})]})},t.path):e.jsx(Po,{children:c||i?e.jsxs(no,{children:[e.jsx(io,{asChild:!0,children:e.jsx(To,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-4 w-4 "+(i?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})}),e.jsx(oo,{children:e.jsx("p",{children:o(i?"checking_access":"restricted_access")})})]}):e.jsx(To,{asChild:!0,isActive:(h=t.path,u.pathname===h||u.pathname.startsWith(h+"/")),size:"lg",className:"h-10",children:e.jsxs(b.Link,{to:t.path,className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(d,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})},t.path);var h};return e.jsx(s,{item:t,index:a},t.path)})})})})})}),r&&j&&c&&e.jsx(Sl,{ref:j.dragRef,onMouseDown:j.handleMouseDown,isDragging:j.isDragging})]})}Sl.displayName="ResizableRail";const Pl=t.memo(function({children:a,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const i=t.useMemo(()=>s||e.jsx(Cl,{config:r}),[s,r]),o=t.useMemo(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e.jsx(cl,{config:r,children:e.jsx(wn,{children:e.jsx(mo,{defaultOpen:!1,style:o,children:e.jsxs("div",{className:"sidebar-container min-h-screen flex w-full",children:[i,e.jsxs("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e.jsx("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e.jsx(pl,{})}),e.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:a})]})]})})})})});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,t+"",a);class Al extends t.Component{constructor(e){super(e),Tl(this,"copyErrorDetails",()=>{const e=us.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),ra({title:"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((void 0).DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,t){if((void 0).DEV)throw e;us.handleError(e,!1),this.setState({errorInfo:t})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=us.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(dt,{className:"w-full max-w-2xl",children:[e.jsxs(ut,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-destructive"})}),e.jsx(mt,{children:"Algo deu errado"})]}),e.jsxs(ht,{className:"space-y-4",children:[e.jsx("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),e.jsxs(ui,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(mi,{asChild:!0,children:e.jsxs(nt,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),e.jsxs(pi,{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsx("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e.jsx(Qr,{className:"h-32 w-full rounded border bg-muted p-2",children:e.jsx("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e.jsx("div",{className:"space-y-2",children:t.map((t,a)=>e.jsx("div",{className:"text-sm p-2 rounded bg-muted/50",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"font-medium text-muted-foreground shrink-0",children:[a+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),e.jsxs(nt,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.Copy,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e.jsx(nt,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const _l={"pt-BR":ci,"en-US":Xn,"es-ES":si},Il=(e,t="pt-BR")=>{if(!e)return"";const a=i.parseISO(e);if(!i.isValid(a))return"Invalid date";const s=_l[t]||ci;return i.format(a,"PP",{locale:s})};class Rl{static async sendEmail(e){const t=bs(),{data:a,error:s}=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(s)throw s;return a}}const Ll=Rl;function Ol(){const[e,a]=t.useState([]),[s,r]=t.useState(!1),[n,i]=t.useState(null),[l,c]=t.useState(null);t.useEffect(()=>{d()},[]);const d=async()=>{try{const e=bs(),{data:t,error:s}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(s)throw s;i(t.threadId),a([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){c("Erro ao inicializar conversa"),o.toast.error("Erro ao inicializar conversa")}};return{messages:e,isLoading:s,error:l,sendMessage:t.useCallback(async e=>{if(!n||!e.trim())return;const t={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};a(e=>[...e,t]),r(!0),c(null);try{const t=bs(),{data:s,error:r}=await t.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:n,message:e}});if(r)throw r;const{runId:i}=s,o=await(async e=>{if(!n)return!1;for(let a=0;a<60;a++)try{const t=bs(),{data:a,error:s}=await t.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:n,runId:e}});if(s)throw s;const{status:r}=a;if("completed"===r)return!0;if("failed"===r||"cancelled"===r)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(n)try{const e=bs(),{data:t,error:s}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:n}});if(s)throw s;const r=t.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));a(r)}catch(e){throw e}})()}catch(s){const e=s instanceof Error?s.message:"Erro ao enviar mensagem";c(e),o.toast.error(e),a(e=>e.filter(e=>e.id!==t.id))}finally{r(!1)}},[n]),threadId:n}}function Fl({content:t,className:a}){return e.jsx("div",{className:at("prose prose-sm max-w-none",a),children:e.jsx(D,{remarkPlugins:[M],components:{h1:({children:t})=>e.jsx("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:t}),h2:({children:t})=>e.jsx("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:t}),h3:({children:t})=>e.jsx("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:t}),p:({children:t})=>e.jsx("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:t}),ul:({children:t})=>e.jsx("ul",{className:"list-disc list-inside mb-2 space-y-1",children:t}),ol:({children:t})=>e.jsx("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:t}),li:({children:t})=>e.jsx("li",{className:"text-sm text-foreground",children:t}),code:({inline:t,children:a,...s})=>t?e.jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...s,children:a}):e.jsx("code",{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...s,children:a}),pre:({children:t})=>e.jsx("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:t}),a:({children:t,href:a})=>e.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:t}),blockquote:({children:t})=>e.jsx("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:t}),strong:({children:t})=>e.jsx("strong",{className:"font-bold text-foreground",children:t}),em:({children:t})=>e.jsx("em",{className:"italic text-foreground",children:t})},children:t})})}function Dl({open:a,onOpenChange:s,placeId:r,placeName:n,onMakeManager:i,onMakeMembers:o,currentManagerId:c,currentMemberIds:d=[]}){const{t:u}=Ga(),[m,p]=t.useState([]),[h,f]=t.useState(!1),[g,x]=t.useState(""),{data:b=[],isLoading:v}=Yr({enabled:a}),y=t.useMemo(()=>{let e=[...b];if(e.sort((e,t)=>{const a=e.userName?.toLowerCase()||"",s=t.userName?.toLowerCase()||"";return a.localeCompare(s)}),g){const t=g.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(t)||e.userEmail?.toLowerCase().includes(t))}return e},[b,g]),N=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},j=1===m.length,w=m.length>0;return e.jsx(gt,{open:a,onOpenChange:s,children:e.jsxs(Nt,{className:"max-w-2xl",children:[e.jsx(jt,{children:e.jsxs(kt,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ot,{placeholder:u("search_placeholder"),value:g,onChange:e=>x(e.target.value),className:"pl-9"})]}),e.jsx(Qr,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((t,a)=>e.jsx(Sa,{className:"h-16 w-full"},a))}):0===y.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(l.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:y.map(t=>{const a=t.userId===c,s=d.includes(t.userId||""),r=m.includes(t.userId||"");return e.jsxs("div",{className:at("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(t.userId||""),children:[e.jsx(Wt,{checked:r,onCheckedChange:()=>N(t.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:t.userName}),a&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(a||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:a?"Gestor":"Membro"})]},t.userId)})})}),e.jsxs(wt,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:m.length>0&&e.jsxs("span",{children:[m.length," selecionado(s)"]})}),j&&i&&e.jsxs(nt,{onClick:async()=>{if(i&&1===m.length){f(!0);try{await i(m[0],r),p([])}finally{f(!1)}}},disabled:h,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),w&&o&&e.jsxs(nt,{onClick:async()=>{if(o&&0!==m.length){f(!0);try{await o(m,r),p([])}finally{f(!1)}}},disabled:h,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function Ml({place:a,level:s=0,manageAccessConfig:r}){const[n,i]=t.useState(!1),[o,c]=t.useState(!1),d=a.subPlaces&&a.subPlaces.length>0,u=a.isActive??!0,m=a.usersCount??0;return e.jsxs("div",{children:[e.jsxs(ui,{open:n,onOpenChange:i,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*s+1+"rem"},children:[d?e.jsxs(mi,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:at("h-4 w-4 transition-transform shrink-0",n&&"rotate-90")}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:a.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",a.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:a.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m})]}),e.jsx(Qt,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(Ko,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),d&&e.jsx(pi,{children:a.subPlaces.map(t=>e.jsx(Ml,{place:t,level:s+1,manageAccessConfig:r},t.id))})]}),0===s&&e.jsx(Hi,{}),r&&e.jsx(Dl,{open:o,onOpenChange:c,placeId:a.id,placeName:a.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(a.id),currentMemberIds:r.getCurrentMemberIds?.(a.id)})]})}var zl=Object.defineProperty,$l=(e,t,a)=>((e,t,a)=>t in e?zl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const Ul=new class{constructor(){$l(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const s=Ss.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=ls.getAccessToken();if(!r)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 ${r}`,"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 s=t.get(e.id);if(e.parentId){const r=t.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):a.push(s)}else a.push(s)}),a}async getPlaces(e,t){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(a){if(await Ss.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(s){return us.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return us.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};function Vl(e){const t=new Map,a=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};t.set(e.id,s),a.set(e.id_user,s)}),e.forEach(e=>{const r=t.get(e.id);if(e.id_leader){const t=a.get(e.id_leader);if(t)return void t.children.push(r)}s.push(r)});const r=(e,t)=>{e.level=t,e.children.forEach(e=>r(e,t+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,t)=>{const a=e.name||e.id_user||e.email||"",s=t.name||t.id_user||t.email||"";return a.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function ql(e){const t=[],a=e=>{t.push(e),e.children.forEach(a)};return e.forEach(a),t}function Bl(){const{alias:e,isAuthenticated:t}=Zs(),a=ls.getAccessToken(),{data:s=[]}=Yr({enabled:!0});return x.useQuery({queryKey:["leadership",e,s.length],queryFn:async()=>{if(!a||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=bs(),{data:r,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(!r||0===r.length)return[];const i={};s.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=r.map(e=>({...e,name:i[e.id_user]?.name||e.id_user,email:i[e.id_user]?.email||"",subordinatesCount:r.filter(t=>t.id_leader===e.id_user).length})),l=new Set(r.map(e=>e.id_user));return new Set(r.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:r[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||e,email:t?.email||"",subordinatesCount:r.filter(t=>t.id_leader===e).length})}),Vl(o)},enabled:!!a&&!!e&&t&&s.length>0})}function Wl(){const e="common",{alias:t}=Zs(),a=x.useQueryClient(),s=bs();return x.useMutation({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 Xl(s,t,e,a.id_user,a.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success("Líder virtual promovido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao criar líder")}})}function Hl(){const e="common",{alias:t}=Zs(),a=x.useQueryClient(),s=bs();return x.useMutation({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 r=a.users.map(e=>e.id_user),{data:n}=await s.schema(e).from("leaders").select("id_user").eq("alias",t).in("id_user",r).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 c of a.users){if(c.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");await Xl(s,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 s.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{o.toast.error(e.message||"Erro ao adicionar liderados")}})}function Kl(){const e="common",{alias:t}=Zs(),a=x.useQueryClient(),s=bs();return x.useMutation({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");const{data:r}=await s.schema(e).from("leaders").select("id_user").eq("id",a.id).eq("alias",t).single();if(!r)throw new Error("Líder não encontrado");if(r.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await Xl(s,t,e,r.id_user,a.id_leader,a.id);const{data:n,error:i}=await s.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]}),o.toast.success("Líder atualizado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao atualizar líder")}})}function Ql(){const{alias:e}=Zs(),t=x.useQueryClient(),a=bs();return x.useMutation({mutationFn:async t=>{if(!e)throw new Error("Unidade não selecionada");const{error:s}=await a.schema("common").from("leaders").update({is_removed:!0}).eq("id",t).eq("alias",e);if(s)throw s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",e]}),o.toast.success("Líder removido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao remover líder")}})}function Gl(){const e="common",{alias:t}=Zs(),a=x.useQueryClient(),s=bs();return x.useMutation({mutationFn:async({leaderUserId:a,selectedUsers:r})=>{if(!t)throw new Error("Unidade não selecionada");const n=r.map(e=>e.id_user),i=await Promise.all([s.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).eq("id_leader",a),s.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:c,error:d}]=i;if(l)throw l;if(d)throw d;const u=o||[],m=c||[],p=new Set(n),h=u.filter(e=>!p.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),x=r.filter(e=>!g.has(e.id_user));for(const y of f)await Xl(s,t,e,y.id_user,a,y.id);for(const y of x){if(y.id_user===a)throw new Error("Usuário não pode ser seu próprio líder");await Xl(s,t,e,y.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:null}).in("id",a).eq("alias",t))}if(f.length){const r=f.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:a}).in("id",r).eq("alias",t))}if(x.length){const r=x.map(e=>({alias:t,id_user:e.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(s.schema(e).from("leaders").insert(r))}const v=(await Promise.all(b)).find(e=>e?.error);if(v?.error)throw v.error;return{unlinked:h.length,updated:f.length,created:x.length}},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{o.toast.error(e.message||"Erro ao sincronizar subordinados")}})}async function Xl(e,t,a,s,r,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,c=new Set;let d=r;for(;d;){if(c.has(d))throw new Error("Esta associação criaria um ciclo na hierarquia");if(d===s)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 Jl({leader:t,expandedIds:a,onToggleExpand:s,onEdit:r}){const n=a.has(t.id),i=t.children.length>0,o=32*t.level;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4",children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${o}px`},children:[i?e.jsx("button",{onClick:()=>s(t.id),className:"p-1 hover:bg-accent rounded",children:n?e.jsx(l.ChevronDown,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})}):e.jsx("div",{className:"w-6"}),e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("button",{onClick:()=>{r(t)},className:"font-medium hover:text-primary hover:underline text-left",children:t.name||t.id_user||t.email})]})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsx("span",{className:"text-sm",children:t.subordinatesCount||0})})]}),i&&n&&t.children.map(t=>e.jsx(Jl,{leader:t,expandedIds:a,onToggleExpand:s,onEdit:r},t.id))]})}var Yl=function(e,t){for(var a={};e.length;){var s=e[0],r=s.code,n=s.message,i=s.path.join(".");if(!a[i])if("unionErrors"in s){var o=s.unionErrors[0].errors[0];a[i]={message:o.message,type:o.code}}else a[i]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=a[i].types,c=l&&l[s.code];a[i]=u.appendErrors(i,t,a,r,c?[].concat(c,s.message):s.message)}e.shift()}return a},Zl=function(e,t,a){return void 0===a&&(a={}),function(s,r,n){try{return Promise.resolve(function(r,i){try{var o=Promise.resolve(e["sync"===a.mode?"parse":"parseAsync"](s,t)).then(function(e){return n.shouldUseNativeValidation&&$.validateFieldsNatively({},n),{errors:{},values:a.raw?s: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:$.toNestErrors(Yl(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const ec=z.z.object({id_leader:z.z.string().nullable(),id_users:z.z.array(z.z.string()).min(1,"Selecione pelo menos um liderado")}),tc=z.z.object({id_leader:z.z.string().nullable(),id_users:z.z.array(z.z.string())});function ac({value:a,onChange:s,excludeUserIds:r=[],error:n}){const{data:i=[],isLoading:o}=Yr(),[c,d]=t.useState(""),u=t.useRef(null),m=t.useRef(0),{t:p}=Ga(),h=i.filter(e=>!r.includes(e.userId||"")).filter(e=>{const t=c.toLowerCase(),a=e.userName?.toLowerCase().includes(t);return a}).sort((e,t)=>{const s=a.includes(e.userId),r=a.includes(t.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",i=t.userName||t.userEmail||"";return n.localeCompare(i)});return t.useEffect(()=>{u.current&&m.current>0&&(u.current.scrollTop=m.current)},[h]),o?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin"}),e.jsx("span",{className:"ml-2",children:p("loading_data")})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ot,{placeholder:p("search_user"),value:c,onChange:e=>d(e.target.value)}),e.jsx("div",{ref:u,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===h.length?e.jsx("p",{className:"text-sm text-muted-foreground",children:p("search_user")}):e.jsx("div",{className:"space-y-2",children:h.map(t=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Wt,{id:t.userId,checked:a.includes(t.userId),onCheckedChange:()=>{return e=t.userId,u.current&&(m.current=u.current.scrollTop),void(a.includes(e)?s(a.filter(t=>t!==e)):s([...a,e]));var e}}),e.jsx(ct,{htmlFor:t.userId,className:"flex-1 cursor-pointer",children:t.userName||t.userEmail})]},t.userId))})}),a.length>0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p("selected_count",{count:a.length})}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function sc({leader:a,prefilledLeaderId:s,onSuccess:r}){const{t:n}=Ga(),{alias:i}=Zs(),o=!!a,c=a?.id.startsWith("virtual-"),d=Hl(),m=Wl(),p=Kl(),h=Gl(),f=Ql(),{data:g=[]}=Bl(),{data:x=[]}=Yr(),[b,v]=t.useState(""),y=ql(g).map(e=>e.id_user),N=o?ql(g).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user):[],j=u.useForm({resolver:Zl(o?tc:ec),defaultValues:{id_leader:s||(o?a?.id_leader:null)||null,id_users:o?N:[]}});t.useEffect(()=>{if(a){const e=ql(g).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user);j.reset({id_leader:a.id_leader||null,id_users:e})}else s?j.reset({id_leader:s,id_users:[]}):j.reset({id_leader:null,id_users:[]})},[i,a?.id,a?.id_user,a?.id_leader,s,g]);const w=d.isPending||m.isPending||p.isPending||h.isPending||f.isPending,k=j.watch("id_leader"),S=j.watch("id_users"),C=o?[a.id_user,...y.filter(e=>e!==a.id_user&&!S.includes(e)&&!N.includes(e))]:[k,...y.filter(e=>!S.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:j.handleSubmit(async e=>{try{if(o)if(c){await m.mutateAsync({id_user:a.id_user,id_leader:e.id_leader});const t=x.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await h.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{await p.mutateAsync({id:a.id,id_leader:e.id_leader});const t=x.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await h.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{const t=x.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await d.mutateAsync({id_leader:e.id_leader,users:t})}r?.()}catch(t){}}),className:"space-y-4",children:[o&&e.jsxs("div",{children:[e.jsx(ct,{children:n("leader")}),e.jsx(ot,{value:x.find(e=>e.userId===a.id_user)?.userName||a.name||a.id_user,disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(ct,{children:n("superior")}),e.jsxs(Ot,{value:k||"none",onValueChange:e=>j.setValue("id_leader","none"===e?null:e),children:[e.jsx(Mt,{children:e.jsx(Dt,{placeholder:n("select_placeholder")})}),e.jsxs(Ut,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(ot,{placeholder:n("superior_search"),value:b,onChange:e=>v(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(Qr,{className:"h-[200px]",children:[e.jsx(qt,{value:"none",children:n("form.superiorNone")}),x.filter(e=>{const t=o?e.userId!==a.id_user:!S.includes(e.userId),s=!b||e.userName?.toLowerCase().includes(b.toLowerCase());return t&&s}).sort((e,t)=>{const a=e.userName||e.userEmail||"",s=t.userName||t.userEmail||"";return a.localeCompare(s)}).map(t=>e.jsx(qt,{value:t.userId,children:t.userName},t.userId))]})]})]},`superior-select-${i}`),j.formState.errors.id_leader&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:j.formState.errors.id_leader.message})]}),e.jsxs("div",{children:[e.jsxs(ct,{children:[n("subordinates")," *"]}),e.jsx(ac,{value:S,onChange:e=>j.setValue("id_users",e),excludeUserIds:C,error:j.formState.errors.id_users?.message},`users-multiselect-${i}`)]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(nt,{type:"submit",disabled:w||!o&&0===S.length,children:w&&!f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),n(o?"updating":"saving")]}):o?S.length>0?n("update_success",{count:S.length}):n("update"):n("create_success",{count:S.length})}),o&&!k&&0===S.length&&e.jsx(nt,{type:"button",variant:"destructive",disabled:w,onClick:async()=>{if(a&&window.confirm(n("remove_confirm")))try{await f.mutateAsync(a.id),r?.()}catch(e){}},className:"ml-auto",children:f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),n("removing")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Trash2,{className:"mr-2 h-4 w-4"}),n("remove")]})})]})]})}function rc({open:t,onOpenChange:a,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(gt,{open:t,onOpenChange:a,children:e.jsxs(Nt,{className:"sm:max-w-[500px]",children:[e.jsx(jt,{children:e.jsx(kt,{children:n})}),e.jsx(sc,{leader:s,prefilledLeaderId:r,onSuccess:()=>a(!1)})]})})}const nc="leadership-expanded-nodes",ic=(e,t)=>{try{localStorage.setItem(`${nc}-${e}`,JSON.stringify(Array.from(t)))}catch(a){}};function oc(e){const[a,s]=t.useState(!1),[r,n]=t.useState(0),{t:i}=Ga(),{uploadFunction:o,deleteFunction:l,defaultOptions:c,onSuccess:d,onError:u}=e||{};return{upload:async(e,t)=>{if(!o){const e=new Error("uploadFunction não fornecida");throw ra({title:"Erro de configuração",description:"Função de upload não configurada. Verifique a documentação.",variant:"destructive"}),e}s(!0),n(0);try{const a={...c,...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 s=await o(e,a);return n(100),ra({title:"Sucesso",description:i("file_upload_success")}),d?.(s),s}catch(a){const e=a instanceof Error?a:new Error("Erro ao fazer upload");throw ra({title:"Erro",description:e.message,variant:"destructive"}),u?.(e),e}finally{s(!1)}},deleteMedia:async(e,t)=>{if(!l){const e=new Error("deleteFunction não fornecida");throw ra({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await l(e,t),ra({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(a){throw ra({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),a}},uploading:a,progress:r}}function lc(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 cc(e,t){const a=lc(e);if(!a)return e;return`https://www.youtube.com/embed/${a}${t?"?autoplay=1&mute=1":""}`}function dc(e){const t=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function uc(e,t){const a=dc(e);if(!a)return e;return`https://player.vimeo.com/video/${a}${t?"?autoplay=1&muted=1":""}`}function mc(e){if(!e)return;const t=e.match(/src="([^"]+)"/);return t?t[1]:void 0}function pc(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function hc(e,t){return e/t}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return o.toast}}),exports.AUTH_CONFIG=Ts,exports.Accordion=Sn,exports.AccordionContent=En,exports.AccordionItem=Cn,exports.AccordionTrigger=Pn,exports.ActionButton=it,exports.ActionMenu=Ko,exports.ActionMenuItems=$r,exports.Alert=vn,exports.AlertDescription=Nn,exports.AlertDialog=tr,exports.AlertDialogAction=dr,exports.AlertDialogCancel=ur,exports.AlertDialogContent=nr,exports.AlertDialogDescription=cr,exports.AlertDialogFooter=or,exports.AlertDialogHeader=ir,exports.AlertDialogOverlay=rr,exports.AlertDialogPortal=sr,exports.AlertDialogTitle=lr,exports.AlertDialogTrigger=ar,exports.AlertTitle=yn,exports.AppHeader=pl,exports.AppLayout=Pl,exports.AppSidebar=Cl,exports.AspectRatio=Tn,exports.AuthErrorInterceptor=ws,exports.AuthProvider=({children:a})=>{const[s,r]=t.useState({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=x.useQueryClient()}catch{}const[i,o]=t.useState(!1),[l,c]=t.useState(0),d=t.useCallback(e=>{r(t=>({...t,...e}))},[]),u=t.useCallback(e=>{r(t=>({...t,isLoading:e}))},[]),m=t.useCallback(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=t.useCallback(async e=>{try{u(!0);const a=ls.getAccessToken();if(!a)return;const r=await vs.generateToken(a,e.alias,void 0,!0);if(!r)return;ls.setSupabaseToken(r),ls.setSelectedAlias(e.alias);const i=ls.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||ls.getCompanyId(e.alias),c={id:l||e.id,name:e.name,alias:o};let m=null,p=null;if(s.user?.id&&o&&l)try{const e=(await Es.fetchActiveUsersMap(o,l)).get(s.user.id);if(e){const t=Gs(e);m=t.placeId,p=t.placeName}}catch(t){}d({alias:o,selectedUnit:c,placeId:m,placeName:p,activePlaceId:m,activePlaceName:p}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(t){}finally{u(!1)}},[d,n,u,s.user]),h=t.useCallback(async()=>await Js.processCallback(),[]),f=t.useCallback(async()=>{Js.logout(),m(),n&&await n.clear()},[m,n]),g=t.useCallback(e=>{o(e)},[]),b=t.useCallback(()=>{c(e=>e+1)},[]),v=t.useCallback(()=>{c(e=>e+1)},[]);t.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const t=setInterval(()=>{e&&(ls.areAllTokensValid()||e&&f())},6e5);return()=>{e=!1,clearInterval(t)}},[s.isAuthenticated,f]),t.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const t=await Js.initialize();if(!e)return;t&&t.isAuthenticated?d({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&&u(!1)}catch(t){e&&(ws.handleError(t),u(!1))}})(),()=>{e=!1}},[d,u,f]);const y=t.useMemo(()=>({...s,logout:f,processCallback:h,switchUnit:p,availableUnits:s.companies,isSearchVisible:i,setSearchVisible:g,clearSearch:b,refreshData:v}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,f,h,p,i,g,b,v]);return e.jsx(Ys.Provider,{value:y,children:a})},exports.AuthService=Js,exports.Avatar=An,exports.AvatarFallback=In,exports.AvatarImage=_n,exports.Badge=Qt,exports.BaseForm=en,exports.Blockquote=Ri,exports.Breadcrumb=Rn,exports.BreadcrumbEllipsis=zn,exports.BreadcrumbItem=On,exports.BreadcrumbLink=Fn,exports.BreadcrumbList=Ln,exports.BreadcrumbPage=Dn,exports.BreadcrumbSeparator=Mn,exports.BulkActionBar=sn,exports.Button=nt,exports.ButtonGroup=Un,exports.CRUD_CONFIG=As,exports.Calendar=di,exports.CallbackPage=()=>{const{processCallback:a}=Zs(),[s,r]=t.useState(null),[n,i]=t.useState(!1);t.useEffect(()=>{(async()=>{try{if(await a()){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 r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[a]);const o=async()=>{i(!0),r(null);try{await a()||r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},c=()=>{window.location.href="/"};return s?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(dt,{className:"w-full max-w-md",children:[e.jsx(ut,{className:"text-center",children:e.jsxs(mt,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e.jsx(l.AlertCircle,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),e.jsxs(ht,{className:"space-y-4",children:[e.jsx(vn,{variant:"destructive",children:e.jsx(Nn,{children:s})}),e.jsx("div",{className:"text-sm text-muted-foreground",children:e.jsx("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(nt,{onClick:o,disabled:n,className:"flex-1",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Xt,{size:"sm",className:"mr-2"}),"Tentando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.RefreshCw,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e.jsx(nt,{onClick:c,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(dt,{className:"w-full max-w-md",children:[e.jsx(ut,{className:"text-center",children:e.jsx(mt,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(ht,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(Xt,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=dt,exports.CardContent=ht,exports.CardDescription=pt,exports.CardFooter=ft,exports.CardHeader=ut,exports.CardSkeleton=jr,exports.CardTitle=mt,exports.Cards=function({data:t,renderCard:a,isLoading:s=!1,emptyMessage:r="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return s?e.jsx(xi,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((t,a)=>e.jsx(Sa,{className:"h-48 w-full"},a))}):0===t.length?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:r})})}):e.jsx(xi,{cols:n?String(n):"auto-fit",gap:i,className:o,children:t.map(a)})},exports.ChatbotPage=function(){const{t:a}=Ga(),[s,r]=t.useState(!1),[n,i]=t.useState(""),{messages:o,isLoading:c,error:d,sendMessage:u}=Ol(),m=t.useRef(null),p=t.useRef(null);t.useEffect(()=>{if(m.current){const e=m.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[o]),t.useEffect(()=>{s&&p.current&&p.current.focus()},[s]),t.useEffect(()=>{const e=e=>{"Escape"===e.key&&s&&r(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[s]);const h=()=>{n.trim()&&!c&&(u(n),i(""))};return e.jsxs(e.Fragment,{children:[e.jsx(nt,{onClick:()=>r(!s),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:s?e.jsx(l.X,{className:"h-6 w-6"}):e.jsx(l.MessageCircle,{className:"h-6 w-6"})}),s&&e.jsxs(dt,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[e.jsxs(ut,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsx(mt,{className:"text-lg font-semibold",children:a("title")}),e.jsx(nt,{variant:"ghost",size:"icon",onClick:()=>r(!1),className:"h-8 w-8",children:e.jsx(l.X,{className:"h-4 w-4"})})]}),e.jsxs(ht,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e.jsx(Qr,{ref:m,className:"flex-1 px-4",children:e.jsxs("div",{className:"space-y-4 py-4",children:[o.map(t=>e.jsx("div",{className:"flex "+("user"===t.role?"justify-end":"justify-start"),children:e.jsx("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.jsx(Fl,{content:t.content}):e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.content})})},t.id)),c&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-muted rounded-lg px-4 py-2",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),d&&e.jsx("div",{className:"text-center text-sm text-destructive py-2",children:d})]})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(ot,{ref:p,value:n,onChange:e=>i(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),h())},placeholder:a("placeholder"),disabled:c,className:"flex-1"}),e.jsx(nt,{onClick:h,disabled:c||!n.trim(),size:"icon",children:e.jsx(l.Send,{className:"h-4 w-4"})})]})})]})]})]})},exports.Checkbox=Wt,exports.Collapsible=ui,exports.CollapsibleContent=pi,exports.CollapsibleTrigger=mi,exports.ColorPicker=Kr,exports.Combobox=Ya,exports.Command=xa,exports.CommandDialog=({children:t,...a})=>e.jsx("div",{...a,children:e.jsx(xa,{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})}),exports.CommandEmpty=ya,exports.CommandGroup=Na,exports.CommandInput=ba,exports.CommandItem=wa,exports.CommandList=va,exports.CommandSeparator=ja,exports.CommandShortcut=ka,exports.CrudCards=function({manager:t,config:a,onEdit:s,onDelete:r}){const{t:n}=Ga();return t.isLoading?e.jsx(xi,{children:Array.from({length:3}).map((t,a)=>e.jsxs(dt,{children:[e.jsxs(ut,{children:[e.jsx(Sa,{className:"h-4 w-3/4"}),e.jsx(Sa,{className:"h-3 w-1/2"})]}),e.jsx(ht,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Sa,{className:"h-3 w-full"}),e.jsx(Sa,{className:"h-3 w-2/3"})]})})]},a))}):e.jsx(hi.Root,{children:t.entities.map(t=>e.jsxs(hi.Item,{onClick:()=>s(t),children:[e.jsx(ut,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(mt,{className:"text-base leading-6 truncate",children:t.title||t.name||n("no_title")}),e.jsx(pt,{className:"text-sm",children:i.format(new Date(t.created_at),"dd/MM/yyyy HH:mm",{locale:ci})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-2",children:[t.link&&e.jsx(nt,{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),o.toast.info(n("link_copied")))}catch(t){window.location.href=e}})(t.link)},title:n("open_external_link"),children:e.jsx(l.ExternalLink,{className:"h-4 w-4"})}),e.jsx("div",{onClick:e=>e.stopPropagation(),children:e.jsx(Ur,{onEdit:()=>s(t),onDelete:r?()=>r(t):void 0,canDelete:!!r})})]})]})}),e.jsx(ht,{className:"pt-0",children:e.jsx("div",{className:"space-y-2",children:a.cardFields?.map(a=>{const s=t[a.key];return s?e.jsx(hi.Field,{label:a.label,value:a.render?a.render(s,t):String(s)},String(a.key)):null})})})]},t.id))})},exports.CrudPageInternal=dn,exports.CrudPagination=an,exports.CrudPrimitiveFilterBar=function({searchValue:t="",onSearchChange:a,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:i="horizontal"}){const{t:o}=Ga(),c=t||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===i?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[a&&e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ot,{type:"text",placeholder:o("search"),value:t,onChange:e=>a(e.target.value),className:"pl-9 h-9"})]}),s.map((t,a)=>e.jsx("div",{className:"vertical"===i?"w-full":"",children:t},a)),n&&c&&r&&e.jsxs(nt,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[e.jsx(l.X,{size:14,className:"mr-1"}),o("clear_filters")]})]})},exports.CrudPrimitivePagination=tn,exports.CrudPrimitiveTable=function({data:a,columns:s,sortField:r,sortDirection:n,onSort:i,onRowClick:o,renderActions:c,isLoading:d=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:p=!1,selectedIds:h=[],onSelectItem:f,onSelectAll:g,isAllSelected:x=!1}){const b=t.useMemo(()=>{const e=s.reduce((e,t)=>t.width?e:e+(t.weight??1),0);return s.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}%`})},[s]);return d?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((t,a)=>e.jsx(Sa,{className:"h-12 w-full"},a))})}):0===a.length?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:u})})}):e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(pr,{className:m,children:[e.jsx(hr,{className:"sticky top-0 bg-background z-10",children:e.jsxs(xr,{children:[p&&e.jsx(br,{className:"w-[40px]",children:e.jsx(Wt,{checked:x,onCheckedChange:g,"aria-label":"Selecionar todos"})}),s.map((t,a)=>{return e.jsx(br,{className:t.className,style:{width:b[a]},children:t.sortable&&i?e.jsxs("button",{onClick:()=>i(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(s=String(t.key),r!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===n?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}):e.jsx("span",{className:"font-medium",children:t.header})},String(t.key));var s}),c&&e.jsx(br,{className:"w-[80px] text-right",children:"Ações"})]})}),e.jsx(fr,{children:a.map(t=>e.jsxs(xr,{onClick:()=>o?.(t),className:o?"cursor-pointer":"",children:[p&&e.jsx(vr,{children:e.jsx(Wt,{checked:h.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${t.id}`})}),s.map(a=>e.jsx(vr,{className:a.className,children:a.render?a.render(t):String(t[a.key]??"-")},String(a.key))),c&&e.jsx(vr,{className:"text-right",onClick:e=>e.stopPropagation(),children:c(t)})]},t.id))})]})})},exports.CrudTable=Br,exports.DataList=hi,exports.DatePicker=function({date:t,onDateChange:a,placeholder:s="Pick a date",disabled:r=!1,className:n,disabledDates:o}){return e.jsxs(ha,{children:[e.jsx(fa,{asChild:!0,children:e.jsxs(nt,{variant:"outline",disabled:r,className:at("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",n),children:[e.jsx(l.Calendar,{className:"mr-2 h-4 w-4"}),t?i.format(t,"PPP"):e.jsx("span",{children:s})]})}),e.jsx(ga,{className:"w-auto p-0",align:"start",children:e.jsx(di,{mode:"single",selected:t,onSelect:a,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})},exports.DeleteConfirmationDialog=mr,exports.Dialog=gt,exports.DialogClose=vt,exports.DialogContent=Nt,exports.DialogDescription=St,exports.DialogFooter=wt,exports.DialogHeader=jt,exports.DialogOverlay=yt,exports.DialogPortal=bt,exports.DialogTitle=kt,exports.DialogTrigger=xt,exports.DropdownMenu=Sr,exports.DropdownMenuCheckboxItem=Or,exports.DropdownMenuContent=Rr,exports.DropdownMenuGroup=Pr,exports.DropdownMenuItem=Lr,exports.DropdownMenuLabel=Dr,exports.DropdownMenuPortal=Er,exports.DropdownMenuRadioGroup=Ar,exports.DropdownMenuRadioItem=Fr,exports.DropdownMenuSeparator=Mr,exports.DropdownMenuShortcut=zr,exports.DropdownMenuSub=Tr,exports.DropdownMenuSubContent=Ir,exports.DropdownMenuSubTrigger=_r,exports.DropdownMenuTrigger=Cr,exports.EmailService=Rl,exports.EmptyState=kr,exports.EntitySelect=Ya,exports.ErrorBoundary=Al,exports.FilterBar=cn,exports.Form=Ct,exports.FormControl=It,exports.FormDescription=Rt,exports.FormField=({...t})=>e.jsx(Pt.Provider,{value:{name:t.name},children:e.jsx(u.Controller,{...t})}),exports.FormItem=At,exports.FormLabel=_t,exports.FormMessage=Lt,exports.FormSkeleton=function({fields:t=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,a)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Sa,{className:"h-4 w-24"}),e.jsx(Sa,{className:"h-10 w-full"})]},a)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Sa,{className:"h-10 w-20"}),e.jsx(Sa,{className:"h-10 w-20"})]})]})},exports.Grid=xi,exports.H1=wi,exports.H2=ki,exports.H3=Si,exports.H4=Ci,exports.HeaderSkeleton=function(){return e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(Sa,{className:"h-8 w-8 rounded-full"}),e.jsx(Sa,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Sa,{className:"h-8 w-8"}),e.jsx(Sa,{className:"h-8 w-24"})]})]})},exports.I18nextProvider=function({i18n:e,defaultNS:a,children:s}){const r=t.useMemo(()=>({i18n:e,defaultNS:a}),[e,a]);return t.createElement(Ma.Provider,{value:r},s)},exports.IconPicker=Jr,exports.ImageEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:c}){const{t:d}=Ga(),[u,m]=t.useState(a||{alignment:"center",allowDownload:!1}),p=t.useRef(null),{upload:h,uploading:f}=oc({uploadFunction:i,deleteFunction:o,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),g=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("url")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ot,{type:"url",placeholder:d("url_placeholder"),value:u.imageUrl||"",onChange:e=>g("imageUrl",e.target.value),className:"flex-1"}),i&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await h(t),a={...u,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(nt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),d("uploading")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),d("upload")]})})]})]}),u.imageFile&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d("image.fileInfo",{name:u.imageFile,size:Math.round((u.imageSize||0)/1024)})})]}),u.imageUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("preview")}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:e.jsx("div",{className:"flex "+("left"===u.alignment?"justify-start":"right"===u.alignment?"justify-end":"justify-center"),children:e.jsx("img",{src:u.imageUrl,alt:u.alt||"Preview",style:{width:u.width?`${u.width}px`:"auto",height:u.height?`${u.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{htmlFor:"caption",children:d("caption")}),e.jsx(Ht,{id:"caption",placeholder:d("caption"),value:u.caption||"",onChange:e=>g("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{htmlFor:"alt",children:d("alt")}),e.jsx(ot,{id:"alt",placeholder:d("alt"),value:u.alt||"",onChange:e=>g("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("alignment")}),e.jsxs(Ot,{value:u.alignment||"center",onValueChange:e=>g("alignment",e),children:[e.jsx(Mt,{children:e.jsx(Dt,{})}),e.jsxs(Ut,{children:[e.jsx(qt,{value:"left",children:d("left")}),e.jsx(qt,{value:"center",children:d("center")}),e.jsx(qt,{value:"right",children:d("right")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{htmlFor:"width",children:d("width")}),e.jsx(ot,{id:"width",type:"number",placeholder:"px",value:u.width||"",onChange:e=>g("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{htmlFor:"height",children:d("height")}),e.jsx(ot,{id:"height",type:"number",placeholder:"px",value:u.height||"",onChange:e=>g("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"allowDownload",type:"checkbox",checked:u.allowDownload||!1,onChange:e=>g("allowDownload",e.target.checked),className:"h-4 w-4"}),e.jsx(ct,{htmlFor:"allowDownload",className:"cursor-pointer",children:d("allow_download")})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(nt,{variant:"outline",onClick:n,children:d("cancel")}),e.jsx(nt,{onClick:()=>{u.imageUrl?r(u):ra({title:d("error"),description:d("error_no_image"),variant:"destructive"})},disabled:!u.imageUrl,children:d("save")})]})]})},exports.ImageRenderer=function({content:t,className:a="",style:s}){if(!t.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${a}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&e.jsxs("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e.jsx(l.Download,{className:"h-4 w-4"}),"Baixar imagem"]})]})})},exports.InlineCode=Ii,exports.Input=ot,exports.InputGroup=bi,exports.InputGroupAddon=yi,exports.InputGroupInput=vi,exports.Kbd=Ni,exports.LOGO_CONFIG=Os,exports.Label=ct,exports.Large=Ti,exports.Lead=Ei,exports.LeaderRow=Jl,exports.LeadershipDialog=rc,exports.LeadershipForm=sc,exports.LeadershipPage=function(){const{alias:a}=Zs(),{t:s}=Ga(),{data:r,isLoading:n,error:i,refetch:o}=Bl(),{data:c=[]}=Yr(),[d,u]=t.useState(()=>a?(e=>{try{const t=localStorage.getItem(`${nc}-${e}`);if(t)return new Set(JSON.parse(t))}catch(i){}return new Set})(a):new Set),[m,p]=t.useState(!1),[h,f]=t.useState(),[g,x]=t.useState(null),b=c.length-(r?new Set(ql(r).map(e=>e.id_user)).size:0);t.useEffect(()=>{if(r&&r.length>0&&a){if(!localStorage.getItem(`${nc}-${a}`)){const e=r.map(e=>e.id),t=new Set(e);u(t),ic(a,t)}}},[r,a]);const v=e=>{u(t=>{const s=new Set(t);return s.has(e)?s.delete(e):s.add(e),a&&ic(a,s),s})},y=e=>{f(e),x(null),p(!0)};return n?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx(l.RefreshCw,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:s("loading")})]})}):i?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e.jsx(nt,{onClick:()=>o(),children:"Tentar novamente"})]})}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center justify-between p-4 border-b",children:e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(nt,{size:"sm",onClick:()=>{f(void 0),x(null),p(!0)},children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsxs(nt,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=ql(r).filter(e=>e.children.length>0).map(e=>e.id),t=new Set(e);u(t),a&&ic(a,t)},disabled:!r||0===r.length,children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),e.jsxs(nt,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;u(e),a&&ic(a,e)},disabled:!r||0===r.length,children:[e.jsx(l.ChevronRight,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[b," usuário",1!==b?"s":""," não associado",1!==b?"s":""]})]})})]})}),r&&0!==r.length?e.jsx(Qr,{className:"flex-1",children:e.jsx("div",{children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e.jsx("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e.jsx("tbody",{children:r.map(t=>e.jsx(Jl,{leader:t,expandedIds:d,onToggleExpand:v,onEdit:y},t.id))})]})})}):e.jsx("div",{className:"flex items-center justify-center flex-1",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e.jsx(rc,{open:m,onOpenChange:()=>{p(!1),f(void 0),x(null)},leader:h,prefilledLeaderId:g,title:h?s("edit")+" "+s("name"):g?s("add")+" Liderado":s("add")+" Líder Raiz"},`leadership-dialog-${a}`)]})},exports.List=Li,exports.LoadingState=function({isLoading:t,children:a,className:s,type:r="spinner",size:n="md"}){return t?"overlay"===r?e.jsxs("div",{className:at("relative",s),children:[a,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(Xt,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:at("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:at("flex items-center justify-center py-8",s),children:e.jsx(Xt,{size:n})}):e.jsx(e.Fragment,{children:a})},exports.LocaleProvider=({children:a})=>{const{user:s,alias:r}=Zs(),[n,i]=t.useState({locale:"pt-BR",timezone:"America/Sao_Paulo",currency:"BRL",dateFormat:"DD/MM/YYYY"}),[o,l]=t.useState(!0);t.useEffect(()=>{(async()=>{if(!s?.id||!r){const e=localStorage.getItem("i18nextLng")||"pt-BR";return await et.changeLanguage(e),void l(!1)}try{const e=await Go.getUserPreferences(s.id,r);e&&(i({locale:e.locale,timezone:e.timezone,currency:e.currency,dateFormat:e.dateFormat}),await et.changeLanguage(e.locale),localStorage.setItem("i18nextLng",e.locale))}catch(e){}finally{l(!1)}})()},[s?.id,r]);const c=t.useCallback(async e=>{if(s?.id&&r)try{await Go.updatePreferences(s.id,r,{locale:e}),i(t=>({...t,locale:e})),await et.changeLanguage(e),localStorage.setItem("i18nextLng",e)}catch(t){throw t}},[s?.id,r]),d=t.useCallback(async e=>{if(s?.id&&r)try{await Go.updatePreferences(s.id,r,{timezone:e}),i(t=>({...t,timezone:e}))}catch(t){throw t}},[s?.id,r]),u=t.useCallback(async e=>{if(s?.id&&r)try{await Go.updatePreferences(s.id,r,{currency:e}),i(t=>({...t,currency:e}))}catch(t){throw t}},[s?.id,r]);return e.jsx(al.Provider,{value:{...n,setLocale:c,setTimezone:d,setCurrency:u,isLoading:o},children:a})},exports.LocaleSelector=il,exports.LoginPage=()=>e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(dt,{className:"w-full max-w-md",children:[e.jsx(ut,{className:"text-center",children:e.jsx(mt,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(ht,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(nt,{onClick:async()=>{Is()?await Js.loginDev():Js.loginProd()},className:"w-full",size:"lg",children:Is()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=Fs,exports.ManageAccessModal=Dl,exports.MarkdownMessage=Fl,exports.MultiSelect=Ya,exports.Muted=_i,exports.NativeSelect=ji,exports.NavigationProvider=cl,exports.P=Pi,exports.PageBreadcrumb=function({items:t,maxItems:a=3,className:s}){return t.length>a&&(t[0],t.slice(-(a-1))),t.length,e.jsx(Rn,{className:s})},exports.PageMetadataProvider=wn,exports.Pagination=Oi,exports.PaginationContent=Fi,exports.PaginationEllipsis=Ui,exports.PaginationItem=Di,exports.PaginationLink=Mi,exports.PaginationNext=$i,exports.PaginationPrevious=zi,exports.PlaceCard=Ml,exports.PlacesList=function({places:t,isLoading:a,manageAccessConfig:s}){const{t:r}=Ga();return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r("loading_data")})]})}):t&&0!==t.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(t=>e.jsx(Ml,{place:t,manageAccessConfig:s},t.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(l.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.Popover=ha,exports.PopoverContent=ga,exports.PopoverTrigger=fa,exports.Progress=pn,exports.ProtectedRoute=({children:a})=>{const{isAuthenticated:s,isLoading:r}=Zs();if(t.useEffect(()=>{if(!s)return;const e=()=>{ls.areAllTokensValid()||Js.logout()};e();const t=setInterval(e,3e5);return()=>clearInterval(t)},[s]),t.useEffect(()=>{if(r)return;if(s)return;if(ls.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 n=Is();(async()=>{n?await Js.loginDev():Js.loginProd()})()},[s,r]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(dt,{className:"w-full max-w-md",children:[e.jsx(ut,{className:"text-center",children:e.jsx(mt,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(ht,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){if(new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token"))return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(dt,{className:"w-full max-w-md",children:[e.jsx(ut,{className:"text-center",children:e.jsx(mt,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(ht,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})});try{if(ls.areAllTokensValid())return e.jsx(e.Fragment,{children:a})}catch{}return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(dt,{className:"w-full max-w-md",children:[e.jsx(ut,{className:"text-center",children:e.jsx(mt,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(ht,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:Is()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:a})},exports.QUALIEX_CONFIG=Rs,exports.QUERY_KEYS={crud:e=>[e],list:(e,t)=>[e,"list",t],detail:(e,t)=>[e,"detail",t]},exports.QualiexEnrichmentService=Vs,exports.QualiexErrorInterceptor=Ss,exports.QualiexUserField=Zr,exports.RadioGroup=Vi,exports.RadioGroupItem=qi,exports.ResizableRail=Sl,exports.SEARCH_CONFIG=_s,exports.ScrollArea=Qr,exports.ScrollBar=Gr,exports.Searchbar=Wi,exports.Select=Ot,exports.SelectContent=Ut,exports.SelectGroup=Ft,exports.SelectItem=qt,exports.SelectLabel=Vt,exports.SelectScrollDownButton=$t,exports.SelectScrollUpButton=zt,exports.SelectSearch=Ya,exports.SelectSeparator=Bt,exports.SelectTrigger=Mt,exports.SelectValue=Dt,exports.Separator=Hi,exports.Sheet=Ki,exports.SheetClose=Gi,exports.SheetContent=Zi,exports.SheetDescription=so,exports.SheetFooter=to,exports.SheetHeader=eo,exports.SheetOverlay=Ji,exports.SheetPortal=Xi,exports.SheetTitle=ao,exports.SheetTrigger=Qi,exports.Sidebar=po,exports.SidebarContent=No,exports.SidebarFooter=vo,exports.SidebarGroup=jo,exports.SidebarGroupAction=ko,exports.SidebarGroupContent=So,exports.SidebarGroupLabel=wo,exports.SidebarHeader=wl,exports.SidebarInput=xo,exports.SidebarInset=go,exports.SidebarMenu=Co,exports.SidebarMenuAction=Ao,exports.SidebarMenuBadge=_o,exports.SidebarMenuButton=To,exports.SidebarMenuItem=Po,exports.SidebarMenuSkeleton=Io,exports.SidebarMenuSub=Ro,exports.SidebarMenuSubButton=Oo,exports.SidebarMenuSubItem=Lo,exports.SidebarProvider=mo,exports.SidebarRail=fo,exports.SidebarSeparator=yo,exports.SidebarSkeleton=function(){return e.jsx("div",{className:"w-64 border-r bg-muted/10",children:e.jsxs("div",{className:"p-4",children:[e.jsx(Sa,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((t,a)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),e.jsx(Sa,{className:"h-4 w-20"})]},a))})]})})},exports.SidebarTrigger=ho,exports.Skeleton=Sa,exports.Slider=Fo,exports.Small=Ai,exports.SonnerToaster=({...t})=>{const{theme:a="system"}=I.useTheme();return e.jsx(o.Toaster,{theme:a,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",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"}},...t})},exports.Spinner=Xt,exports.Stack=ln,exports.StatusSelect=function({value:t,onChange:a,activeLabel:s,inactiveLabel:r,allLabel:n,placeholder:i,className:o="w-full sm:w-[180px]"}){const{t:l}=Ga(),c=[{id:"active",name:s||l("active")},{id:"inactive",name:r||l("inactive")},{id:"all",name:n||l("all")}];return e.jsx(Ya,{value:t,onChange:e=>a(e),options:c,getOptionValue:e=>e.id,getOptionLabel:e=>e.name,placeholder:i||l("select"),className:o})},exports.Switch=Do,exports.TabPageContent=function({children:t,className:a}){return e.jsx("div",{className:at("space-y-6",a),children:t})},exports.TabPageHeader=function({title:t,description:a,actions:s,className:r}){return e.jsxs("div",{className:at("space-y-4",r),children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:t}),a&&e.jsx("p",{className:"text-muted-foreground text-sm",children:a})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx(Hi,{})]})},exports.TabPageLayout=function({children:t,className:a}){return e.jsx("div",{className:at("flex flex-col h-full",a),children:e.jsx(Qr,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:t})})})},exports.Table=pr,exports.TableBody=fr,exports.TableCaption=yr,exports.TableCell=vr,exports.TableFooter=gr,exports.TableHead=br,exports.TableHeader=hr,exports.TableRow=xr,exports.TableRowActions=Ur,exports.TableSkeleton=Nr,exports.Tabs=Mo,exports.TabsContent=Uo,exports.TabsList=zo,exports.TabsTrigger=$o,exports.Textarea=Ht,exports.Toast=ca,exports.ToastAction=da,exports.ToastClose=ua,exports.ToastDescription=pa,exports.ToastProvider=ia,exports.ToastTitle=ma,exports.ToastViewport=oa,exports.Toaster=function(){const{toasts:t}=na();return e.jsxs(ia,{children:[t.map(function({id:t,title:a,description:s,action:r,...n}){return e.jsxs(ca,{...n,children:[e.jsxs("div",{className:"grid gap-1",children:[a&&e.jsx(ma,{children:a}),s&&e.jsx(pa,{children:s})]}),r,e.jsx(ua,{})]},t)}),e.jsx(oa,{})]})},exports.Toggle=qo,exports.ToggleGroup=Wo,exports.ToggleGroupItem=Ho,exports.TokenManager=ls,exports.TokenService=es,exports.Tooltip=no,exports.TooltipContent=oo,exports.TooltipProvider=ro,exports.TooltipTrigger=io,exports.TranslationLoader=function({children:a}){const{ready:s}=Ga(),[r,n]=t.useState(!0);return t.useEffect(()=>{s&&r&&n(!1)},[s,r]),r&&!s?e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-background",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Xt,{size:"lg"}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Carregando traduções..."})]})}):e.jsx(e.Fragment,{children:a})},exports.VideoEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:c}){const{t:d}=Ga(),[u,m]=t.useState(a||{inputType:"url",controls:!0}),p=t.useRef(null),h=t.useRef(null),{upload:f,uploading:g}=oc({uploadFunction:i,deleteFunction:o,defaultOptions:{...c,allowedTypes:["video/*"],maxSize:104857600}}),{upload:x,uploading:b}=oc({uploadFunction:i,deleteFunction:o,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),v=t.useMemo(()=>pc(u.videoUrl||mc(u.embedCode)||""),[u.videoUrl,u.embedCode]),y=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("input_type")}),e.jsxs(Ot,{value:u.inputType||"url",onValueChange:e=>y("inputType",e),children:[e.jsx(Mt,{children:e.jsx(Dt,{})}),e.jsxs(Ut,{children:[e.jsx(qt,{value:"url",children:d("url")}),e.jsx(qt,{value:"upload",children:d("input_type_upload")}),e.jsx(qt,{value:"embed",children:d("input_type_embed")})]})]})]}),"upload"===u.inputType&&i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("file")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:p,type:"file",accept:"video/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await f(t),a={...u,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:u.title||t.name.replace(/\.[^/.]+$/,"")};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(nt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),d("uploading")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),d("select_video")]})}),u.videoFile&&e.jsx("span",{className:"text-xs text-muted-foreground truncate self-center",children:d("video.fileInfo",{name:u.videoFile,size:Math.round((u.videoSize||0)/1024/1024)})})]})]}),"embed"===u.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("embed")}),e.jsx(Ht,{placeholder:d("embed"),value:u.embedCode||"",onChange:e=>y("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("thumbnail")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ot,{type:"url",placeholder:d("thumbnail"),value:u.thumbnail||"",onChange:e=>y("thumbnail",e.target.value),className:"flex-1"}),e.jsx("input",{ref:h,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await x(t),a={...u,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};m(a),s(a)}catch(a){}finally{h.current&&(h.current.value="")}},className:"hidden"}),e.jsx(nt,{type:"button",variant:"outline",onClick:()=>h.current?.click(),disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),d("video.uploading")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),d("upload")]})})]}),u.thumbnailFile&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d("video.thumbnailFileInfo",{name:u.thumbnailFile})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{htmlFor:"title",children:d("title")}),e.jsx(ot,{id:"title",placeholder:d("title"),value:u.title||"",onChange:e=>y("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"autoplay",type:"checkbox",checked:u.autoplay||!1,onChange:e=>y("autoplay",e.target.checked),className:"h-4 w-4"}),e.jsx(ct,{htmlFor:"autoplay",className:"cursor-pointer",children:d("video.autoplay")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"controls",type:"checkbox",checked:!1!==u.controls,onChange:e=>y("controls",e.target.checked),className:"h-4 w-4"}),e.jsx(ct,{htmlFor:"controls",className:"cursor-pointer",children:d("video.controls")})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{children:d("preview")}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=u.videoUrl||mc(u.embedCode)||"";if(!t)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:d("no_content_preview")});if("file"===v)return e.jsxs("video",{controls:!1!==u.controls,autoPlay:u.autoplay,poster:u.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e.jsx("source",{src:t}),d("unsupported")]});const a="youtube"===v?cc(t,u.autoplay):uc(t,u.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:u.title||d("video"),src:a,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(nt,{variant:"outline",onClick:n,children:d("cancel")}),e.jsx(nt,{onClick:()=>{u.videoUrl||u.embedCode?r(u):ra({title:d("error"),description:d("error_no_video"),variant:"destructive"})},disabled:!(u.videoUrl||u.embedCode),children:d("save")})]})]})},exports.VideoRenderer=function({content:t,className:a="",style:s}){const r=t.videoUrl||mc(t.embedCode)||"";if(!r)return null;const n=pc(r),{t:i}=Ga();return e.jsx(dt,{className:`overflow-hidden my-4 ${a}`,style:s,children:e.jsxs(ht,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e.jsx("source",{src:r}),"Seu navegador não suporta vídeos HTML5."]}):e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:t.title||i("video"),src:"youtube"===n?cc(r,t.autoplay):uc(r,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:t.title})})]})})},exports.WizardBreadcrumb=fn,exports.WizardButtons=xn,exports.WizardForm=function({title:a,sections:s,initialData:r,onSubmit:n,onCancel:i,open:o,submitButtonText:l,isLoading:c=!1,usersData:d,showProgressIndicator:u=!0,progressType:m="stepper",validateOnNext:p=!0,allowSkipSections:h=!1,previousButtonText:f,nextButtonText:g,onStepChange:x,onStepValidationFail:b,renderProgressIndicator:v,renderButtons:y,currentStepIndex:N,onCurrentStepChange:j}){const[w,k]=t.useState(0),S=N??w,C=j??k,P=t.useRef(null),[E,T]=t.useState(null),A=t.useCallback(e=>{P.current=e,T(e)},[]),_=t.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:I,errors:R,updateField:L,handleSubmit:O}=Wr(_,r,void 0,o);t.useEffect(()=>{o&&C(0)},[o,C]);const F=t.useCallback(()=>{const e=s[S];if(!e)return!0;const t=e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e),a={};let r=!0;return t.forEach(e=>{const t=I[e.name];if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length)&&(a[e.name]=`${e.label} é obrigatório`,r=!1),e.validation&&"function"==typeof e.validation){const s=e.validation(t,I);s&&(a[e.name]=s,r=!1)}}),!r&&b&&b(S,a),r},[s,S,I,b]),D=t.useCallback(()=>{if(p&&!F())return;const e=S+1;e<s.length&&(C(e),x?.(e,s[e].id))},[S,s,p,F,C,x]),M=t.useCallback(()=>{const e=S-1;e>=0&&(C(e),x?.(e,s[e].id))},[S,s,C,x]),z=t.useCallback(()=>{let e=!0;for(let t=0;t<s.length;t++){s[t].fields.flatMap(e=>"group"===e.type?e.fields||[]:e).forEach(t=>{const a=I[t.name];t.required&&(""===a||null==a||Array.isArray(a)&&0===a.length)&&(e=!1)})}e&&O(n)()},[s,I,O,n]),$=t.useMemo(()=>s.map((e,t)=>({index:t,id:e.id,label:e.label||e.id,isActive:t===S,isCompleted:t<S,isDisabled:e.disabled||!1})),[s,S]),U=0===S,V=S===s.length-1,q=t.useMemo(()=>{if(!u)return null;if(v)return v(S,s.length,s);const t=h?e=>{C(e),x?.(e,s[e].id)}:void 0;switch(m){case"breadcrumb":return e.jsx(fn,{steps:$,currentStepIndex:S,onStepClick:t});case"progressbar":return e.jsx(gn,{steps:$,currentStepIndex:S});default:return e.jsx(hn,{steps:$,currentStepIndex:S,onStepClick:t})}},[u,v,m,$,S,s,h,C,x]),B=t.useMemo(()=>{const t={isFirstStep:U,isLastStep:V,canGoNext:S<s.length-1,canGoPrevious:S>0,isLoading:c,onPrevious:M,onNext:D,onSubmit:z,previousButtonText:f,nextButtonText:g,submitButtonText:l};return y?y(t):e.jsx(xn,{...t})},[U,V,S,s.length,c,M,D,z,f,g,l,y]),W=t=>{const a=(t.computedValue,I[t.name]),s=void 0!==a?a:"",r=R[t.name];switch(t.type){case"group":return e.jsxs("div",{className:"space-y-2",children:[t.label&&e.jsx(ct,{className:"text-sm font-medium",children:t.label}),e.jsx("div",{className:at("grid gap-4",1===t.columns&&"grid-cols-1",2===t.columns&&"grid-cols-1 md:grid-cols-2",3===t.columns&&"grid-cols-1 md:grid-cols-3",4===t.columns&&"grid-cols-1 md:grid-cols-4",!t.columns&&"grid-cols-1"),children:t.fields?.map(e=>W(e))})]},t.name);case"number":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ot,{id:t.name,type:"number",value:s,onChange:e=>L(t.name,""===e.target.value?"":Number(e.target.value)),placeholder:t.placeholder,disabled:t.disabled||void 0!==t.computedValue,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"textarea":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ht,{id:t.name,value:s,onChange:e=>L(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,rows:t.rows||3,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"select":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ot,{value:s,onValueChange:e=>L(t.name,e),children:[e.jsx(Mt,{className:r?"border-destructive":"",children:e.jsx(Dt,{placeholder:t.placeholder||`Selecione ${t.label}`})}),e.jsx(Ut,{children:t.options?.map(t=>e.jsx(qt,{value:String(t.value),children:t.label},t.value))})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"multiselect":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ya,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>L(t.name,e),placeholder:t.placeholder,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"color":case"color-picker":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Kr,{value:s,onChange:e=>L(t.name,e),label:""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"icon-picker":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Jr,{value:s,onChange:e=>L(t.name,e),label:""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"user-select":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Zr,{value:s,onChange:e=>L(t.name,e),placeholder:t.placeholder,disabled:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"custom":return t.render?e.jsxs("div",{className:"space-y-2",children:[t.label&&e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),t.render({value:s,onChange:e=>L(t.name,e),error:r,disabled:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name):null;default:return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ct,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ot,{id:t.name,type:t.type||"text",value:s,onChange:e=>L(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled||void 0!==t.computedValue,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name)}},H=s[S];return e.jsx(gt,{open:o,onOpenChange:i,children:e.jsxs(Nt,{ref:A,className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(jt,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:e.jsx(kt,{className:"text-white",children:a})}),q,e.jsx("div",{className:"space-y-4 py-4",children:H?.fields.map(e=>W(e))}),e.jsx("div",{className:"flex justify-between pt-4 border-t",children:B})]})})},exports.WizardProgressBar=gn,exports.WizardStepper=hn,exports.assets=yl,exports.badgeVariants=Kt,exports.buildHierarchy=Vl,exports.buttonGroupVariants=$n,exports.buttonVariants=rt,exports.calculateAspectRatio=hc,exports.cn=at,exports.createCrudPage=function(t){return({manager:a})=>{const{manager:s,config:r,onSave:n,onEdit:i,onToggleStatus:o}=t,l=a??s,c={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit:i||r.onEdit};return e.jsx(dn,{manager:l,config:c,formSections:r.formSections,onSave:n,onToggleStatus:o,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,t){const a=Qo({basePath:e,newPath:t.newPath,editPath:t.editPath});return{useCustomRouting:!0,onNew:a.onNew,onEdit:a.onEdit}},exports.createRoutingHandlers=Qo,exports.createService=Ws,exports.createSimpleSaveHandler=function(e,t,a){return s=>{if(s.id){const t=a(s);e.updateEntity(s.id,t)}else{const a=t(s);e.createEntity(a)}}},exports.createSimpleService=function(e){const t=Ws({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,s)=>er({queryKey:e.tableName,service:{...t,getAll:async(e={})=>await t.getAll({...e})},entityName:e.entityName,additionalFilters:a,onSuccess:s})}},exports.debounce=(e,t)=>{let a;return(...s)=>{clearTimeout(a),a=setTimeout(()=>e(...s),t)}},exports.deriveEmailField=Ms,exports.deriveNameField=Ds,exports.deriveUsernameField=zs,exports.detectVideoProvider=pc,exports.emailService=Ll,exports.errorService=us,exports.extractImageFileName=function(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"}},exports.extractVimeoId=dc,exports.extractYouTubeId=lc,exports.flattenTree=ql,exports.formatCurrency=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDate=Il,exports.formatDatetime=e=>{if(!e)return"";const t=i.parseISO(e);if(!i.isValid(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"})}`},exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=function(e,t,a={}){const s=[];return Object.keys(t).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const a=t[e],r={key:e,header:mn(e),label:mn(e),...un(e,a),sortable:!0,searchable:"string"==typeof a};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...a}},exports.getQualiexConfig=Ls,exports.getSupabaseClient=bs,exports.handleExternalLink=tt,exports.i18n=et,exports.isDevEnvironment=Is,exports.isImageUrl=function(e){const t=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>t.includes(e))},exports.logoSrc=Nl,exports.normalizeVideoUrl=function(e,t,a){switch(t||pc(e)){case"youtube":return cc(e,a);case"vimeo":return uc(e,a);default:return e}},exports.normalizeVimeoUrl=uc,exports.normalizeYouTubeUrl=cc,exports.parseIframeSrc=mc,exports.placeService=Ul,exports.qualiexApi=Es,exports.resizeKeepingAspect=function(e,t,a,s){const r=hc(e,t);return a&&!s?{width:a,height:Math.round(a/r)}:s&&!a?{width:Math.round(s*r),height:s}:{width:e,height:t}},exports.resolveFieldMappings=$s,exports.searchbarVariants=Bi,exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new x.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.slugify=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),exports.smallLogoSrc=jl,exports.toast=ra,exports.toggleVariants=Vo,exports.translationService=Yo,exports.trimTextFields=st,exports.useActiveModules=fl,exports.useAllQualiexUsers=(e={})=>{const{alias:t}=Zs(),{enabled:a=!0}=e;return x.useQuery({queryKey:["qualiex-all-users",t],queryFn:async()=>t?Es.getAllUsers(t):[],enabled:a&&!!t,staleTime:3e5,retry:2})},exports.useAuth=Zs,exports.useBaseForm=Wr,exports.useCreateLeaderMutation=function(){const e="common",{alias:t}=Zs(),a=x.useQueryClient(),s=bs();return x.useMutation({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 s.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 Xl(s,t,e,a.id_user,a.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success("Líder adicionado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao adicionar líder")}})},exports.useCreateMultipleLeadersMutation=Hl,exports.useCreateSingleLeaderMutation=Wl,exports.useCrud=er,exports.useDebounce=ml,exports.useFormField=Et,exports.useI18nFormatters=()=>{const{locale:e,timezone:t,currency:a}=sl();return{formatDatetime:a=>((e,t="pt-BR")=>{if(!e)return"";const a=i.parseISO(e);if(!i.isValid(a))return"Invalid date";const s=_l[t]||ci;return i.format(a,"PPp",{locale:s})})(a,e,t),formatDate:t=>Il(t,e),formatCurrency:t=>((e,t="BRL",a="pt-BR")=>null==e?"":new Intl.NumberFormat(a,{style:"currency",currency:t,minimumFractionDigits:2,maximumFractionDigits:2}).format(e))(t,a,e),locale:e,timezone:t,currency:a}},exports.useLeadershipApi=Bl,exports.useLocale=sl,exports.useMediaUpload=oc,exports.useNavigation=dl,exports.useOpenAIChat=Ol,exports.usePageMetadata=function(e){const{setMetadata:a,clearMetadata:s}=kn();t.useEffect(()=>(a(e),()=>s()),[e.title,e.subtitle,a,s])},exports.usePageMetadataContext=kn,exports.usePageTitle=ul,exports.usePermissionQuery=hl,exports.useQualiexUsers=Yr,exports.useRemoveLeaderMutation=Ql,exports.useRouteBreadcrumbs=function(){const e=b.useLocation();return(()=>{const t=e.pathname.split("/").filter(Boolean),a=[{label:"Exemplos",href:"/"}];let s="";return t.forEach((e,r)=>{s+=`/${e}`;const n=r===t.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");a.push({label:i,href:n?void 0:s,isCurrentPage:n})}),a})()},exports.useSidebar=uo,exports.useSidebarResize=kl,exports.useSyncSubordinatesMutation=Gl,exports.useToast=na,exports.useTranslation=Ga,exports.useUpdateLeaderMutation=Kl;
10
+ */var Qa=(Ka||(Ka=1,"production"===process.env.NODE_ENV?Ba.exports=function(){if(qa)return Wa;qa=1;var e=t,a="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},s=e.useState,r=e.useEffect,n=e.useLayoutEffect,i=e.useDebugValue;function o(e){var t=e.getSnapshot;e=e.value;try{var s=t();return!a(e,s)}catch(r){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 a=t(),l=s({inst:{value:a,getSnapshot:t}}),d=l[0].inst,c=l[1];return n(function(){d.value=a,d.getSnapshot=t,o(d)&&c({inst:d})},[e,a,t]),r(function(){return o(d)&&c({inst:d}),e(function(){o(d)&&c({inst:d})})},[e]),i(a),a};return Wa.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:l,Wa}():Ba.exports=(Ha||(Ha=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t=e.getSnapshot;e=e.value;try{var a=t();return!s(e,a)}catch(r){return!0}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var a=t,s="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=a.useState,n=a.useEffect,i=a.useLayoutEffect,o=a.useDebugValue,l=!1,d=!1,c="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,c){l||void 0===a.startTransition||(l=!0);var u=c();if(!d){var m=c();s(u,m)||(d=!0)}var p=(m=r({inst:{value:u,getSnapshot:c}}))[0].inst,h=m[1];return i(function(){p.value=u,p.getSnapshot=c,e(p)&&h({inst:p})},[t,u,c]),n(function(){return e(p)&&h({inst:p}),t(function(){e(p)&&h({inst:p})})},[t]),o(u),u};Ga.useSyncExternalStore=void 0!==a.useSyncExternalStore?a.useSyncExternalStore:c,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Ga)),Ba.exports);const Xa={t:(e,t)=>{return La(t)?t:"object"==typeof(a=t)&&null!==a&&La(t.defaultValue)?t.defaultValue:Array.isArray(e)?e[e.length-1]:e;var a},ready:!1},Ja=()=>()=>{},Ya=(e,a={})=>{const{i18n:s}=a,{i18n:r,defaultNS:n}=t.useContext(Ua)||{},i=s||r||za;i&&!i.reportNamespaces&&(i.reportNamespaces=new Va),i||Aa(i,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const o=t.useMemo(()=>({...Fa,...i?.options?.react,...a}),[i,a]),{useSuspense:l,keyPrefix:d}=o,c=e||n||i?.options?.defaultNS,u=La(c)?[c]:c||["translation"],m=t.useMemo(()=>u,u);i?.reportNamespaces?.addUsedNamespaces?.(m);const p=t.useRef(0),h=t.useCallback(e=>{if(!i)return Ja;const{bindI18n:t,bindI18nStore:a}=o,s=()=>{p.current+=1,e()};return t&&i.on(t,s),a&&i.store.on(a,s),()=>{t&&t.split(" ").forEach(e=>i.off(e,s)),a&&a.split(" ").forEach(e=>i.store.off(e,s))}},[i,o]),f=t.useRef(),x=t.useCallback(()=>{if(!i)return Xa;const e=!(!i.isInitialized&&!i.initializedStoreOnce)&&m.every(e=>((e,t,a={})=>t.languages&&t.languages.length?t.hasLoadedNamespace(e,{lng:a.lng,precheck:(t,s)=>{if(a.bindI18n&&a.bindI18n.indexOf("languageChanging")>-1&&t.services.backendConnector.backend&&t.isLanguageChangingTo&&!s(t.isLanguageChangingTo,e))return!1}}):(Aa(t,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:t.languages}),!0))(e,i,o)),t=a.lng||i.language,s=p.current,r=f.current;if(r&&r.ready===e&&r.lng===t&&r.keyPrefix===d&&r.revision===s)return r;const n={t:i.getFixedT(t,"fallback"===o.nsMode?m:m[0],d),ready:e,lng:t,keyPrefix:d,revision:s};return f.current=n,n},[i,m,d,o,a.lng]),[g,b]=t.useState(0),{t:v,ready:y}=Qa.useSyncExternalStore(h,x,x);t.useEffect(()=>{if(i&&!y&&!l){const e=()=>b(e=>e+1);a.lng?Ra(i,a.lng,m,e):Ia(i,m,e)}},[i,a.lng,m,y,l,g]);const N=i||{},j=t.useRef(null),w=t.useRef(),k=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(s){}return a},C=t.useMemo(()=>{const e=N,t=e?.language;let a=e;e&&(j.current&&j.current.__original===e?w.current!==t?(a=k(e),j.current=a,w.current=t):a=j.current:(a=k(e),j.current=a,w.current=t));const s=[v,a,y];return s.t=v,s.i18n=a,s.ready=y,s},[v,N,y,N.resolvedLanguage,N.language,N.languages]);if(i&&l&&!y)throw new Promise(e=>{const t=()=>e();a.lng?Ra(i,a.lng,m,t):Ia(i,m,t)});return C};const Za=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function es({multiple:a,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:f,className:x,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:y,onClose:N}){const{t:j}=Ya(),[w,k]=t.useState(!1),[C,S]=t.useState(""),P=t.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=t.useMemo(()=>{if(!v)return;let e=v,t=0;try{for(;e&&t<3;){const a=window.getComputedStyle(e),s=a.overflowY||a.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,t++}}catch{}return e??void 0},[v]),T=t.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return g?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,g]),A=t.useMemo(()=>{if(!C)return T;const e=Za(C);return T.filter(t=>Za(t.label).includes(e))},[T,C]),_=t.useMemo(()=>T.filter(e=>P.includes(e.value)),[T,P]),I=(e,t)=>{t.preventDefault(),t.stopPropagation(),n&&n(a?P.filter(t=>t!==e):"")},R=b?_.slice(0,b):_,L=b&&_.length>b?_.length-b:0;return e.jsxs("div",{className:nt("space-y-2",x),children:[c&&e.jsxs(mt,{children:[c,f&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(ga,{open:w,onOpenChange:e=>{k(e),e?y?.():(S(""),N?.())},modal:!1,children:[e.jsx(ba,{asChild:!0,children:e.jsxs(lt,{variant:"outline",role:"combobox","aria-expanded":w,disabled:h,className:nt("w-full justify-between min-h-10 h-auto",0===_.length&&"text-muted-foreground"),children:[0===_.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),d]}):a?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[R.map(t=>e.jsxs(Jt,{variant:"secondary",className:"gap-1 pr-1",children:[t.label,e.jsx("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&&I(t.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>I(t.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},t.value)),L>0&&e.jsxs(Jt,{variant:"outline",className:"gap-1",children:["+",L]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),_[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(va,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(ya,{children:[e.jsx(Na,{placeholder:p,value:C,onChange:e=>S(e.target.value)}),e.jsx(ja,{children:0===s.length?e.jsx(wa,{children:m}):0===A.length?e.jsx(wa,{children:j("no_results")}):e.jsx(ka,{children:A.map(t=>e.jsxs(Sa,{value:t.value,onSelect:()=>(e=>{if(n)if(a){const t=P.includes(e)?P.filter(t=>t!==e):[...P,e];n(t)}else n(e),k(!1)})(t.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:nt("mr-2 h-4 w-4",P.includes(t.value)?"opacity-100":"opacity-0")}),t.label]},t.value))})})]})})]})]})}function ts({multiple:t=!1,options:a,items:s,value:r,onChange:n,onValueChange:i,getOptionValue:o=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:p,searchPlaceholder:h,disabled:f=!1,required:x=!1,isLoading:g=!1,error:b,className:v,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:j,onOpen:w,onClose:k}){const{t:C}=Ya(),S=s||a||[],P=i||n,E=c||C("select_placeholder"),T=p||C("no_results"),A=h||C("search_placeholder");if(g)return e.jsxs("div",{className:nt("space-y-2",v),children:[u&&e.jsxs(mt,{children:[u,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Ea,{className:"h-10 w-full"})]});const _="string"==typeof b?b:b instanceof Error?b.message:b?"Erro ao carregar dados":void 0;return _?e.jsxs("div",{className:nt("space-y-2",v),children:[u&&e.jsxs(mt,{children:[u,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:_})]})]}):e.jsx(es,{multiple:t,options:S,value:r||(t?[]:""),onChange:P,getOptionValue:o,getOptionLabel:d,placeholder:E,label:u,icon:m,emptyMessage:T,searchPlaceholder:A,disabled:f,required:x,className:v,sortOptions:y,maxDisplayedBadges:N,popoverContainer:j,onOpen:w,onClose:k})}var as=Object.defineProperty;class ss{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 r=e.split(".");if(3!==r.length)return null;const n=r[1];n.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(n),t=atob(e),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);const s=new TextDecoder("utf-8").decode(a);return JSON.parse(s)}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(s){throw s}}}}catch(r){return null}}static validateTokens(e,t){const a=[],s=[];try{t.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(t),n=this.parseJwtPayload(e);if(!r){const e="ID token decode falhou - possível problema com base64url encoding";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}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(r.exp&&r.exp<o){const e="ID token expirado - autenticação inválida";return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:a,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:a,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:a,errors:s}}}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?as(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a})(ss,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const rs="qualiex_access_token",ns="qualiex_id_token",is="supabase_token",os="oauth_state",ls="oauth_nonce",ds="selected_alias",cs="manual_logout",us={setAccessToken:e=>localStorage.setItem(rs,e),getAccessToken:()=>localStorage.getItem(rs),setIdToken:e=>localStorage.setItem(ns,e),getIdToken:()=>localStorage.getItem(ns),getSupabaseToken:()=>localStorage.getItem(is),setOAuthState:e=>sessionStorage.setItem(os,e),getOAuthState:()=>sessionStorage.getItem(os),clearOAuthState:()=>sessionStorage.removeItem(os),setOAuthNonce:e=>sessionStorage.setItem(ls,e),getOAuthNonce:()=>sessionStorage.getItem(ls),clearOAuthNonce:()=>sessionStorage.removeItem(ls),setSelectedAlias:e=>localStorage.setItem(ds,e),getSelectedAlias:()=>localStorage.getItem(ds),clearSelectedAlias:()=>localStorage.removeItem(ds),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!us.getAccessToken()||!us.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(is,e),us._clearValidationCache()},areAllTokensValid:()=>{const e=us.getAccessToken(),t=us.getIdToken();if(!e||!t)return!1;try{const a=ss.validateTokens(e,t);return!!a.idTokenValid&&a.idTokenValid}catch(a){return!1}},clearExpiredTokens:()=>{let e=!1;const t=us.getAccessToken(),a=us.getIdToken(),s=us.getSupabaseToken();return t&&us.isTokenExpired(t)&&(localStorage.removeItem(rs),e=!0),a&&us.isTokenExpired(a)&&(localStorage.removeItem(ns),e=!0),s&&us.isTokenExpired(s)&&(localStorage.removeItem(is),e=!0),e},clearAll:()=>{localStorage.removeItem(rs),localStorage.removeItem(ns),localStorage.removeItem(is),localStorage.removeItem(ds),localStorage.removeItem(cs),sessionStorage.removeItem(os),sessionStorage.removeItem(ls)},setManualLogout:()=>localStorage.setItem(cs,"true"),isManualLogout:()=>"true"===localStorage.getItem(cs),clearManualLogout:()=>localStorage.removeItem(cs),isTokenExpired:e=>{try{return ss.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{us._validationCache.isValid=!1,us._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=us.getSupabaseToken();if(!e)return!1;if(us.isTokenExpired(e))return us._clearValidationCache(),us._handleExpiredToken(),!1;const t=Date.now();return t-us._validationCache.timestamp<us._validationCache.cacheValidityMs?us._validationCache.isValid:(us._validationCache.isValid=!0,us._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>us.isSupabaseTokenValid()?us.getSupabaseToken():null,_handleExpiredToken:()=>{us.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!us.isSupabaseTokenValid())return null;const e=us.getSupabaseToken();if(!e)return null;try{const t=ss.parseJwtPayload(e);if(!t)return null;const a=t.alias||t.default||t.user_alias,s=t.place_id||null,r=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 s=t[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===a){n=e[7];break}}}return{alias:a,companyId:n,placeId:s,placeName:r,payload:t}}catch(t){return us._handleExpiredToken(),null}},getCompanyId:e=>{const t=us.getAccessToken();if(t)try{const a=ss.parseJwtPayload(t);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const s=a[t];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}const a=us.extractTokenData();if(a?.companyId)return a.companyId;const s=us.getIdToken();if(s)try{const t=ss.parseJwtPayload(s);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const s=t[a];if(s&&"string"==typeof s){const t=s.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(r){}return null},getCurrentCompanyId:()=>{const e=us.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=us.getIdToken();if(!e)return[];try{const t=ss.parseJwtPayload(e);if(!t)return[];const a=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=t[e];if(s&&"string"==typeof s){const e=s.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 ms=Object.defineProperty,ps=(e,t,a)=>((e,t,a)=>t in e?ms(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const hs=new class{constructor(){ps(this,"errors",[]),ps(this,"toastCount",0),ps(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()){oa({title:this.getErrorTitle(a),description:a,variant:"destructive"})}}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){oa({title:e,description:t,variant:"default"})}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 fs=Object.defineProperty,xs=(e,t,a)=>((e,t,a)=>t in e?fs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const gs=(void 0).VITE_SUPABASE_URL,bs=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY,vs=class e{constructor(){xs(this,"client"),xs(this,"currentToken",null),xs(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:bs};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return x.createClient(gs,bs,{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=us.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 hs.handleError(t instanceof Error?t:"❌ Supabase - Error validating token",!1),!1}}};xs(vs,"instance");let ys=vs;function Ns(){return ys.getInstance().getClient()}class js{static async generateToken(e,t,a,s=!1){try{if(!s){const e=us.getSupabaseToken();if(e&&us.isSupabaseTokenValid())return e}const r=Ns(),{data:n,error:i}=await r.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?(us.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&a?.(),null}}}var ws=Object.defineProperty,ks=(e,t,a)=>((e,t,a)=>t in e?ws(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);class Cs{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=us.getAccessToken(),t=us.getSelectedAlias();if(!e||!t)return null;const a=await js.generateToken(e,t,this.onLogoutCallback||void 0,!1);return a?(us.setSupabaseToken(a),a):null}catch(e){return null}finally{this.isRegenerating=!1}}}ks(Cs,"isRegenerating",!1),ks(Cs,"onLogoutCallback",null);class Ss{static handleError(e){if(!e)return!1;const t=e.message||e.toString();return!!this.isAuthenticationError(e,t)&&(us.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 Ps=Object.defineProperty;class Es{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 Cs.attemptRegeneration()?(this.isRetrying=!1,!0):(Ss.handleError(e),this.isRetrying=!1,!1)}catch(s){return Ss.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=us.getAccessToken();return e?us.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?Ps(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a})(e,t+"",a)})(Es,"isRetrying",!1);var Ts=Object.defineProperty,As=(e,t,a)=>((e,t,a)=>t in e?Ts(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const _s=new class{constructor(){As(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const s=Es.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=us.getAccessToken();if(!r)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 ${r}`,"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){const t=e.status||e.userStatus||"",a=void 0!==e.isActive?e.isActive:"active"===t.toLowerCase()||"ACTIVE"===t.toUpperCase();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,isActive:a,status:t||void 0}}async fetchUsers(e,t){try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return hs.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];s=a}if(!Array.isArray(s))return hs.handleError("[QualiexApi] Resposta não é um array",!1),[];return s.map(this.mapToQualiexUser)}catch(a){if(await Es.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return hs.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];s=a}return Array.isArray(s)?s.map(this.mapToQualiexUser):(hs.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(s){return hs.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}const r=a instanceof Error?a.message:"Erro ao buscar usuários da API Qualiex";return hs.handleError(r,!0),[]}}async fetchUserById(e,t,a){try{return(await this.fetchUsers(t,a)).find(t=>t.userId===e)||null}catch(s){return hs.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,t){const a=await this.fetchUsers(e,t),s=new Map;return a.forEach(e=>{s.set(e.userId,e)}),s}async fetchAllUsers(e,t){try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"all"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return hs.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];s=a}return Array.isArray(s)?s.map(this.mapToQualiexUser):(hs.handleError("[QualiexApi] Resposta não é um array",!1),[])}catch(a){if(await Es.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"all"},e);let s=a;if(a.data)s=a.data;else{if(!Array.isArray(a))return hs.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];s=a}return Array.isArray(s)?s.map(this.mapToQualiexUser):(hs.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(s){return hs.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}return hs.handleError(a instanceof Error?a.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async getUsers(e){const t=us.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId):[]}async getAllUsers(e){const t=us.extractTokenData();return t&&t.companyId?this.fetchAllUsers(e,t.companyId):[]}},Is={oauth:{authUrl:(void 0).VITE_OAUTH_AUTH_URL,clientId:(void 0).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"}},Ls={debounceDelay:500},Ms=()=>{const e=window.location.origin;return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("id-preview")||e.includes("lovable.dev")||(void 0).DEV},Os={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Ds=()=>Os,Fs={isQualiex:"true"===(void 0).VITE_IS_QUALIEX},zs={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 $s(e,t){const a=Ds(),s=t||a.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function Us(e,t){const a=Ds(),s=t||a.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function Vs(e,t){const a=Ds(),s=t||a.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function qs(e,t){return t&&t.length>0?t.map(e=>({idField:e.idField,nameField:e.nameField||$s(e.idField),emailField:e.emailField||Us(e.idField),usernameField:e.usernameField||Vs(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:$s(e),emailField:Us(e),usernameField:Vs(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Bs=new Map;class Ws{static async fetchQualiexUsers(e,t){const a=`${t}_${e}`,s=Bs.get(a);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await _s.fetchUsers(e,t);return Bs.set(a,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,t){const a=new Set;for(const s of e)for(const e of t){const t=s[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 s={...e};for(const r of t){const t=e[r.idField];if(!t)continue;const n=a.get(t);if(n){if(r.nameField){s[r.nameField]||(s[r.nameField]=n.userName||n.displayName||null)}if(r.emailField){s[r.emailField]||(s[r.emailField]=n.userEmail||null)}if(r.usernameField){s[r.usernameField]||(s[r.usernameField]=n.userName||null)}}}return s}static async enrichWithUserData(e,t){if(!Array.isArray(e)||0===e.length)return e;try{if(!us.areAllTokensValid())return e;const a=us.extractTokenData();if(!a)return e;const{alias:s,companyId:r}=a;if(!s||!r)return e;const n=qs(t.userIdFields,t.userFieldsMapping);if(0===this.extractUserIds(e,n).size)return e;const i=await this.fetchQualiexUsers(s,r),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,n,o))}catch(a){return hs.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 Hs=["responsible_name"],Ks=e=>Hs.includes(e);function Gs(e,t,a){const s="string"==typeof e?{tableName:e,searchFields:t||[],schemaName:a||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:r,searchFields:n,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=s,c=()=>{if(!us.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Ns().schema(o).from(r)},u=(e,t,a,s)=>{let r=c().select(i||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,t])=>{void 0!==t&&""!==t&&(Array.isArray(t)?r=r.in(e,t):"object"==typeof t&&t&&"operator"in t?"not_null"===t.operator?r=r.not(e,"is",null):"is_null"===t.operator&&(r=r.is(e,null)):null!==t&&(r=r.eq(e,t)))}),r=((e,t)=>{if(t&&n.length>0){const a=n.map(e=>`${e}.ilike.%${t}%`).join(",");return e.or(a)}return e})(r,e);const o=t.includes(".");return o||Ks(t)||(r=r.order(t,{ascending:"asc"===a})),{query:r,isForeignKey:o}},m=async(e,t,a,r,n)=>{const i=qs(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===t||e.emailField===t||e.usernameField===t),o=t.includes(".");if(Ks(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 Ws.enrichWithUserData(i.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let c;c=o?d.sort((e,s)=>{const r=t.split(".").reduce((e,t)=>e?.[t],e)||"",n=t.split(".").reduce((e,t)=>e?.[t],s)||"",i=String(r).localeCompare(String(n),"pt-BR");return"asc"===a?i:-i}):((e,t,a)=>[...e].sort((e,s)=>{const r=e[t]||"",n=s[t]||"",i=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===a?i:-i}))(d,t,a);const u=((e,t=1,a=25)=>{const s=(t-1)*a,r=s+a,n=e.slice(s,r);return{data:n,pagination:{currentPage:t,totalPages:Math.ceil(e.length/a),totalItems:n.length,totalCount:e.length,itemsPerPage:a,hasNextPage:r<e.length,hasPreviousPage:t>1}}})(c,r,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 Ws.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.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:s="desc",page:r=1,limit:n=25,...i}=e;return{search:t,sortField:a,sortDirection:s,page:r,limit:n,additionalFilters:i}})(e),{query:p}=u(t,a,n,c),h=((e,t,a)=>{const s=(t-1)*a,r=s+a-1;return e.range(s,r)})(p,i,o),{data:f,error:x,count:g}=await h;if(x)throw new Error(`Error fetching ${r}: ${x.message}`);let b=((e,t,a,s)=>{const r=Math.ceil((t||0)/s);return{data:e,currentPage:a,totalPages:r,totalItems:t||0,itemsPerPage:s,hasNextPage:a<r,hasPreviousPage:a>1}})(f||[],g,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const t=qs(s.userIdFields,s.userFieldsMapping);return e.some(e=>t.some(t=>e[t.idField]))})(b.data)){const e=await m(b.data,a,n,i,o);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:t,error:a}=await c().select(i||"*").eq("id",e).maybeSingle();if(a)throw new Error(`Error fetching ${r}: ${a.message}`);return t},async create(e){const t=it(e),a=Object.entries(t).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),{data:s,error:n}=await c().insert(a).select().single();if(n)throw new Error(`Error creating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from create ${r} operation`);return s},async update(e,t){const a={...it(t),updated_at:(new Date).toISOString()},{data:s,error:n}=await c().update(a).eq("id",e).select().single();if(n)throw new Error(`Error updating ${r}: ${n.message}`);if(!s)throw new Error(`No data returned from update ${r} operation`);return s},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 ${r}: ${a.message}`)}}}const Qs=()=>{us.clearManualLogout()},Xs=e=>e?.placeId||null,Js=e=>e?.placeName||null,Ys=e=>({placeId:Xs(e),placeName:Js(e)}),Zs=class{static async initialize(){try{if(!us.hasAllTokens()||!us.areAllTokensValid())return us.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=us.getAccessToken(),a=us.getIdToken();Qs();const s=this.extractUserFromIdToken(a),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(t),i=us.extractTokenData(),o=i?.alias;let l=null;if(o&&r.some(e=>e.alias===o))l=o;else{const e=us.getSelectedAlias(),t=e&&r.some(t=>t.alias===e);l=t?e:n||r[0]?.alias||null}!us.isSupabaseTokenValid()&&l&&await Cs.attemptRegeneration();let d=null;if(l){const e=us.getCompanyId(l),t=r.find(e=>e.alias===l);t&&(d={id:e||t.id,name:t.name,alias:t.alias})}let c=null,u=null;if(s?.id&&l){const t=us.getCompanyId(l);if(t)try{const e=(await _s.fetchActiveUsersMap(l,t)).get(s.id);if(e){const t=Ys(e);c=t.placeId,u=t.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:s,alias:l,companies:r,selectedUnit:d,userId:s?.id||null,userAlias:s?.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=Ns(),{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 s=new URL("/callback",window.location.origin);return s.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=us.generateOAuthState();us.setOAuthState(e);const t=us.generateOAuthNonce();us.setOAuthNonce(t);const a=`${window.location.origin}/callback`,s=new URL(Is.oauth.authUrl);s.searchParams.set("client_id",Is.oauth.clientId),s.searchParams.set("response_type",Is.oauth.responseType),s.searchParams.set("scope",Is.oauth.scope),s.searchParams.set("redirect_uri",a),s.searchParams.set("state",e),s.searchParams.set("nonce",t),s.searchParams.set("response_mode","fragment"),Ms(),window.location.href=s.toString()}static async processCallback(){try{if(us.hasAllTokens()){if(!us.getValidSupabaseToken()){us.getAccessToken();await Cs.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),s=a("access_token"),r=a("id_token"),n=a("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!s||!r)throw new Error("Tokens não encontrados na URL de callback");us.setAccessToken(s),us.setIdToken(r),Qs();const i=this.extractAliasFromAccessToken(s);if(i)us.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(r);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");us.setSelectedAlias(e[0].alias)}if(!await Cs.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return us.clearOAuthState(),us.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){us.setManualLogout(),us.clearAll(),window.location.href="/login"}static decodeToken(e){return ss.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 s=t[e].split(";");if(s.length>=4)a.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=t[e].split("|");s&&r&&a.push({id:"",alias:s.trim(),name:r.trim()})}}}),a}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}};Cs.setLogoutCallback(()=>{Zs.logout()});let er=Zs;const tr=t.createContext(void 0),ar=()=>{const e=t.useContext(tr);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function sr({queryKey:e,service:a,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:i}){const[l,d]=b.useSearchParams(),c=g.useQueryClient(),{alias:u,userId:m,isAuthenticated:p}=ar(),h=t.useCallback(t=>{const a=`${e}_${t}`,s=l.get(a);return s||(l.get(t)||"")},[l,e]),f=h("search"),x=h("sortField")||Rs.sorting.defaultField,v=h("sortDirection")||Rs.sorting.defaultDirection,y=parseInt(h("page")||"1"),N=parseInt(h("limit")||String(Rs.pagination.defaultPageSize)),j=f,w=t.useMemo(()=>({search:j,sortField:x,sortDirection:v,page:y,limit:N,...n}),[j,x,v,y,N,n]),k=t.useCallback(()=>a.getAll(w),[a,w]),C=g.useQuery({queryKey:[e,u,m,w],queryFn:k,enabled:!!u&&p});if(!C)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const S=g.useMutation({mutationFn:a.create,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(zs.success.created(s)),i?.()},onError:e=>{o.toast.error(`${zs.error.create(s)}: ${e.message}`)}}),P=g.useMutation({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(zs.success.updated(s)),i?.()},onError:e=>{o.toast.error(`${zs.error.update(s)}: ${e.message}`)}}),E=g.useMutation({mutationFn:a.delete,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(zs.success.deleted(s))},onError:e=>{o.toast.error(`${zs.error.delete(s)}: ${e.message}`)}}),T=t.useCallback(t=>{const a={...Object.fromEntries(l)};Object.entries(t).forEach(([t,s])=>{const r=`${e}_${t}`;""===s||0===s?delete a[r]:a[r]=String(s)}),delete a.sortField,delete a.sortDirection,d(a)},[l,d,e]),A=t.useCallback(e=>{T({search:e,page:1})},[T]),_=t.useCallback(e=>{T({sortField:e,sortDirection:x===e&&"asc"===v?"desc":"asc",page:1})},[x,v,T]),I=t.useCallback(e=>{T({page:e})},[T]),R=t.useCallback(e=>{T({limit:e,page:1})},[T]),L=t.useCallback(()=>{const t=Object.fromEntries(l),a=`${e}_`,s=Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith(a)));d(s)},[d,l,e]),[M,O]=t.useState([]),D=t.useCallback(e=>{O(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),F=t.useCallback(()=>{const e=C?.data?.data.map(e=>e.id)||[];O(t=>t.length===e.length?[]:e)},[C?.data?.data]),z=t.useCallback(()=>{O([])},[]),$=t.useMemo(()=>{const e=C?.data?.data.map(e=>e.id)||[];return e.length>0&&M.length===e.length},[M,C?.data?.data]),U=g.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(t,a)=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(`${a.length} ${s}(s) deletado(s) com sucesso`),z()},onError:e=>{o.toast.error(`Erro ao deletar itens: ${e.message}`)}}),V=t.useCallback((e,t)=>{const a=t?t(e):e;e.id?P.mutate({id:e.id,data:a}):S.mutate({...a,alias:u})},[u,S,P]);return{entities:C?.data?.data||[],pagination:{data:C?.data?.data||[],currentPage:C?.data?.currentPage||1,totalPages:C?.data?.totalPages||1,totalItems:C?.data?.totalItems||0,itemsPerPage:C?.data?.itemsPerPage||Rs.pagination.defaultPageSize,hasNextPage:C?.data?.hasNextPage||!1,hasPreviousPage:C?.data?.hasPreviousPage||!1},isLoading:C?.isLoading??!0,isCreating:S?.isPending??!1,isUpdating:P?.isPending??!1,isDeleting:E?.isPending??!1,error:C?.error||null,searchTerm:f,sortField:x,sortDirection:v,currentPage:y,itemsPerPage:N,queryKey:e,createEntity:S.mutate,updateEntity:(e,t)=>P.mutate({id:e,data:t}),deleteEntity:E.mutate,save:V,handleSearch:A,handleSort:_,handlePageChange:I,handleItemsPerPageChange:R,clearFilters:L,refetch:C.refetch,selectedIds:M,selectItem:D,selectAll:F,clearSelection:z,isAllSelected:$,bulkDelete:e=>U.mutateAsync(e),isBulkDeleting:U.isPending}}const rr=J.Root,nr=J.Trigger,ir=J.Portal,or=B.forwardRef(({className:t,...a},s)=>e.jsx(J.Overlay,{className:nt("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:s}));or.displayName=J.Overlay.displayName;const lr=B.forwardRef(({className:t,...a},s)=>e.jsxs(ir,{children:[e.jsx(or,{}),e.jsx(J.Content,{ref:s,className:nt("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",t),...a})]}));lr.displayName=J.Content.displayName;const dr=({className:t,...a})=>e.jsx("div",{className:nt("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});dr.displayName="AlertDialogHeader";const cr=({className:t,...a})=>e.jsx("div",{className:nt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});cr.displayName="AlertDialogFooter";const ur=B.forwardRef(({className:t,...a},s)=>e.jsx(J.Title,{ref:s,className:nt("text-lg font-semibold",t),...a}));ur.displayName=J.Title.displayName;const mr=B.forwardRef(({className:t,...a},s)=>e.jsx(J.Description,{ref:s,className:nt("text-sm text-muted-foreground",t),...a}));mr.displayName=J.Description.displayName;const pr=B.forwardRef(({className:t,...a},s)=>e.jsx(J.Action,{ref:s,className:nt(ot(),t),...a}));pr.displayName=J.Action.displayName;const hr=B.forwardRef(({className:t,...a},s)=>e.jsx(J.Cancel,{ref:s,className:nt(ot({variant:"outline"}),"mt-2 sm:mt-0",t),...a}));hr.displayName=J.Cancel.displayName;const fr=({open:t,onOpenChange:a,item:s,onConfirm:r,entityName:n="item",isDeleting:i=!1})=>{const{t:o}=Ya(),d=()=>{a(!1)};return s?e.jsx(rr,{open:t,onOpenChange:d,children:e.jsxs(lr,{className:"sm:max-w-[420px] bg-white",children:[e.jsxs("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.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Fechar"})]}),e.jsxs("div",{className:"flex flex-col items-center text-center space-y-3 py-2",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx(l.AlertTriangle,{className:"w-8 h-8 text-destructive"})}),e.jsx(ur,{className:"text-xl font-semibold",children:"Tem certeza?"}),e.jsx(mr,{asChild:!0,children:e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{children:"Você está prestes a excluir este registro."}),e.jsx("p",{children:"Esta ação não pode ser desfeita."})]})})]}),e.jsxs("div",{className:"flex flex-row gap-2 justify-center mt-6",children:[e.jsx(pr,{onClick:()=>{s&&(r(s),a(!1))},disabled:i,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:o(i?"deleting":"confirm_delete")}),e.jsx(hr,{onClick:d,className:"mt-0 border-none bg-transparent hover:bg-muted text-foreground shadow-none",children:"Cancelar"})]})]})}):null},xr=B.forwardRef(({className:t,...a},s)=>e.jsx("table",{ref:s,className:nt("w-full caption-bottom text-sm",t),...a}));xr.displayName="Table";const gr=B.forwardRef(({className:t,...a},s)=>e.jsx("thead",{ref:s,className:nt("[&_tr]:border-b sticky top-0 z-[1] bg-background",t),...a}));gr.displayName="TableHeader";const br=B.forwardRef(({className:t,...a},s)=>e.jsx("tbody",{ref:s,className:nt("[&_tr:last-child]:border-0",t),...a}));br.displayName="TableBody";const vr=B.forwardRef(({className:t,...a},s)=>e.jsx("tfoot",{ref:s,className:nt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...a}));vr.displayName="TableFooter";const yr=B.forwardRef(({className:t,...a},s)=>e.jsx("tr",{ref:s,className:nt("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",t),...a}));yr.displayName="TableRow";const Nr=B.forwardRef(({className:t,...a},s)=>e.jsx("th",{ref:s,className:nt("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}));Nr.displayName="TableHead";const jr=B.forwardRef(({className:t,...a},s)=>e.jsx("td",{ref:s,className:nt("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",t),...a}));jr.displayName="TableCell";const wr=B.forwardRef(({className:t,...a},s)=>e.jsx("caption",{ref:s,className:nt("mt-4 text-sm text-muted-foreground",t),...a}));function kr({rows:t=5,columns:a=4}){return e.jsx("div",{className:"w-full",children:e.jsxs("div",{className:"rounded-md border",children:[e.jsx("div",{className:"border-b bg-muted/50 px-4 py-3",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:a}).map((t,a)=>e.jsx(Ea,{className:"h-4 w-24"},a))})}),e.jsx("div",{children:Array.from({length:t}).map((t,s)=>e.jsx("div",{className:"border-b px-4 py-3 last:border-0",children:e.jsx("div",{className:"flex space-x-4",children:Array.from({length:a}).map((t,a)=>e.jsx(Ea,{className:"h-4 w-20"},a))})},s))})]})})}function Cr({count:t=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:t}).map((t,a)=>e.jsxs(pt,{children:[e.jsxs(ht,{children:[e.jsx(Ea,{className:"h-4 w-3/4"}),e.jsx(Ea,{className:"h-3 w-1/2"})]}),e.jsx(gt,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ea,{className:"h-3 w-full"}),e.jsx(Ea,{className:"h-3 w-2/3"})]})})]},a))})}wr.displayName="TableCaption";const Sr={default:l.FileX,search:l.Search,error:l.AlertCircle};function Pr({icon:t,title:a,description:s,action:r,className:n,variant:i="default"}){const o=t?()=>t:Sr[i];return e.jsxs("div",{className:nt("flex flex-col items-center justify-center py-12 px-4 text-center",n),children:[e.jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:e.jsx(o,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:a}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(lt,{onClick:r.onClick,variant:"outline",children:r.label})]})}const Er=Y.Root,Tr=Y.Trigger,Ar=Y.Group,_r=Y.Portal,Ir=Y.Sub,Rr=Y.RadioGroup,Lr=B.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(Y.SubTrigger,{ref:n,className:nt("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Lr.displayName=Y.SubTrigger.displayName;const Mr=B.forwardRef(({className:t,...a},s)=>e.jsx(Y.SubContent,{ref:s,className:nt("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}));Mr.displayName=Y.SubContent.displayName;const Or=B.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(Y.Portal,{children:e.jsx(Y.Content,{ref:r,sideOffset:a,className:nt("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-white 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),...s})}));Or.displayName=Y.Content.displayName;const Dr=B.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Y.Item,{ref:r,className:nt("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),...s}));Dr.displayName=Y.Item.displayName;const Fr=B.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(Y.CheckboxItem,{ref:n,className:nt("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",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Y.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));Fr.displayName=Y.CheckboxItem.displayName;const zr=B.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Y.RadioItem,{ref:r,className:nt("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",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Y.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));zr.displayName=Y.RadioItem.displayName;const $r=B.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Y.Label,{ref:r,className:nt("px-2 py-1.5 text-sm font-semibold",a&&"pl-8",t),...s}));$r.displayName=Y.Label.displayName;const Ur=B.forwardRef(({className:t,...a},s)=>e.jsx(Y.Separator,{ref:s,className:nt("-mx-1 my-1 h-px bg-muted",t),...a}));Ur.displayName=Y.Separator.displayName;const Vr=({className:t,...a})=>e.jsx("span",{className:nt("ml-auto text-xs tracking-widest opacity-60",t),...a});Vr.displayName="DropdownMenuShortcut";const qr=({onEdit:t,onDelete:a,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:i=[],renderAs:o})=>{const{t:d}=Ya(),c=[];if(t){const e={icon:l.Edit,label:d("edit"),onClick:t};c.push(e)}if(i.forEach(e=>{c.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:d(r?"deactivate":"activate"),onClick:s};c.push(e)}if(n&&a){const e={icon:l.Trash2,label:d("delete"),onClick:a,destructive:!0};c.push(e)}return"dropdown"===o?e.jsx(e.Fragment,{children:c.map((t,a)=>e.jsxs(Dr,{onClick:t.onClick,className:t.destructive?"text-destructive":"",children:[e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},a))}):e.jsx(e.Fragment,{children:c.map((t,a)=>e.jsxs(lt,{variant:"ghost",size:"sm",onClick:t.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(t.destructive?"text-destructive hover:text-destructive":""),children:[e.jsx(t.icon,{className:"h-4 w-4 mr-2"}),t.label]},a))})},Br=({onEdit:t,onDelete:a,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:i=[]})=>e.jsxs(Er,{children:[e.jsx(Tr,{asChild:!0,children:e.jsx(lt,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(Or,{align:"end",className:"bg-background border border-border shadow-lg w-[160px]",children:e.jsx(qr,{onEdit:t?e=>{e?.stopPropagation(),t?.()}:void 0,onDelete:a?e=>{e?.stopPropagation(),a?.()}:void 0,onToggleStatus:r?e=>{e?.stopPropagation(),r?.()}:void 0,isActive:n,canDelete:s&&!!a,customActions:i,renderAs:"dropdown"})})]}),Wr=Z.Root,Hr=Z.Trigger,Kr=Z.Group,Gr=Z.Portal,Qr=Z.Sub,Xr=Z.RadioGroup,Jr=B.forwardRef(({className:t,inset:a,children:s,...r},n)=>e.jsxs(Z.SubTrigger,{ref:n,className:nt("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",a&&"pl-8",t),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));Jr.displayName=Z.SubTrigger.displayName;const Yr=B.forwardRef(({className:t,...a},s)=>e.jsx(Z.SubContent,{ref:s,className:nt("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}));Yr.displayName=Z.SubContent.displayName;const Zr=B.forwardRef(({className:t,...a},s)=>e.jsx(Z.Portal,{children:e.jsx(Z.Content,{ref:s,className:nt("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})}));Zr.displayName=Z.Content.displayName;const en=B.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Z.Item,{ref:r,className:nt("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),...s}));en.displayName=Z.Item.displayName;const tn=B.forwardRef(({className:t,children:a,checked:s,...r},n)=>e.jsxs(Z.CheckboxItem,{ref:n,className:nt("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",t),checked:s,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Z.ItemIndicator,{children:e.jsx(l.Check,{className:"h-4 w-4"})})}),a]}));tn.displayName=Z.CheckboxItem.displayName;const an=B.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Z.RadioItem,{ref:r,className:nt("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",t),...s,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Z.ItemIndicator,{children:e.jsx(l.Circle,{className:"h-2 w-2 fill-current"})})}),a]}));an.displayName=Z.RadioItem.displayName;const sn=B.forwardRef(({className:t,inset:a,...s},r)=>e.jsx(Z.Label,{ref:r,className:nt("px-2 py-1.5 text-sm font-semibold text-foreground",a&&"pl-8",t),...s}));sn.displayName=Z.Label.displayName;const rn=B.forwardRef(({className:t,...a},s)=>e.jsx(Z.Separator,{ref:s,className:nt("-mx-1 my-1 h-px bg-border",t),...a}));rn.displayName=Z.Separator.displayName;const nn=({className:t,...a})=>e.jsx("span",{className:nt("ml-auto text-xs tracking-widest text-muted-foreground",t),...a});nn.displayName="ContextMenuShortcut";const on=t.memo(({checked:t,onCheckedChange:a})=>e.jsx(Gt,{checked:t,onCheckedChange:a}),(e,t)=>e.checked===t.checked),ln=({manager:a,columns:s,onEdit:r,onView:n,onToggleStatus:i,onDelete:o,renderActions:d,customRowActions:c,enableBulkActions:u=!1,onNew:m,newButtonLabel:p,showNewButton:h=!0,customActions:f=[],hideActionBar:x=!1})=>{const{t:g}=Ya(),{setSearchVisible:b}=ar(),[v,y]=t.useState(!1);t.useEffect(()=>(b(!0),()=>b(!1)),[b]),t.useEffect(()=>{const e=()=>y(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const N=t.useMemo(()=>(()=>{s.length;let e=0;const t=s.map(t=>{if(t.width)return e+=t.width,{...t,calculatedWidth:t.width,isFixed:!0};{const a=t.minWidth||120,s=t.weight||1;return e+=a,{...t,calculatedWidth:a,weight:s,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`}})})(),[s]),j=!x&&(m||f.length>0);return v?a.isLoading?e.jsx(Cr,{count:3}):0===a.entities.length?e.jsx(Pr,{title:g("empty_title"),description:g("empty_description"),variant:"search"}):e.jsxs("div",{className:"flex flex-col h-full",children:[j&&e.jsx("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[m&&h&&e.jsxs(lt,{onClick:m,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),p||g("new")]}),f.map((t,a)=>{const s=t.icon;return e.jsxs(lt,{onClick:t.action,variant:t.variant||"outline",children:[s&&e.jsx(s,{size:16,className:"mr-2"}),t.label]},a)})]})}),e.jsx("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:a.entities.map(t=>e.jsxs(Wr,{children:[e.jsx(Hr,{asChild:!0,children:e.jsx(pt,{className:nt("overflow-hidden cursor-pointer hover:bg-muted/50",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},children:e.jsx(gt,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[u&&e.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:e.jsx(on,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),e.jsxs("div",{className:"flex-1",children:[s.map(a=>e.jsxs("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[a.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:a.render?a.render(t):String(t[a.key]??"")})]},String(a.key))),(r||n||d)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(t):e.jsx(Br,{onEdit:r?()=>{r(t)}:void 0,onDelete:o?()=>o(t):void 0,onToggleStatus:i?()=>i(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})})]})]})})})}),e.jsx(Zr,{className:"w-[160px]",children:e.jsx(qr,{onEdit:r?()=>r(t):void 0,onDelete:o?()=>o(t):void 0,onToggleStatus:i?()=>i(t):void 0,isActive:t.is_actived,canDelete:!!o,customActions:c?c(t):[],renderAs:"context"})})]},t.id))})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[j&&e.jsx("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[m&&h&&e.jsxs(lt,{onClick:m,children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),p||g("new")]}),f.map((t,a)=>{const s=t.icon;return e.jsxs(lt,{onClick:t.action,variant:t.variant||"outline",children:[s&&e.jsx(s,{size:16,className:"mr-2"}),t.label]},a)})]})}),a.isLoading?e.jsx(kr,{rows:5,columns:s.length}):e.jsx("div",{className:"flex flex-col h-full overflow-hidden",children:e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(xr,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),N.map((t,a)=>e.jsx("col",{style:t.style},a)),e.jsx("col",{style:{width:"50px"}})]}),e.jsx(gr,{children:e.jsxs(yr,{children:[u&&e.jsx(Nr,{className:"w-[50px]",children:e.jsx(on,{checked:a.isAllSelected,onCheckedChange:a.selectAll})}),s.map(t=>{return e.jsx(Nr,{className:`${t.className||""} ${t.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:t.sortable?()=>a.handleSort(String(t.key)):void 0,children:e.jsxs("div",{className:"flex items-center "+(t.className?.includes("text-center")?"justify-center":""),children:[t.header,t.sortable&&(s=String(t.key),a.sortField!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===a.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]})},String(t.key));var s}),e.jsx(Nr,{className:"w-[50px] text-center",children:g("actions")})]})}),e.jsx(br,{children:0===a.entities.length?e.jsx(yr,{children:e.jsx(jr,{colSpan:u?s.length+2:s.length+1,className:"h-32",children:e.jsx(Pr,{title:g("empty_title"),description:g("empty_description"),variant:"search"})})}):a.entities.map(t=>e.jsxs(Wr,{children:[e.jsx(Hr,{asChild:!0,children:e.jsxs(yr,{className:nt("cursor-pointer hover:bg-muted/50",u&&a.selectedIds.includes(t.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?a.selectItem(t.id):r?.(t)},children:[u&&e.jsx(jr,{onClick:e=>e.stopPropagation(),children:e.jsx(on,{checked:a.selectedIds.includes(t.id),onCheckedChange:()=>a.selectItem(t.id)})}),s.map(a=>e.jsx(jr,{className:a.className,children:a.render?a.render(t):String(t[a.key]??"")},String(a.key))),e.jsx(jr,{className:"text-center",children:d?d(t):e.jsx(Br,{onEdit:r?()=>r(t):void 0,onDelete:o?()=>o(t):void 0,onToggleStatus:i?()=>i(t):void 0,isActive:t.is_actived,customActions:c?c(t):[]})})]})}),e.jsx(Zr,{className:"w-[160px]",children:e.jsx(qr,{onEdit:r?()=>r(t):void 0,onDelete:o?()=>o(t):void 0,onToggleStatus:i?()=>i(t):void 0,isActive:t.is_actived,canDelete:!!o,customActions:c?c(t):[],renderAs:"context"})})]},t.id))})]})})})]})};function dn(e,a,s,r){const[n,i]=t.useState({}),[o,l]=t.useState({}),d=t.useMemo(()=>e,[e]),c=e=>e instanceof Date&&!isNaN(e.getTime()),u=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{}}},m=(e,t)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(t)}catch(a){return u(e)}},p=(e,t,a)=>{if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length))return`${e.label} é obrigatório`;if(e.validation){let r;if("function"==typeof e.validation?r=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(r=e.validation.custom),r)try{const e=r(t,a);if(e)return e}catch(s){}}};t.useEffect(()=>{if(!r)return;const e=t=>{const a=[];return t.forEach(t=>{a.push(t),t.fields&&a.push(...e(t.fields))}),a},t=e(d),n={};t.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);c(e)&&(t=e.toISOString().split("T")[0])}else c(t)&&(t=t.toISOString().split("T")[0])}else t=u(e);n[e.name]=t}),t.forEach(e=>{const t=m(e,n);void 0!==t&&(n[e.name]=t)}),a&&Object.keys(a).forEach(e=>{t.find(t=>t.name===e)||void 0===a[e]||(n[e]=a[e])}),i(n),l({}),s&&s(n)},[d,a,s,r]);const h=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...h(e.fields))}),t},f=()=>{const e=h(d),t={};return e.forEach(e=>{const a=p(e,n[e.name],n);a&&(t[e.name]=a)}),l(t),0===Object.keys(t).length};return{formData:n,errors:o,updateField:(e,t)=>{i(a=>{const r={...a,[e]:t},n=((e,t)=>{let a={...t};const s=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...s(e.fields))}),t};return s(d).filter(t=>t.dependsOn===e).forEach(e=>{const t=m(e,a);void 0!==t&&(a={...a,[e.name]:t})}),a})(e,r);return s&&s(n),n}),o[e]&&l(t=>{const a={...t};return delete a[e],a});const a=h(d).find(t=>t.name===e);if(a){const s=p(a,t,n);s&&l(t=>({...t,[e]:s}))}},validateForm:f,handleSubmit:e=>t=>{t&&(t.preventDefault(),t.stopPropagation()),f()&&e(n)}}}const cn=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],un=({value:t="#3b82f6",onChange:a,label:s})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(mt,{children:s}),e.jsxs(ga,{children:[e.jsx(ba,{asChild:!0,children:e.jsxs(lt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:t}}),t]})}),e.jsx(va,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(mt,{htmlFor:"color-input",children:"Cor personalizada"}),e.jsx(ct,{id:"color-input",type:"color",value:t,onChange:e=>a?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(mt,{children:"Cores predefinidas"}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:cn.map(t=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:t},onClick:()=>a?.(t),"aria-label":`Selecionar cor ${t}`},t))})]})]})})]})]}),mn=B.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(ee.Root,{ref:r,className:nt("relative overflow-hidden",t),...s,children:[e.jsx(ee.Viewport,{className:"h-full w-full rounded-[inherit]",children:a}),e.jsx(pn,{}),e.jsx(ee.Corner,{})]}));mn.displayName=ee.Root.displayName;const pn=B.forwardRef(({className:t,orientation:a="vertical",...s},r)=>e.jsx(ee.ScrollAreaScrollbar,{ref:r,orientation:a,className:nt("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),...s,children:e.jsx(ee.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));pn.displayName=ee.ScrollAreaScrollbar.displayName;const hn={Star:l.Star,Heart:l.Heart,Home:l.Home,User:l.User,Settings:l.Settings,Mail:l.Mail,Phone:l.Phone,Calendar:l.Calendar,MapPin:l.MapPin,Camera:l.Camera,Image:l.Image,Music:l.Music,Video:l.Video,Book:l.Book,Bookmark:l.Bookmark,Search:l.Search,Filter:l.Filter,Edit:l.Edit,Trash2:l.Trash2,Plus:l.Plus,Minus:l.Minus,Check:l.Check,X:l.X,ChevronDown:l.ChevronDown,ChevronUp:l.ChevronUp,ChevronLeft:l.ChevronLeft,ChevronRight:l.ChevronRight,ArrowUp:l.ArrowUp,ArrowDown:l.ArrowDown,ArrowLeft:l.ArrowLeft,ArrowRight:l.ArrowRight,Clock:l.Clock,Bell:l.Bell,AlertCircle:l.AlertCircle,Info:l.Info,HelpCircle:l.HelpCircle,Download:l.Download,Upload:l.Upload,Share:l.Share,Copy:l.Copy,Save:l.Save,FileText:l.FileText,Folder:l.Folder,FolderOpen:l.FolderOpen,Archive:l.Archive,Lock:l.Lock,Unlock:l.Unlock,Eye:l.Eye,EyeOff:l.EyeOff,Shield:l.Shield,Key:l.Key,Zap:l.Zap,Flame:l.Flame,Sparkles:l.Sparkles,Award:l.Award,Trophy:l.Trophy,Target:l.Target},fn=({value:a="Star",onChange:s,label:r})=>{const{t:n}=Ya(),[i,o]=t.useState(""),d=Object.entries(hn).filter(([e])=>e.toLowerCase().includes(i.toLowerCase())),c=hn[a]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(mt,{children:r}),e.jsxs(ga,{children:[e.jsx(ba,{asChild:!0,children:e.jsxs(lt,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(c,{className:"h-4 w-4 mr-2"}),a]})}),e.jsx(va,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(mt,{htmlFor:"icon-search",children:n("search")}),e.jsx(ct,{id:"icon-search",placeholder:n("search"),value:i,onChange:e=>o(e.target.value)})]}),e.jsx(mn,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:d.map(([t,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(a===t?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(t),title:t,children:e.jsx(r,{className:"h-4 w-4"})},t))})})]})})]})]})},xn=B.forwardRef(({className:t,...a},s)=>e.jsx(te.Root,{className:nt("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:s,children:e.jsx(te.Thumb,{className:nt("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")})}));xn.displayName=te.Root.displayName;const gn=(e={})=>{const{user:t,alias:a}=ar(),{enabled:s=!0}=e;return g.useQuery({queryKey:["qualiex-users",a],queryFn:()=>_s.getUsers(a),enabled:s&&!!a&&!!t,retry:2,retryDelay:1e3})},bn=({value:t="",onChange:a,placeholder:s,disabled:r,className:n,enabled:i})=>{const{t:o}=Ya(),{data:l=[],isLoading:d,error:c}=gn({enabled:i});return e.jsx(ts,{value:t,onChange:a,options:l,isLoading:d,error:c,getOptionValue:e=>e.userId,getOptionLabel:e=>e.userName,placeholder:s||o("search_placeholder"),searchPlaceholder:o("search_placeholder"),emptyMessage:o("no_results"),disabled:r,className:n})};function vn({title:a,sections:s,initialData:r,onSubmit:n,onCancel:i,open:o,submitButtonText:l,isLoading:d=!1,usersData:c}){const{t:u}=Ya(),[m,p]=t.useState(s?.[0]?.id||""),h=t.useRef(null),[f,x]=t.useState(null),g=t.useCallback(e=>{h.current=e,x(e)},[]),b=t.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:v,errors:y,updateField:N,handleSubmit:j}=dn(b,r,void 0,o),w=t.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(v):e.disabled||!1})):[],[s,v]),k=t.useMemo(()=>{const e=w.find(e=>e.id===m);if(e&&!e.disabled)return m;const t=w.find(e=>!e.disabled);return t?.id||m},[w,m]);t.useEffect(()=>{k!==m&&p(k)},[k,m]);const C=w.find(e=>e.id===k),S=t=>{const a=(t.computedValue,v[t.name]),s=void 0!==a?a:"",r=y[t.name];switch(t.type){case"group":const a="horizontal"===t.layout,n=a?`flex gap-3 w-full ${t.className||""}`:"space-y-3",i=a?nt("space-y-2 w-full",t.wrapperClassName):nt("space-y-2",t.className,t.wrapperClassName);return e.jsxs("div",{className:i,children:[t.label,e.jsx("div",{className:n,children:t.fields?.map(e=>S(e))})]},t.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsx(bn,{value:s||"",onChange:e=>N(t.name,e),placeholder:t.placeholder,disabled:t.disabled,className:r?"border-red-500":""}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsx(Qt,{id:t.name,value:s||"",onChange:e=>{N(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,rows:t.rows,maxLength:t.maxLength,className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"select":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsxs(Ft,{value:String(s),onValueChange:e=>{N(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,children:[e.jsx(Ut,{className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e.jsx($t,{placeholder:t.placeholder})}),e.jsx(Bt,{children:t.options?.map(t=>e.jsx(Ht,{value:t.value,children:t.label},t.value))})]}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx(ts,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>N(t.name,e),placeholder:t.placeholder,disabled:t.disabled,error:r,popoverContainer:f,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"date":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsx(ct,{id:t.name,type:"date",value:String(s),onChange:e=>N(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,className:nt("w-full",r?"border-red-500":"",t.disabled?"bg-gray-100 cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"color":return e.jsxs("div",{children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label," ",t.required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(ct,{id:t.name,type:"color",value:s||t.defaultValue||"#000000",onChange:e=>N(t.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"color-picker":return e.jsxs("div",{children:[e.jsx(un,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"#3b82f6",onChange:e=>N(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"icon-picker":return e.jsxs("div",{children:[e.jsx(fn,{label:`${t.label} ${t.required?"*":""}`,value:s||t.defaultValue||"Star",onChange:e=>N(t.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},t.name);case"custom":if(!t.component)return null;const o=t.component,l="function"==typeof t.componentProps?t.componentProps(v):t.componentProps||{};return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[t.label&&e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsx(o,{value:s,onChange:e=>{N(t.name,e),t.onValueChange&&t.onValueChange(e)},disabled:t.disabled,error:r,popoverContainer:f,...l}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"number":return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsx(ct,{id:t.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const a=e.target.value,s=""===a?null:Number(a);N(t.name,s)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:t.min,step:t.step||"1"}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"checkbox":return e.jsxs("div",{className:`flex items-center space-x-2 ${t.className||""}`,children:[e.jsx(Gt,{id:t.name,checked:!!s,onCheckedChange:e=>N(t.name,e),disabled:t.disabled}),e.jsx(mt,{htmlFor:t.name,className:"cursor-pointer",children:t.label}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name);case"switch":return e.jsxs("div",{className:`flex items-center justify-between space-x-2 ${t.className||""}`,children:[e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsx(xn,{id:t.name,checked:!!s,onCheckedChange:e=>N(t.name,e),disabled:t.disabled}),r&&e.jsx("p",{className:"text-sm text-red-500 mt-2",children:r})]},t.name);default:return e.jsxs("div",{className:`space-y-2 ${t.className||""}`,children:[e.jsx(mt,{htmlFor:t.name,children:t.label}),e.jsx(ct,{id:t.name,type:"text",value:s||"",onChange:e=>{N(t.name,e.target.value)},placeholder:t.placeholder,disabled:t.disabled,className:`${r?"border-red-500":""} ${t.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:t.disabled}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},t.name)}},P=t.useCallback(()=>{if(!C)return null;if(C.disabled)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-3 mb-4",children:e.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),e.jsx("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(C.component){const t=C.component;return e.jsx(t,{formData:v,updateField:N,errors:y,users:c,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(S)})},[C,v,N,y,c,S]),E=e.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[w.length>1&&e.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:e.jsx("div",{className:"flex space-x-2",children:w.map(t=>e.jsx(lt,{variant:k===t.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const t=w.find(t=>t.id===e);t&&!t.disabled&&p(e)})(t.id),disabled:t.disabled,className:t.disabled?"opacity-50 cursor-not-allowed":"",children:t.title},t.id))})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"text-muted-foreground",children:u("loading")})}):e.jsxs("form",{onSubmit:j(n),className:"space-y-3 md:space-y-4",children:[P(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(lt,{type:"button",variant:"outline",onClick:i,children:u("cancel")}),e.jsx(lt,{type:"submit",disabled:d,children:l||u("save")})]})]})})]});return e.jsx(vt,{open:o,onOpenChange:e=>{!1===e&&!0===o&&i()},children:e.jsxs(kt,{ref:g,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(Ct,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e.jsx(Pt,{className:"text-white",children:a}),e.jsx(Et,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),E]})})}function yn({currentPage:t,totalPages:a,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:i,variant:o="full"}){const d=(t-1)*r+1,c=Math.min(t*r,s);return e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[e.jsx("div",{className:"flex items-center gap-2",children:"full"===o&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),e.jsxs(Ft,{value:String(r),onValueChange:e=>i(Number(e)),children:[e.jsx(Ut,{className:"h-8 w-[70px]",children:e.jsx($t,{})}),e.jsxs(Bt,{children:[e.jsx(Ht,{value:"10",children:"10"}),e.jsx(Ht,{value:"25",children:"25"}),e.jsx(Ht,{value:"50",children:"50"}),e.jsx(Ht,{value:"100",children:"100"})]})]})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[d,"-",c," de ",s," itens"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(lt,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(lt,{variant:"outline",size:"sm",onClick:()=>n(t-1),disabled:1===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronLeft,{size:16})}),e.jsxs("div",{className:"flex items-center gap-1 px-2",children:[e.jsx("span",{className:"text-sm font-medium",children:t}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"de"}),e.jsx("span",{className:"text-sm font-medium",children:a})]}),e.jsx(lt,{variant:"outline",size:"sm",onClick:()=>n(t+1),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(lt,{variant:"outline",size:"sm",onClick:()=>n(a),disabled:t===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function Nn({manager:t}){return e.jsx(yn,{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 jn=({selectedCount:t,onClearSelection:a,onBulkDelete:s,customActions:r=[],isLoading:n=!1})=>{const{t:i}=Ya();return e.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:i("selected",{count:t})}),e.jsxs(lt,{variant:"ghost",size:"sm",onClick:a,className:"h-7 px-2",children:[e.jsx(l.X,{size:14,className:"mr-1"}),i("clear")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.map((t,a)=>{const s=t.icon;return e.jsxs(lt,{variant:t.variant||"outline",size:"sm",onClick:()=>t.action([]),disabled:n,className:"h-7",children:[s&&e.jsx(s,{size:14,className:"mr-1"}),t.label]},a)}),s&&e.jsxs(lt,{variant:"destructive",size:"sm",onClick:s,disabled:n,className:"h-7",children:[e.jsx(l.Trash2,{size:14,className:"mr-1"}),i("delete")]})]})]})},wn={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},kn={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Cn={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Sn({children:t,direction:a="column",gap:s="md",align:r="stretch",justify:n="start",wrap:i=!1,className:o}){return e.jsx("div",{className:nt("flex","column"===a?"flex-col":"flex-row",wn[s],kn[r],Cn[n],i&&"flex-wrap",o),children:t})}function Pn({manager:t,filters:a,inline:s=!1}){const{t:r}=Ya(),{isSearchVisible:n}=ar(),i=t.searchTerm,o=e.jsxs(e.Fragment,{children:[a.some(e=>"search"===e.type)&&!n&&e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ct,{placeholder:r("search"),value:t.searchTerm,onChange:e=>t.handleSearch(e.target.value),className:"pl-10"})]}),a.filter(e=>"select"===e.type&&e.options).map((t,a)=>e.jsxs("select",{value:t.value||"",onChange:e=>t.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:[t.placeholder&&e.jsx("option",{value:"",children:t.placeholder}),t.options.map(t=>e.jsx("option",{value:t.value,children:t.label},t.value))]},`select-${a}`)),a.filter(e=>"custom"===e.type&&e.component).map((t,a)=>{const r=t.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...t.props})},`custom-${a}`)}),i&&e.jsxs(lt,{variant:"outline",onClick:t.clearFilters,className:"whitespace-nowrap",children:[e.jsx(l.X,{className:"h-4 w-4 mr-2"}),r("clear")]})]});return s?e.jsx("div",{className:"flex items-center gap-2",children:o}):e.jsx(Sn,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(Sn,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:o})})}function En({manager:a,config:s,formSections:r,onSave:n,onToggleStatus:i,defaultSort:o}){a&&a.queryKey;const{t:d}=Ya(),{setSearchVisible:c}=ar(),[u,m]=b.useSearchParams(),[p,h]=t.useState(!1),[f,x]=t.useState(null),[g,v]=t.useState({isOpen:!1,entityId:null,entityName:""}),[y,N]=t.useState({isOpen:!1,count:0});t.useEffect(()=>(c(!0),()=>{c(!1)}),[c]),t.useEffect(()=>{if(o&&a){const e=`${a.queryKey}_sortField`,t=`${a.queryKey}_sortDirection`;if(!u.has(e)&&!u.has(t)){const a=Object.fromEntries(u);a[e]=o.column,a[t]=o.direction,m(a)}}},[]);return e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[s.enableBulkActions&&a.selectedIds.length>0&&e.jsx(jn,{selectedCount:a.selectedIds.length,onClearSelection:a.clearSelection,onBulkDelete:s.bulkActions&&s.bulkActions.length>0?void 0:()=>{N({isOpen:!0,count:a.selectedIds.length})},customActions:s.bulkActions,isLoading:a.isBulkDeleting}),e.jsxs("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(lt,{onClick:()=>{s.onNew?s.onNew():(x(null),h(!0))},children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),d("new")]}),s.customActions?.map((t,a)=>e.jsxs(lt,{onClick:t.action,variant:t.variant||"outline",children:[t.icon&&e.jsx(t.icon,{size:16,className:"mr-2"}),t.label]},a))]}),s.filters&&s.filters.length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e.jsx(Pn,{manager:a,filters:s.filters,inline:!0})})]}),e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:s.customListView?e.jsx("div",{className:"flex-1 overflow-auto p-4",children:s.customListView(a.entities,a)}):e.jsx(ln,{manager:a,columns:s.columns,onEdit:e=>{s.onEdit?s.onEdit(e):(x(e),h(!0))},onDelete:e=>{v({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:i,enableBulkActions:s.enableBulkActions,customRowActions:s.customRowActions})}),e.jsx("div",{className:"flex-shrink-0 border-t bg-background",children:e.jsx(Nn,{manager:a})}),!s.useCustomRouting&&e.jsx(vn,{open:p,title:f?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:f||void 0,onSubmit:e=>{n(e),h(!1),x(null)},onCancel:()=>{h(!1),x(null)},isLoading:a.isLoading,submitButtonText:d(f?"update":"create")}),e.jsx(fr,{open:g.isOpen,onOpenChange:()=>{v({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{g.entityId&&(a.deleteEntity(g.entityId),v({isOpen:!1,entityId:null,entityName:""}))},item:g.entityId?{id:g.entityId,title:g.entityName}:void 0,entityName:s.entityName,isDeleting:a.isDeleting}),e.jsx(fr,{open:y.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),onConfirm:()=>(a.bulkDelete?.(a.selectedIds),void N({isOpen:!1,count:0})),item:{id:"bulk",title:`${y.count} ${1===y.count?s.entityName:s.entityNamePlural}`},entityName:s.entityNamePlural,isDeleting:a.isBulkDeleting,isBulk:!0,bulkCount:y.count})]})}function Tn(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 An(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const _n=B.forwardRef(({className:t,value:a,...s},r)=>e.jsx(ae.Root,{ref:r,className:nt("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",t),...s,children:e.jsx(ae.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(a||0)}%)`}})}));function In({steps:t,currentStepIndex:a,onStepClick:s,className:r}){return e.jsx("div",{className:nt("flex items-center justify-between mb-6",r),children:t.map((a,r)=>e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("div",{className:nt("flex items-center justify-center w-10 h-10 rounded-full border-2 transition-colors font-medium",a.isActive&&"border-primary bg-primary text-primary-foreground",a.isCompleted&&"border-primary bg-primary text-primary-foreground",!a.isActive&&!a.isCompleted&&"border-muted-foreground/30 text-muted-foreground bg-background",s&&!a.isDisabled&&"cursor-pointer hover:border-primary/50",a.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>s&&!a.isDisabled&&s(r),role:s&&!a.isDisabled?"button":void 0,tabIndex:s&&!a.isDisabled?0:void 0,"aria-label":`${a.label} - ${a.isCompleted?"Completo":a.isActive?"Atual":"Pendente"}`,children:a.isCompleted?e.jsx(l.Check,{className:"w-5 h-5"}):r+1}),r<t.length-1&&e.jsx("div",{className:nt("flex-1 h-0.5 mx-2 transition-colors",a.isCompleted?"bg-primary":"bg-muted-foreground/30"),"aria-hidden":"true"})]},a.id))})}function Rn({steps:t,currentStepIndex:a,onStepClick:s,className:r}){return e.jsx("div",{className:nt("flex items-center gap-2 mb-6 overflow-x-auto",r),children:t.map((a,r)=>e.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap",children:[e.jsxs("div",{className:nt("flex items-center gap-2 px-3 py-2 rounded-md transition-colors",a.isActive&&"bg-primary text-primary-foreground font-medium",a.isCompleted&&"bg-primary/10 text-primary",!a.isActive&&!a.isCompleted&&"bg-muted text-muted-foreground",s&&!a.isDisabled&&"cursor-pointer hover:bg-primary/20",a.isDisabled&&"opacity-50 cursor-not-allowed"),onClick:()=>s&&!a.isDisabled&&s(r),role:s&&!a.isDisabled?"button":void 0,tabIndex:s&&!a.isDisabled?0:void 0,"aria-label":`${a.label} - ${a.isCompleted?"Completo":a.isActive?"Atual":"Pendente"}`,children:[e.jsx("span",{className:"text-sm font-medium",children:r+1}),e.jsx("span",{className:"text-sm",children:a.label}),a.isCompleted&&e.jsx(l.Check,{className:"w-4 h-4 ml-1"})]}),r<t.length-1&&e.jsx("span",{className:"text-muted-foreground","aria-hidden":"true",children:"/"})]},a.id))})}function Ln({steps:t,currentStepIndex:a,className:s}){const r=t[a],n=(a+1)/t.length*100;return e.jsxs("div",{className:nt("mb-6 space-y-2",s),children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Etapa ",a+1," de ",t.length]}),e.jsx("span",{className:"font-medium",children:r?.label})]}),e.jsx(_n,{value:n,className:"h-2"})]})}function Mn({isFirstStep:t,isLastStep:a,canGoNext:s,canGoPrevious:r,isLoading:n,onPrevious:i,onNext:o,onSubmit:l,previousButtonText:d,nextButtonText:c,submitButtonText:u}){const{t:m}=Ya();return e.jsxs(e.Fragment,{children:[e.jsx("div",{children:r&&!t&&e.jsx(lt,{type:"button",variant:"outline",onClick:i,disabled:n,children:d||m("previous")})}),e.jsxs("div",{className:"flex gap-2",children:[s&&!a&&e.jsx(lt,{type:"button",onClick:o,disabled:n,children:c||m("next")}),a&&e.jsx(lt,{type:"button",onClick:l,disabled:n,children:n?m("saving"):u||m("save")})]})]})}_n.displayName=ae.Root.displayName;const On=s.cva("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"}}),Dn=B.forwardRef(({className:t,variant:a,...s},r)=>e.jsx("div",{ref:r,role:"alert",className:nt(On({variant:a}),t),...s}));Dn.displayName="Alert";const Fn=B.forwardRef(({className:t,...a},s)=>e.jsx("h5",{ref:s,className:nt("mb-1 font-medium leading-none tracking-tight",t),...a}));Fn.displayName="AlertTitle";const zn=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("text-sm [&_p]:leading-relaxed",t),...a}));zn.displayName="AlertDescription";const $n=t.createContext(void 0);function Un({children:a,actions:s}){const[r,n]=t.useState({}),[i,o]=t.useState(s);return t.useEffect(()=>{o(s)},[s]),e.jsx($n.Provider,{value:{metadata:r,setMetadata:n,clearMetadata:()=>n({}),headerActions:i,setHeaderActions:o},children:a})}function Vn(){const e=t.useContext($n);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}const qn=se.Root,Bn=B.forwardRef(({className:t,...a},s)=>e.jsx(se.Item,{ref:s,className:nt("border-b",t),...a}));Bn.displayName="AccordionItem";const Wn=B.forwardRef(({className:t,children:a,...s},r)=>e.jsx(se.Header,{className:"flex",children:e.jsxs(se.Trigger,{ref:r,className:nt("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",t),...s,children:[a,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Wn.displayName=se.Trigger.displayName;const Hn=B.forwardRef(({className:t,children:a,...s},r)=>e.jsx(se.Content,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...s,children:e.jsx("div",{className:nt("pb-4 pt-0",t),children:a})}));Hn.displayName=se.Content.displayName;const Kn=re.Root,Gn=B.forwardRef(({className:t,...a},s)=>e.jsx(ne.Root,{ref:s,className:nt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...a}));Gn.displayName=ne.Root.displayName;const Qn=B.forwardRef(({className:t,...a},s)=>e.jsx(ne.Image,{ref:s,className:nt("aspect-square h-full w-full",t),...a}));Qn.displayName=ne.Image.displayName;const Xn=B.forwardRef(({className:t,...a},s)=>e.jsx(ne.Fallback,{ref:s,className:nt("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...a}));Xn.displayName=ne.Fallback.displayName;const Jn=B.forwardRef(({...t},a)=>e.jsx("nav",{ref:a,"aria-label":"breadcrumb",...t}));Jn.displayName="Breadcrumb";const Yn=B.forwardRef(({className:t,...a},s)=>e.jsx("ol",{ref:s,className:nt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",t),...a}));Yn.displayName="BreadcrumbList";const Zn=B.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:nt("inline-flex items-center gap-1.5",t),...a}));Zn.displayName="BreadcrumbItem";const ei=B.forwardRef(({asChild:t,className:a,...s},r)=>{const n=t?B.Fragment:"a";return e.jsx(n,{ref:r,className:nt("transition-colors hover:text-foreground",a),...s})});ei.displayName="BreadcrumbLink";const ti=B.forwardRef(({className:t,...a},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:nt("font-normal text-foreground",t),...a}));ti.displayName="BreadcrumbPage";const ai=({children:t,className:a,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:nt("[&>svg]:size-3.5",a),...s,children:t??e.jsx(l.ChevronRight,{})});ai.displayName="BreadcrumbSeparator";const si=({className:t,...a})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:nt("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More"})]});si.displayName="BreadcrumbEllipsis";const ri=s.cva("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"}}),ni=B.forwardRef(({className:t,orientation:a,...s},r)=>e.jsx("div",{ref:r,className:nt(ri({orientation:a}),t),...s}));function ii(e){return(t={})=>{const a=t.width?String(t.width):e.defaultWidth;return e.formats[a]||e.formats[e.defaultWidth]}}function oi(e){return(t,a)=>{let s;if("formatting"===(a?.context?String(a.context):"standalone")&&e.formattingValues){const t=e.defaultFormattingWidth||e.defaultWidth,r=a?.width?String(a.width):t;s=e.formattingValues[r]||e.formattingValues[t]}else{const t=e.defaultWidth,r=a?.width?String(a.width):e.defaultWidth;s=e.values[r]||e.values[t]}return s[e.argumentCallback?e.argumentCallback(t):t]}}function li(e){return(t,a={})=>{const s=a.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=t.match(r);if(!n)return null;const i=n[0],o=s&&e.parsePatterns[s]||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 di(e){return(t,a={})=>{const s=t.match(e.matchPattern);if(!s)return null;const r=s[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(r.length)}}}ni.displayName="ButtonGroup";const ci={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"}},ui={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},mi={ordinalNumber:(e,t)=>{const a=Number(e),s=a%100;if(s>20||s<10)switch(s%10){case 1:return a+"st";case 2:return a+"nd";case 3:return a+"rd"}return a+"th"},era:oi({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:oi({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:oi({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:oi({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:oi({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"})},pi={ordinalNumber:di({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:li({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:li({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:li({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:li({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:li({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"})},hi={code:"en-US",formatDistance:(e,t,a)=>{let s;const r=ci[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"in "+s:s+" ago":s},formatLong:{date:ii({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:ii({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:ii({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},formatRelative:(e,t,a,s)=>ui[e],localize:mi,match:pi,options:{weekStartsOn:0,firstWeekContainsDate:1}},fi={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"}},xi={date:ii({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:ii({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:ii({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},gi={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"},bi={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"},vi={ordinalNumber:(e,t)=>Number(e)+"º",era:oi({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:oi({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:oi({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:oi({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:oi({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"})},yi={ordinalNumber:di({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:li({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:li({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:li({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:li({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:li({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"})},Ni={code:"es",formatDistance:(e,t,a)=>{let s;const r=fi[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",t.toString()),a?.addSuffix?a.comparison&&a.comparison>0?"en "+s:"hace "+s:s},formatLong:xi,formatRelative:(e,t,a,s)=>1!==t.getHours()?bi[e]:gi[e],localize:vi,match:yi,options:{weekStartsOn:1,firstWeekContainsDate:1}},ji={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"}},wi={date:ii({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:ii({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:ii({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},ki={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"},Ci={ordinalNumber:(e,t)=>{const a=Number(e);return"week"===t?.unit?a+"ª":a+"º"},era:oi({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:oi({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:oi({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:oi({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:oi({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"})},Si={ordinalNumber:di({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:li({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:li({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:li({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:li({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:li({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"})},Pi={code:"pt-BR",formatDistance:(e,t,a)=>{let s;const r=ji[e];return s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",String(t)),a?.addSuffix?a.comparison&&a.comparison>0?"em "+s:"há "+s:s},formatLong:wi,formatRelative:(e,t,a,s)=>{const r=ki[e];return"function"==typeof r?r(t):r},localize:Ci,match:Si,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Ei({className:t,classNames:a,showOutsideDays:s=!0,...r}){return e.jsx(E.DayPicker,{showOutsideDays:s,className:nt("p-3 pointer-events-auto",t),locale:Pi,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:nt(ot({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:nt(ot({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.jsx(l.ChevronLeft,{className:"h-4 w-4"}),IconRight:({...t})=>e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}Ei.displayName="Calendar";const Ti=ie.Root,Ai=ie.CollapsibleTrigger,_i=ie.CollapsibleContent;const Ii={Root:function({children:t,className:a}){return e.jsx("div",{className:nt("space-y-4",a),children:t})},Item:function({children:t,onClick:a,className:s}){return e.jsx(pt,{className:nt("transition-colors",a&&"cursor-pointer hover:bg-muted/50",s),onClick:a,children:e.jsx(gt,{className:"p-4",children:t})})},Field:function({label:t,value:a,className:s}){return e.jsxs("div",{className:nt("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[t,":"]}),e.jsx("span",{className:"text-foreground",children:a})]})}};const Ri=({shouldScaleBackground:t=!0,...a})=>e.jsx(A.Drawer.Root,{shouldScaleBackground:t,...a});Ri.displayName="Drawer";const Li=A.Drawer.Trigger,Mi=A.Drawer.Portal,Oi=A.Drawer.Close,Di=B.forwardRef(({className:t,...a},s)=>e.jsx(A.Drawer.Overlay,{ref:s,className:nt("fixed inset-0 z-50 bg-black/80",t),...a}));Di.displayName=A.Drawer.Overlay.displayName;const Fi=B.forwardRef(({className:t,children:a,...s},r)=>e.jsxs(Mi,{children:[e.jsx(Di,{}),e.jsxs(A.Drawer.Content,{ref:r,className:nt("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",t),...s,children:[e.jsx("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),a]})]}));Fi.displayName="DrawerContent";const zi=({className:t,...a})=>e.jsx("div",{className:nt("grid gap-1.5 p-4 text-center sm:text-left",t),...a});zi.displayName="DrawerHeader";const $i=({className:t,...a})=>e.jsx("div",{className:nt("mt-auto flex flex-col gap-2 p-4",t),...a});$i.displayName="DrawerFooter";const Ui=B.forwardRef(({className:t,...a},s)=>e.jsx(A.Drawer.Title,{ref:s,className:nt("text-lg font-semibold leading-none tracking-tight",t),...a}));Ui.displayName=A.Drawer.Title.displayName;const Vi=B.forwardRef(({className:t,...a},s)=>e.jsx(A.Drawer.Description,{ref:s,className:nt("text-sm text-muted-foreground",t),...a}));Vi.displayName=A.Drawer.Description.displayName;const qi={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))]"},Bi={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Wi({children:t,cols:a="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:nt("grid",qi[a],Bi[s],r),children:t})}const Hi=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-slot":"input-group",className:nt("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}));Hi.displayName="InputGroup";const Ki=s.cva("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"}}),Gi=B.forwardRef(({className:t,align:a,...s},r)=>e.jsx("div",{ref:r,"data-slot":"input-group-addon",className:nt(Ki({align:a}),t),...s}));Gi.displayName="InputGroupAddon";const Qi=s.cva("",{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"}}),Xi=B.forwardRef(({className:t,size:a,variant:s="ghost",...r},n)=>e.jsx(lt,{ref:n,"data-slot":"input-group-button",variant:s,className:nt(Qi({size:a}),"rounded-none first:rounded-l-md last:rounded-r-md",t),...r}));Xi.displayName="InputGroupButton";const Ji=B.forwardRef(({className:t,...a},s)=>e.jsx(ct,{ref:s,"data-slot":"input-group-control",className:nt("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));Ji.displayName="InputGroupInput";const Yi=B.forwardRef(({className:t,...a},s)=>e.jsx(Qt,{ref:s,"data-slot":"input-group-control",className:nt("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",t),...a}));Yi.displayName="InputGroupTextarea";const Zi=B.forwardRef(({className:t,keys:a,children:s,...r},n)=>a&&a.length>0?e.jsxs("span",{className:nt("inline-flex items-center gap-1",t),children:[a.map((t,a)=>e.jsx("kbd",{className:nt("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.jsx("kbd",{ref:n,className:nt("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"),...r,children:s})]}):e.jsx("kbd",{ref:n,className:nt("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",t),...r,children:s}));Zi.displayName="Kbd";const eo=B.forwardRef(({className:t,children:a,...s},r)=>e.jsx("select",{ref:r,className:nt("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),...s,children:a}));eo.displayName="NativeSelect";const to=B.forwardRef(({className:t,...a},s)=>e.jsx("h1",{ref:s,className:nt("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",t),...a}));to.displayName="H1";const ao=B.forwardRef(({className:t,...a},s)=>e.jsx("h2",{ref:s,className:nt("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",t),...a}));ao.displayName="H2";const so=B.forwardRef(({className:t,...a},s)=>e.jsx("h3",{ref:s,className:nt("scroll-m-20 text-2xl font-semibold tracking-tight",t),...a}));so.displayName="H3";const ro=B.forwardRef(({className:t,...a},s)=>e.jsx("h4",{ref:s,className:nt("scroll-m-20 text-xl font-semibold tracking-tight",t),...a}));ro.displayName="H4";const no=B.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:nt("leading-7 [&:not(:first-child)]:mt-6",t),...a}));no.displayName="P";const io=B.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:nt("text-xl text-muted-foreground",t),...a}));io.displayName="Lead";const oo=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,className:nt("text-lg font-semibold",t),...a}));oo.displayName="Large";const lo=B.forwardRef(({className:t,...a},s)=>e.jsx("small",{ref:s,className:nt("text-sm font-medium leading-none",t),...a}));lo.displayName="Small";const co=B.forwardRef(({className:t,...a},s)=>e.jsx("p",{ref:s,className:nt("text-sm text-muted-foreground",t),...a}));co.displayName="Muted";const uo=B.forwardRef(({className:t,...a},s)=>e.jsx("code",{ref:s,className:nt("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",t),...a}));uo.displayName="InlineCode";const mo=B.forwardRef(({className:t,...a},s)=>e.jsx("blockquote",{ref:s,className:nt("mt-6 border-l-2 pl-6 italic",t),...a}));mo.displayName="Blockquote";const po=B.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:nt("my-6 ml-6 list-disc [&>li]:mt-2",t),...a}));po.displayName="List";const ho=({className:t,...a})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:nt("mx-auto flex w-full justify-center",t),...a});ho.displayName="Pagination";const fo=B.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,className:nt("flex flex-row items-center gap-1",t),...a}));fo.displayName="PaginationContent";const xo=B.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,className:nt("",t),...a}));xo.displayName="PaginationItem";const go=({className:t,isActive:a,size:s="icon",...r})=>e.jsx("a",{"aria-current":a?"page":void 0,className:nt(ot({variant:a?"outline":"ghost",size:s}),t),...r});go.displayName="PaginationLink";const bo=({className:t,...a})=>e.jsxs(go,{"aria-label":"Go to previous page",size:"default",className:nt("gap-1 pl-2.5",t),...a,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});bo.displayName="PaginationPrevious";const vo=({className:t,...a})=>e.jsxs(go,{"aria-label":"Go to next page",size:"default",className:nt("gap-1 pr-2.5",t),...a,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});vo.displayName="PaginationNext";const yo=({className:t,...a})=>e.jsxs("span",{"aria-hidden":!0,className:nt("flex h-9 w-9 items-center justify-center",t),...a,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});yo.displayName="PaginationEllipsis";const No=B.forwardRef(({className:t,...a},s)=>e.jsx(oe.Root,{className:nt("grid gap-2",t),...a,ref:s}));No.displayName=oe.Root.displayName;const jo=B.forwardRef(({className:t,...a},s)=>e.jsx(oe.Item,{ref:s,className:nt("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.jsx(oe.Indicator,{className:"flex items-center justify-center",children:e.jsx(l.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));jo.displayName=oe.Item.displayName;const wo=s.cva("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"}}),ko=B.forwardRef(({className:t,variant:a,size:s,onClear:r,showClearButton:n=!0,value:i,...o},d)=>{const c=null!=i&&""!==i;return e.jsxs("div",{className:nt(wo({variant:a,size:s,className:t})),children:[e.jsx(l.Search,{className:"ml-3 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("input",{type:"text",className:nt("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:i,...o}),n&&c&&r&&e.jsx("button",{type:"button",onClick:r,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.jsx(l.X,{className:"h-4 w-4"})})]})});ko.displayName="Searchbar";const Co=B.forwardRef(({className:t,orientation:a="horizontal",decorative:s=!0,...r},n)=>e.jsx(le.Root,{ref:n,decorative:s,orientation:a,className:nt("shrink-0 bg-border","horizontal"===a?"h-[1px] w-full":"h-full w-[1px]",t),...r}));Co.displayName=le.Root.displayName;const So=H.Root,Po=H.Trigger,Eo=H.Close,To=H.Portal,Ao=B.forwardRef(({className:t,...a},s)=>e.jsx(H.Overlay,{className:nt("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:s}));Ao.displayName=H.Overlay.displayName;const _o=s.cva("fixed z-50 gap-4 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 data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t 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"}}),Io=B.forwardRef(({side:t="right",className:a,children:s,...r},n)=>e.jsxs(To,{children:[e.jsx(Ao,{}),e.jsxs(H.Content,{ref:n,className:nt(_o({side:t}),a),...r,children:[s,e.jsxs(H.Close,{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 data-[state=open]:bg-secondary",children:[e.jsx(l.X,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Io.displayName=H.Content.displayName;const Ro=({className:t,...a})=>e.jsx("div",{className:nt("flex flex-col space-y-2 text-center sm:text-left",t),...a});Ro.displayName="SheetHeader";const Lo=({className:t,...a})=>e.jsx("div",{className:nt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a});Lo.displayName="SheetFooter";const Mo=B.forwardRef(({className:t,...a},s)=>e.jsx(H.Title,{ref:s,className:nt("text-lg font-semibold text-foreground",t),...a}));Mo.displayName=H.Title.displayName;const Oo=B.forwardRef(({className:t,...a},s)=>e.jsx(H.Description,{ref:s,className:nt("text-sm text-muted-foreground",t),...a}));Oo.displayName=H.Description.displayName;const Do=de.Provider,Fo=de.Root,zo=de.Trigger,$o=B.forwardRef(({className:t,sideOffset:a=4,...s},r)=>e.jsx(de.Content,{ref:r,sideOffset:a,className:nt("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),...s}));$o.displayName=de.Content.displayName;const Uo="sidebar:state",Vo=B.createContext(null);function qo(){const e=B.useContext(Vo);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Bo=B.forwardRef(({defaultOpen:t=!0,open:a,onOpenChange:s,className:r,style:n,children:i,...o},l)=>{const[d,c]=B.useState(!1);B.useEffect(()=>{const e=()=>c(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,m]=B.useState(!1),[p,h]=B.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(Uo);return null!==e?"true"===e:t}return t}),f=a??p,x=B.useCallback(e=>{const t="function"==typeof e?e(f):e;s?s(t):h(t),"undefined"!=typeof window&&localStorage.setItem(Uo,String(t))},[s,f]),g=B.useCallback(()=>d?m(e=>!e):x(e=>!e),[d,x,m]);B.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),g())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[g]);const b=f?"expanded":"collapsed",v=B.useMemo(()=>({state:b,open:f,setOpen:x,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:g}),[b,f,x,d,u,m,g]);return e.jsx(Vo.Provider,{value:v,children:e.jsx(Do,{delayDuration:0,children:e.jsx("div",{className:nt("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",r),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4.5rem",...n},ref:l,...o,children:i})})})});Bo.displayName="SidebarProvider";const Wo=B.forwardRef(({side:t="left",variant:a="sidebar",collapsible:s="offcanvas",className:r,children:n,...i},o)=>{const{isMobile:l,state:d,openMobile:c,setOpenMobile:u}=qo();return"none"===s?e.jsx("div",{className:nt("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:o,...i,children:n}):l?e.jsx(So,{open:c,onOpenChange:u,...i,children:e.jsxs(Io,{"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:t,children:[e.jsx(Mo,{className:"sr-only",children:"Menu de Navegação"}),e.jsx("div",{className:"flex h-full w-full flex-col",children:n})]})}):e.jsxs("div",{ref:o,className:"group peer hidden md:block text-sidebar-foreground","data-state":d,"data-collapsible":"collapsed"===d?s:"","data-variant":a,"data-side":t,children:[e.jsx("div",{className:nt("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"===a||"inset"===a?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:nt("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===t?"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"===a||"inset"===a?"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",r),...i,children:e.jsx("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:n})})]})});Wo.displayName="Sidebar";const Ho=B.forwardRef(({className:t,onClick:a,...s},r)=>{const{toggleSidebar:n}=qo();return e.jsxs(lt,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:nt("h-7 w-7",t),onClick:e=>{a?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Ho.displayName="SidebarTrigger";const Ko=B.forwardRef(({className:t,...a},s)=>{const{toggleSidebar:r}=qo();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:nt("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})});Ko.displayName="SidebarRail";const Go=B.forwardRef(({className:t,...a},s)=>e.jsx("main",{ref:s,className:nt("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}));Go.displayName="SidebarInset";const Qo=B.forwardRef(({className:t,...a},s)=>e.jsx(ct,{ref:s,"data-sidebar":"input",className:nt("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",t),...a}));Qo.displayName="SidebarInput";const Xo=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:nt("flex flex-col gap-2 p-2",t),...a}));Xo.displayName="SidebarHeader";const Jo=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:nt("flex flex-col gap-2 p-2",t),...a}));Jo.displayName="SidebarFooter";const Yo=B.forwardRef(({className:t,...a},s)=>e.jsx(Co,{ref:s,"data-sidebar":"separator",className:nt("mx-2 w-auto bg-sidebar-border",t),...a}));Yo.displayName="SidebarSeparator";const Zo=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:nt("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",t),...a}));Zo.displayName="SidebarContent";const el=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:nt("relative flex w-full min-w-0 flex-col p-2",t),...a}));el.displayName="SidebarGroup";const tl=B.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const i=s?a.Slot:"div";return e.jsx(i,{ref:n,"data-sidebar":"group-label",className:nt("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})});tl.displayName="SidebarGroupLabel";const al=B.forwardRef(({className:t,asChild:s=!1,...r},n)=>{const i=s?a.Slot:"button";return e.jsx(i,{ref:n,"data-sidebar":"group-action",className:nt("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})});al.displayName="SidebarGroupAction";const sl=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:nt("w-full text-sm",t),...a}));sl.displayName="SidebarGroupContent";const rl=B.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:nt("flex w-full min-w-0 flex-col gap-1",t),...a}));rl.displayName="SidebarMenu";const nl=B.forwardRef(({className:t,...a},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:nt("group/menu-item relative",t),...a}));nl.displayName="SidebarMenuItem";const il=s.cva("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"}}),ol=B.forwardRef(({asChild:t=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:i,className:o,...l},d)=>{const c=t?a.Slot:"button",{isMobile:u,state:m}=qo(),p=e.jsx(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:nt(il({variant:r,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),e.jsxs(Fo,{children:[e.jsx(zo,{asChild:!0,children:p}),e.jsx($o,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):p});ol.displayName="SidebarMenuButton";const ll=B.forwardRef(({className:t,asChild:s=!1,showOnHover:r=!1,...n},i)=>{const o=s?a.Slot:"button";return e.jsx(o,{ref:i,"data-sidebar":"menu-action",className:nt("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})});ll.displayName="SidebarMenuAction";const dl=B.forwardRef(({className:t,...a},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:nt("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}));dl.displayName="SidebarMenuBadge";const cl=B.forwardRef(({className:t,showIcon:a=!1,...s},r)=>{const n=B.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:nt("rounded-md h-8 flex gap-2 px-2 items-center",t),...s,children:[a&&e.jsx("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":n}})]})});cl.displayName="SidebarMenuSkeleton";const ul=B.forwardRef(({className:t,...a},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:nt("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}));ul.displayName="SidebarMenuSub";const ml=B.forwardRef(({...t},a)=>e.jsx("li",{ref:a,...t}));ml.displayName="SidebarMenuSubItem";const pl=B.forwardRef(({asChild:t=!1,size:s="md",isActive:r,className:n,...i},o)=>{const l=t?a.Slot:"a";return e.jsx(l,{ref:o,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:nt("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"===s&&"text-xs","md"===s&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i})});pl.displayName="SidebarMenuSubButton";const hl=B.forwardRef(({className:t,...a},s)=>e.jsxs(ce.Root,{ref:s,className:nt("relative flex w-full touch-none select-none items-center",t),...a,children:[e.jsx(ce.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(ce.Range,{className:"absolute h-full bg-primary"})}),e.jsx(ce.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"})]}));hl.displayName=ce.Root.displayName;const fl=ue.Root,xl=B.forwardRef(({className:t,...a},s)=>e.jsx(ue.List,{ref:s,className:nt("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",t),...a}));xl.displayName=ue.List.displayName;const gl=B.forwardRef(({className:t,...a},s)=>e.jsx(ue.Trigger,{ref:s,className:nt("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}));gl.displayName=ue.Trigger.displayName;const bl=B.forwardRef(({className:t,...a},s)=>e.jsx(ue.Content,{ref:s,className:nt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...a}));bl.displayName=ue.Content.displayName;const vl=s.cva("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"}}),yl=B.forwardRef(({className:t,variant:a,size:s,...r},n)=>e.jsx(me.Root,{ref:n,className:nt(vl({variant:a,size:s,className:t})),...r}));yl.displayName=me.Root.displayName;const Nl=B.createContext({size:"default",variant:"default"}),jl=B.forwardRef(({className:t,variant:a,size:s,children:r,...n},i)=>e.jsx(pe.Root,{ref:i,className:nt("flex items-center justify-center gap-1",t),...n,children:e.jsx(Nl.Provider,{value:{variant:a,size:s},children:r})}));jl.displayName=pe.Root.displayName;const wl=B.forwardRef(({className:t,children:a,variant:s,size:r,...n},i)=>{const o=B.useContext(Nl);return e.jsx(pe.Item,{ref:i,className:nt(vl({variant:o.variant||s,size:o.size||r}),t),...n,children:a})});function kl({onEdit:t,onDelete:a,onToggleStatus:s,isActive:r=!0,canEdit:n=!0,canDelete:i=!0,customActions:o=[],renderAs:d="dropdown",variant:c="default"}){const{t:u}=Ya(),m=[];return t&&n&&m.push({icon:l.Edit,label:u("edit"),onClick:t,variant:"default"}),s&&m.push({icon:r?l.PowerOff:l.Power,label:u(r?"deactivate":"activate"),onClick:s,variant:"default"}),o.forEach(e=>{!1!==e.show&&m.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),a&&i&&m.push({icon:l.Trash2,label:u("remove"),onClick:a,variant:"destructive"}),0===m.length?null:"dropdown"===d?e.jsxs(Er,{children:[e.jsx(Tr,{asChild:!0,children:e.jsx(lt,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:e.jsx(l.EllipsisVertical,{size:"compact"===c?14:16})})}),e.jsx(Or,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:m.map((t,a)=>e.jsxs(Dr,{onClick:t.onClick,className:"destructive"===t.variant?"text-destructive":"",children:[t.icon&&e.jsx(t.icon,{className:"mr-2 h-4 w-4"}),t.label]},a))})]}):e.jsx("div",{className:"flex items-center gap-1",children:m.map((t,a)=>e.jsxs(lt,{variant:"destructive"===t.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:t.onClick,className:"compact"===c?"h-7 px-2":"",children:[t.icon&&e.jsx(t.icon,{size:"compact"===c?14:16}),"compact"!==c&&e.jsx("span",{className:"ml-1",children:t.label})]},a))})}function Cl(e){const t=b.useNavigate();return{onNew:()=>{const a=e.newPath||`${e.basePath}/new`;t(a)},onEdit:a=>{const s=e.editPath?e.editPath.replace(":id",a.id):`${e.basePath}/${a.id}/edit`;t(s)}}}wl.displayName=pe.Item.displayName;const Sl=new class{async getUserPreferences(e,t){if(!us.areAllTokensValid())return null;const a=Ns();try{const{data:s,error:r}=await a.schema("common").from("user_preferences").select("*").eq("id_user",e).eq("alias",t).maybeSingle();if(r)return"PGRST116"===r.code?this.createDefaultPreferences(e,t):("42501"===r.code||"PGRST301"===r.code||r.message?.includes("permission denied"),null);if(!s)return this.createDefaultPreferences(e,t);const n=s;return{locale:n.locale,timezone:n.timezone,datetimeFormat:n.datetime_format}}catch(s){return null}}async createDefaultPreferences(e,t){const a=Ns(),s={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(s).select().single();if(t)throw t;const r=e;return{locale:r.locale,timezone:r.timezone,datetimeFormat:r.datetime_format}}catch(r){throw r}}async updatePreferences(e,t,a){const s=Ns();try{const{error:r}=await s.schema("common").from("user_preferences").update(a).eq("id_user",e).eq("alias",t);if(r)throw r}catch(r){throw r}}};var Pl=Object.defineProperty,El=(e,t,a)=>((e,t,a)=>t in e?Pl(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const Tl=new class{constructor(){El(this,"cache",{}),El(this,"cacheTimestamps",new Map),El(this,"CACHE_TTL",3e5),El(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{if(!us.areAllTokensValid())return{};const t=Ns(),{data:a,error:s}=await t.schema("common").from("translations").select("key, pt, en, es").eq("is_removed",!1);if(s)return"42501"===s.code||"PGRST301"===s.code||s.message?.includes("permission denied")||s.message?.includes("No suitable key"),{};const r={};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&&(r[t.key]=a)}),this.cache[e]=r,this.cacheTimestamps.set(e,Date.now()),r}catch(t){return{}}}async upsertTranslation(e,t,a,s){const r=Ns(),{error:n}=await r.schema("common").from("translations").upsert({key:e,pt:t,en:a,es:s},{onConflict:"key"});if(n)throw n;this.clearCache()}async bulkUpsertTranslations(e){const t=Ns(),{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 Al=Object.defineProperty,_l=(e,t,a)=>((e,t,a)=>t in e?Al(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,"symbol"!=typeof t?t+"":t,a);const Il="true"===(void 0).VITE_I18N_DEBUG_MODE;st.use(new class{constructor(e=!1){_l(this,"type","backend"),_l(this,"isDebugMode"),_l(this,"cache",new Map),_l(this,"loadingPromises",new Map),this.isDebugMode=e}read(e,t,a){if(!us.areAllTokensValid())return void a(null,{});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 s=Tl.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,s),s.then(()=>{a(null,this.cache.get(e)||{})})}create(e,t,a,s){}}(Il)).use($a).init({fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"translations",ns:["translations"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:(e,t)=>Il?`[${e} ❌]`:`[⚠️ ${e}]`});const Rl=t.createContext(void 0),Ll=()=>{const e=t.useContext(Rl);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},Ml=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],Ol=[{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"}],Dl=[{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"}],Fl=()=>{const{locale:t,datetimeFormat:a,timezone:s,setLocale:r,setDatetimeFormat:n,setTimezone:i}=Ll(),{t:o}=Ya();return e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(l.Globe,{className:"h-4 w-4"}),o("language")]}),e.jsxs(Ft,{value:t,onValueChange:r,children:[e.jsx(Ut,{children:e.jsx($t,{})}),e.jsx(Bt,{children:Ml.map(t=>e.jsxs(Ht,{value:t.value,children:[t.flag," ",t.label]},t.value))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(l.Clock,{className:"h-4 w-4"}),o("timezone")||"Fuso Horário"]}),e.jsxs(Ft,{value:s,onValueChange:i,children:[e.jsx(Ut,{children:e.jsx($t,{})}),e.jsx(Bt,{children:Dl.map(t=>e.jsx(Ht,{value:t.value,children:t.label},t.value))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(l.Calendar,{className:"h-4 w-4"}),o("dateTimeFormat")||"Formato de Data/Hora"]}),e.jsxs(Ft,{value:a,onValueChange:n,children:[e.jsx(Ut,{children:e.jsx($t,{})}),e.jsx(Bt,{children:Ol.map(t=>e.jsx(Ht,{value:t.value,children:e.jsxs("div",{className:"flex flex-col items-start",children:[e.jsx("span",{children:t.label}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.description," • ",t.example]})]})},t.value))})]})]})]})},zl=t.memo(({variant:a="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:i,companies:o,alias:d,isAuthenticated:c,logout:u,switchUnit:m}=ar(),[p,h]=t.useState(!1),f=o?.[0]||null,x=d?o?.find(e=>e.alias===d):f,g=o||[],b=r||x||f||f,v=t.useCallback(e=>{n?n(e):m(e)},[n,m]),y=t.useMemo(()=>{if(!g?.length)return[];const e=new Map;g.forEach(t=>{e.set(t.alias,t)});const t=Array.from(e.values()),a=t.find(e=>e.alias===b?.alias),s=t.filter(e=>e.alias!==b?.alias);return s.sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"})),a?[a,...s]:s},[g,b?.alias]);if(!c||!i)return null;const N=()=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx("div",{className:"flex-shrink-0",children:e.jsx("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-5 w-5 text-primary-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",b?.name||"N/A"]})]})]}),b&&e.jsx("div",{className:"mt-3",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:b.name})]})}),y.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",y.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[y.slice(0,3).map(t=>e.jsx(Jt,{variant:t.alias===b?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>v(t),children:t.name},t.alias)),y.length>3&&e.jsxs(Jt,{variant:"outline",className:"text-xs",children:["+",y.length-3]})]})]})]});return"dropdown"===a?e.jsxs(Er,{children:[e.jsx(Tr,{asChild:!0,children:e.jsx(lt,{variant:"ghost",className:`h-auto p-2 ${s}`,children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsxs("div",{className:"hidden md:block text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:i.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b?.name||"N/A"})]}),e.jsx("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:e.jsx(l.User,{className:"h-4 w-4 text-primary-foreground"})}),e.jsx(l.ChevronDown,{className:"h-4 w-4"})]})})}),e.jsxs(Or,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs(Ir,{children:[e.jsxs(Lr,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(Mr,{children:y.map(t=>e.jsxs(Dr,{onClick:()=>v(t),className:t.alias===b?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),t.name,t.alias===b?.alias&&e.jsx(Jt,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},t.alias))})]}),e.jsx(Ur,{}),e.jsxs(Dr,{onClick:()=>h(!0),children:[e.jsx(l.Settings,{className:"mr-2 h-4 w-4"}),"Preferências"]}),e.jsxs(Dr,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]}),e.jsx(vt,{open:p,onOpenChange:h,children:e.jsxs(kt,{children:[e.jsx(Ct,{children:e.jsx(Pt,{children:"Preferências de Internacionalização"})}),e.jsx(Fl,{})]})})]}):e.jsxs(pt,{className:s,children:[e.jsx(ht,{children:e.jsx(ft,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(gt,{className:"space-y-4",children:[e.jsx(N,{}),e.jsx(Co,{}),e.jsxs(lt,{variant:"outline",onClick:()=>h(!0),size:"sm",className:"w-full",children:[e.jsx(l.Settings,{className:"mr-2 h-4 w-4"}),"Preferências"]}),e.jsxs(lt,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]}),e.jsx(vt,{open:p,onOpenChange:h,children:e.jsxs(kt,{children:[e.jsx(Ct,{children:e.jsx(Pt,{children:"Preferências de Internacionalização"})}),e.jsx(Fl,{})]})})]})]})}),$l=t.createContext({});function Ul({children:a,config:s}){const r=t.useMemo(()=>({navigation:s?.navigation,appName:s?.appName}),[s?.navigation,s?.appName]);return e.jsx($l.Provider,{value:r,children:a})}function Vl(){return t.useContext($l)}function ql(){const e=b.useLocation(),{navigation:t}=Vl(),{t:a}=Ya();if(!t)return a("page");const s=t.find(t=>t.path===e.pathname);if(s)return s.label;const r=t.find(t=>e.pathname.startsWith(t.path+"/"));return r?.label||a("page")}function Bl(e,a){const[s,r]=t.useState(e),n=t.useRef(),i=t.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return t.useEffect(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[s,i]}const Wl=t.memo(function({actions:a}){const s=b.useLocation(),r=ql(),{navigation:n,appName:i}=Vl(),{metadata:o,headerActions:d}=Vn(),{t:c}=Ya(),{companies:u,alias:m,isSearchVisible:p,clearSearch:h,refreshData:f,switchUnit:x}=ar(),g=m?u?.find(e=>e.alias===m)||u?.[0]||null:u?.[0]||null,[v,y]=b.useSearchParams(),[N,j]=t.useState(()=>v.get("search")||""),[w,k]=Bl(N,Ls.debounceDelay);t.useEffect(()=>{if(!p)return;const e=new URLSearchParams(v);w?(e.set("search",w),e.set("page","1")):e.delete("search"),y(e)},[w,y,p]);const C=n?.find(e=>e.path===s.pathname)||n?.find(e=>s.pathname.startsWith(e.path+"/")),S=o.title||r,P=o.subtitle||C?.complementaryText||c("item_details");return e.jsx("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:S}),e.jsx(Jt,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:i||c("module")})]}),P&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:P})]}),p&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),e.jsx(ct,{placeholder:c("search"),value:N,onChange:e=>(e=>{j(e)})(e.target.value),className:"w-full pl-10 pr-8"}),N&&e.jsx(lt,{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:()=>{k(),j("");const e=new URLSearchParams(v);e.delete("search"),e.delete("page"),y(e)},title:c("clear_search"),children:e.jsx(l.X,{size:14})})]}),e.jsx(lt,{variant:"outline",size:"sm",onClick:f,className:"flex-shrink-0 h-10 w-10 p-0",title:c("refresh_data"),children:e.jsx(l.RefreshCw,{size:14})})]}),e.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(d||a)&&e.jsx("div",{className:"flex items-center gap-2",children:d||a}),(void 0).VITE_WIKI_URL&&e.jsx(lt,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>rt((void 0).VITE_WIKI_URL,e),title:c("open_wiki"),children:"Wiki"}),e.jsx("div",{className:"text-sm",children:e.jsx(zl,{variant:"dropdown",selectedUnit:g,onUnitChange:x})})]})]})})}),Hl=({key:e,enabled:t,checkFn:a,staleTime:s=3e5,gcTime:r=6e5})=>g.useQuery({queryKey:["permission",e],queryFn:a,enabled:t,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1}),Kl=(e={})=>{const{enabled:t=!0}=e,{alias:a}=ar();return g.useQuery({queryKey:["active-modules",a],queryFn:async()=>{if(!a)return[];const e=Ns(),{data:t,error:s}=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(s){if(!Ss.handleError(s))throw s;return[]}return t||[]},enabled:t&&!!a})},Gl="forlogic-sidebar-pinned",Ql=()=>{try{const e=localStorage.getItem(Gl);return!!e&&JSON.parse(e)}catch{return!1}},Xl=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]},Jl=`https://${(void 0).VITE_SUPABASE_PROJECT_ID_STORAGE??(void 0).VITE_SUPABASE_PROJECT_ID}.supabase.co/storage/v1/object/public/library-assets`,Yl={logo:`${Jl}/${Fs.isQualiex?"logo-qualiex.svg":"logo.svg"}`,smallLogo:`${Jl}/${Fs.isQualiex?"small-forlogic.svg":"small.svg"}`},Zl=Yl.logo,ed=Yl.smallLogo;function td({appName:t,isPinned:a,onPinToggle:s,open:r,dropdownOpen:n,onDropdownChange:i}){const{t:o}=Ya(),{data:d,isLoading:c,error:u}=Kl({enabled:n}),m=e=>{((e,t)=>{const a=e?.find(e=>e.url===t);a?.url&&window.open(a.url,"_blank")})(d,e)};return e.jsxs(Xo,{className:"p-0 gap-0",children:[e.jsx("div",{className:"flex items-center justify-between h-[34px]",children:r?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center pl-[12px]",children:e.jsx("img",{src:Yl.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),e.jsx("button",{onClick:s,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(a?"bg-primary/20 text-primary":"hover:bg-muted text-muted-foreground"),children:e.jsx(l.PanelLeft,{className:"h-4 w-4"})})]}):e.jsx("div",{className:"flex items-center justify-center w-full h-[34px]",children:e.jsx("img",{src:Yl.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e.jsx("div",{className:"mt-2 pt-0",children:e.jsxs(Er,{onOpenChange:i,children:[e.jsx(Tr,{asChild:!0,children:r?e.jsxs("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:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("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.jsx("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:t})]}),e.jsx(l.ChevronDown,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):e.jsx("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.jsx(l.ChevronDown,{className:"h-6 w-6 text-muted-foreground"})})}),e.jsx(Or,{className:r?"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:r?"start":"center",children:c?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[e.jsx(l.Loader2,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:o("loading")})]}):u?e.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[e.jsx(l.AlertCircle,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:o("error")})]}):d&&0!==d.length?e.jsx("div",{className:"space-y-2",children:d.map((t,a)=>e.jsx("div",{onClick:()=>m(t.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${Xl(a)} transition-colors duration-200\n `,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-foreground text-sm",children:t.name}),t.url&&e.jsx(l.ExternalLink,{className:"h-4 w-4 text-muted-foreground"})]})},t.id))}):e.jsx("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:o("no_results")})})]})})]})}function ad({direction:e="right",minWidth:a=224,maxWidth:s=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,d]=t.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[c,u]=t.useState(!1),m=t.useRef(null);t.useEffect(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${l}px`):e.style.setProperty("--sidebar-width","240px"))},[l,o]);const p=t.useCallback(e=>{e.preventDefault(),u(!0)},[]);return t.useEffect(()=>{if(!c)return;const t=t=>{let r;r="left"===e?window.innerWidth-t.clientX:t.clientX,r=Math.max(a,Math.min(s,r)),d(r),i?.(r)},r=()=>{u(!1),localStorage.setItem(n,l.toString())};return document.addEventListener("mousemove",t),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",r)}},[c,e,a,s,l,n,i]),t.useEffect(()=>{c?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[c,e]),{width:l,isDragging:c,dragRef:m,handleMouseDown:p}}const sd=t.forwardRef(({className:t,onMouseDown:a,isDragging:s,...r},n)=>e.jsx("div",{ref:n,onMouseDown:a,className:nt("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-['']",s&&"bg-primary/40",t),...r}));function rd({config:a,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:i=384}={}){const{t:o}=Ya(),{open:d,setOpen:c}=qo(),u=b.useLocation(),{alias:m,user:p}=ar(),[h,f]=t.useState(!1),[x,g]=t.useState(Ql),[v,y]=t.useState(!1),N=t.useRef(!1),j=r?ad({minWidth:n,maxWidth:i,storageKey:"app-sidebar-width",isOpen:d}):null;t.useEffect(()=>{c(!!x||!(!v&&!h))},[x,v,h,c]);return e.jsxs(Wo,{collapsible:"icon",onMouseEnter:()=>{x||N.current||y(!0)},onMouseLeave:()=>{x||y(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:j&&d?{width:`${j.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e.jsx(td,{appName:a?.appName||o("module_title"),isPinned:x,onPinToggle:()=>{const e=!x;g(e),(e=>{try{localStorage.setItem(Gl,JSON.stringify(e))}catch{}})(e),e||(N.current=!0,y(!1),c(!1),setTimeout(()=>{N.current=!1},300))},open:d,dropdownOpen:h,onDropdownChange:f}),e.jsx(Zo,{children:s||e.jsx(el,{className:"p-0 mt-6",children:e.jsx(sl,{children:e.jsx(rl,{className:"space-y-2",children:e.jsx(Do,{children:a?.navigation?.map((t,a)=>{const s=({item:t,index:a})=>{const r=`${t.path}-${a}-${m??"noalias"}-${p?.id??"nouser"}`,{data:n=!0,isLoading:i}=Hl({key:r,enabled:Boolean(t.permissionCheck&&m&&p?.id),checkFn:t.permissionCheck||(()=>Promise.resolve(!0))}),d=t.permissionCheck&&!n;if(d&&"Admin"===t.label)return null;const c=i?l.Loader2:d?l.Lock:t.icon;d?o("restricted_access"):t.complementaryText;return t.children&&t.children.length>0?e.jsx(Ti,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(nl,{children:[e.jsx(Ai,{asChild:!0,children:e.jsx(ol,{size:"lg",className:"h-10",children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(c,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label}),e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),e.jsx(_i,{children:e.jsx(ul,{children:t.children.map((t,a)=>e.jsx(s,{item:t,index:a},t.path))})})]})},t.path):e.jsx(nl,{children:d||i?e.jsxs(Fo,{children:[e.jsx(zo,{asChild:!0,children:e.jsx(ol,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:e.jsxs("div",{className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(c,{className:"h-4 w-4 "+(i?"animate-spin":"")})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})}),e.jsx($o,{children:e.jsx("p",{children:o(i?"checking_access":"restricted_access")})})]}):e.jsx(ol,{asChild:!0,isActive:(h=t.path,u.pathname===h||u.pathname.startsWith(h+"/")),size:"lg",className:"h-10",children:e.jsxs(b.Link,{to:t.path,className:"flex w-full items-center gap-3",children:[e.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:e.jsx(c,{className:"h-5 w-4"})}),e.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:t.label})]})})},t.path);var h};return e.jsx(s,{item:t,index:a},t.path)})})})})})}),r&&j&&d&&e.jsx(sd,{ref:j.dragRef,onMouseDown:j.handleMouseDown,isDragging:j.isDragging})]})}sd.displayName="ResizableRail";const nd=t.memo(function({children:a,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const i=t.useMemo(()=>s||e.jsx(rd,{config:r}),[s,r]),o=t.useMemo(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e.jsx(Ul,{config:r,children:e.jsx(Un,{children:e.jsx(Bo,{defaultOpen:!1,style:o,children:e.jsxs("div",{className:"sidebar-container min-h-screen flex w-full",children:[i,e.jsxs("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[n&&e.jsx("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:e.jsx(Wl,{})}),e.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:a})]})]})})})})});var id=Object.defineProperty,od=(e,t,a)=>((e,t,a)=>t in e?id(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);class ld extends t.Component{constructor(e){super(e),od(this,"copyErrorDetails",()=>{const e=hs.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),oa({title:"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((void 0).DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,t){if((void 0).DEV)throw e;hs.handleError(e,!1),this.setState({errorInfo:t})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const t=hs.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(pt,{className:"w-full max-w-2xl",children:[e.jsxs(ht,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(l.AlertTriangle,{className:"h-12 w-12 text-destructive"})}),e.jsx(ft,{children:"Algo deu errado"})]}),e.jsxs(gt,{className:"space-y-4",children:[e.jsx("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),e.jsxs(Ti,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(Ai,{asChild:!0,children:e.jsxs(lt,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),e.jsxs(_i,{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsx("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&e.jsx(mn,{className:"h-32 w-full rounded border bg-muted p-2",children:e.jsx("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),t.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),e.jsx("div",{className:"space-y-2",children:t.map((t,a)=>e.jsx("div",{className:"text-sm p-2 rounded bg-muted/50",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"font-medium text-muted-foreground shrink-0",children:[a+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("span",{className:"text-xs text-muted-foreground",children:["[",new Date(t.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:t.message})]})]})},t.id))})]})]}),e.jsxs(lt,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[e.jsx(l.Copy,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),e.jsx(lt,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const dd={"pt-BR":Pi,"en-US":hi,"es-ES":Ni},cd=(e,t="pt-BR")=>{if(!e)return"";const a=i.parseISO(e);if(!i.isValid(a))return"Invalid date";const s=dd[t]||Pi;return i.format(a,"PP",{locale:s})};class ud{static async sendEmail(e){const t=Ns(),{data:a,error:s}=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(s)throw s;return a}}const md=ud;function pd(){const[e,a]=t.useState([]),[s,r]=t.useState(!1),[n,i]=t.useState(null),[l,d]=t.useState(null);t.useEffect(()=>{c()},[]);const c=async()=>{try{const e=Ns(),{data:t,error:s}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(s)throw s;i(t.threadId),a([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){d("Erro ao inicializar conversa"),o.toast.error("Erro ao inicializar conversa")}};return{messages:e,isLoading:s,error:l,sendMessage:t.useCallback(async e=>{if(!n||!e.trim())return;const t={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};a(e=>[...e,t]),r(!0),d(null);try{const t=Ns(),{data:s,error:r}=await t.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:n,message:e}});if(r)throw r;const{runId:i}=s,o=await(async e=>{if(!n)return!1;for(let a=0;a<60;a++)try{const t=Ns(),{data:a,error:s}=await t.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:n,runId:e}});if(s)throw s;const{status:r}=a;if("completed"===r)return!0;if("failed"===r||"cancelled"===r)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(n)try{const e=Ns(),{data:t,error:s}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:n}});if(s)throw s;const r=t.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));a(r)}catch(e){throw e}})()}catch(s){const e=s instanceof Error?s.message:"Erro ao enviar mensagem";d(e),o.toast.error(e),a(e=>e.filter(e=>e.id!==t.id))}finally{r(!1)}},[n]),threadId:n}}function hd({content:t,className:a}){return e.jsx("div",{className:nt("prose prose-sm max-w-none",a),children:e.jsx(z,{remarkPlugins:[$],components:{h1:({children:t})=>e.jsx("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:t}),h2:({children:t})=>e.jsx("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:t}),h3:({children:t})=>e.jsx("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:t}),p:({children:t})=>e.jsx("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:t}),ul:({children:t})=>e.jsx("ul",{className:"list-disc list-inside mb-2 space-y-1",children:t}),ol:({children:t})=>e.jsx("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:t}),li:({children:t})=>e.jsx("li",{className:"text-sm text-foreground",children:t}),code:({inline:t,children:a,...s})=>t?e.jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...s,children:a}):e.jsx("code",{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...s,children:a}),pre:({children:t})=>e.jsx("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:t}),a:({children:t,href:a})=>e.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:t}),blockquote:({children:t})=>e.jsx("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:t}),strong:({children:t})=>e.jsx("strong",{className:"font-bold text-foreground",children:t}),em:({children:t})=>e.jsx("em",{className:"italic text-foreground",children:t})},children:t})})}function fd({open:a,onOpenChange:s,placeId:r,placeName:n,onMakeManager:i,onMakeMembers:o,currentManagerId:d,currentMemberIds:c=[]}){const{t:u}=Ya(),[m,p]=t.useState([]),[h,f]=t.useState(!1),[x,g]=t.useState(""),{data:b=[],isLoading:v}=gn({enabled:a}),y=t.useMemo(()=>{let e=[...b];if(e.sort((e,t)=>{const a=e.userName?.toLowerCase()||"",s=t.userName?.toLowerCase()||"";return a.localeCompare(s)}),x){const t=x.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(t)||e.userEmail?.toLowerCase().includes(t))}return e},[b,x]),N=e=>{p(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},j=1===m.length,w=m.length>0;return e.jsx(vt,{open:a,onOpenChange:s,children:e.jsxs(kt,{className:"max-w-2xl",children:[e.jsx(Ct,{children:e.jsxs(Pt,{className:"flex items-center gap-2",children:[e.jsx(l.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",n]})}),e.jsxs("div",{className:"relative",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ct,{placeholder:u("search_placeholder"),value:x,onChange:e=>g(e.target.value),className:"pl-9"})]}),e.jsx(mn,{className:"h-[400px] pr-4",children:v?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((t,a)=>e.jsx(Ea,{className:"h-16 w-full"},a))}):0===y.length?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(l.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):e.jsx("div",{className:"space-y-2",children:y.map(t=>{const a=t.userId===d,s=c.includes(t.userId||""),r=m.includes(t.userId||"");return e.jsxs("div",{className:nt("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>N(t.userId||""),children:[e.jsx(Gt,{checked:r,onCheckedChange:()=>N(t.userId||""),onClick:e=>e.stopPropagation()}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:t.userName}),a&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t.userEmail})]}),(a||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:a?"Gestor":"Membro"})]},t.userId)})})}),e.jsxs(St,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:m.length>0&&e.jsxs("span",{children:[m.length," selecionado(s)"]})}),j&&i&&e.jsxs(lt,{onClick:async()=>{if(i&&1===m.length){f(!0);try{await i(m[0],r),p([])}finally{f(!1)}}},disabled:h,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),w&&o&&e.jsxs(lt,{onClick:async()=>{if(o&&0!==m.length){f(!0);try{await o(m,r),p([])}finally{f(!1)}}},disabled:h,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",m.length>1?"Membros":"Membro"]})]})]})})}function xd({place:a,level:s=0,manageAccessConfig:r}){const[n,i]=t.useState(!1),[o,d]=t.useState(!1),c=a.subPlaces&&a.subPlaces.length>0,u=a.isActive??!0,m=a.usersCount??0;return e.jsxs("div",{children:[e.jsxs(Ti,{open:n,onOpenChange:i,children:[e.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*s+1+"rem"},children:[c?e.jsxs(Ai,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:nt("h-4 w-4 transition-transform shrink-0",n&&"rotate-90")}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:a.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",a.subPlaces.length,")"]})]}):e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx("div",{className:"w-4 shrink-0"}),e.jsx(l.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:a.name})]}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(l.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m})]}),e.jsx(Jt,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(kl,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e.jsx(_i,{children:a.subPlaces.map(t=>e.jsx(xd,{place:t,level:s+1,manageAccessConfig:r},t.id))})]}),0===s&&e.jsx(Co,{}),r&&e.jsx(fd,{open:o,onOpenChange:d,placeId:a.id,placeName:a.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(a.id),currentMemberIds:r.getCurrentMemberIds?.(a.id)})]})}var gd=Object.defineProperty,bd=(e,t,a)=>((e,t,a)=>t in e?gd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a)(e,t+"",a);const vd=new class{constructor(){bd(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,t,a){const s=Es.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=us.getAccessToken();if(!r)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 ${r}`,"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 s=t.get(e.id);if(e.parentId){const r=t.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):a.push(s)}else a.push(s)}),a}async getPlaces(e,t){try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(a){if(await Es.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),s=a.data||a||[];return this.buildHierarchy(s)}catch(s){return hs.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return hs.handleError(a instanceof Error?a.message:"Erro ao buscar locais",!0),[]}}};function yd(e){const t=new Map,a=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};t.set(e.id,s),a.set(e.id_user,s)}),e.forEach(e=>{const r=t.get(e.id);if(e.id_leader){const t=a.get(e.id_leader);if(t)return void t.children.push(r)}s.push(r)});const r=(e,t)=>{e.level=t,e.children.forEach(e=>r(e,t+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,t)=>{const a=e.name||e.id_user||e.email||"",s=t.name||t.id_user||t.email||"";return a.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function Nd(e){const t=[],a=e=>{t.push(e),e.children.forEach(a)};return e.forEach(a),t}function jd(){const{alias:e,isAuthenticated:t}=ar(),a=us.getAccessToken(),{data:s=[]}=gn({enabled:!0});return g.useQuery({queryKey:["leadership",e,s.length],queryFn:async()=>{if(!a||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=Ns(),{data:r,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(!r||0===r.length)return[];const i={};s.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=r.map(e=>({...e,name:i[e.id_user]?.name||"[Não encontrado]",email:i[e.id_user]?.email||"",subordinatesCount:r.filter(t=>t.id_leader===e.id_user).length})),l=new Set(r.map(e=>e.id_user));return new Set(r.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:r[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:r.filter(t=>t.id_leader===e).length})}),yd(o)},enabled:!!a&&!!e&&t&&s.length>0})}function wd(){const e="common",{alias:t}=ar(),a=g.useQueryClient(),s=Ns();return g.useMutation({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 Ed(s,t,e,a.id_user,a.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success("Líder virtual promovido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao criar líder")}})}function kd(){const e="common",{alias:t}=ar(),a=g.useQueryClient(),s=Ns();return g.useMutation({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 r=a.users.map(e=>e.id_user),{data:n}=await s.schema(e).from("leaders").select("id_user").eq("alias",t).in("id_user",r).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 Ed(s,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 s.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{o.toast.error(e.message||"Erro ao adicionar liderados")}})}function Cd(){const e="common",{alias:t}=ar(),a=g.useQueryClient(),s=Ns();return g.useMutation({mutationFn:async a=>{if(!t)throw new Error("Unidade não selecionada");const{data:r}=await s.schema(e).from("leaders").select("id_user").eq("id",a.id).eq("alias",t).single();if(!r)throw new Error("Líder não encontrado");if(r.id_user===a.id_leader)throw new Error("Usuário não pode ser seu próprio líder");a.id_leader&&await Ed(s,t,e,r.id_user,a.id_leader,a.id);const{data:n,error:i}=await s.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]}),o.toast.success("Líder atualizado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao atualizar líder")}})}function Sd(){const{alias:e}=ar(),t=g.useQueryClient(),a=Ns();return g.useMutation({mutationFn:async t=>{if(!e)throw new Error("Unidade não selecionada");const{error:s}=await a.schema("common").from("leaders").update({is_removed:!0}).eq("id",t).eq("alias",e);if(s)throw s},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",e]}),o.toast.success("Líder removido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao remover líder")}})}function Pd(){const e="common",{alias:t}=ar(),a=g.useQueryClient(),s=Ns();return g.useMutation({mutationFn:async({leaderUserId:a,selectedUsers:r})=>{if(!t)throw new Error("Unidade não selecionada");const n=r.map(e=>e.id_user),i=await Promise.all([s.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).eq("id_leader",a),s.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||[],p=new Set(n),h=u.filter(e=>!p.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),x=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!x.has(e.id_user));for(const y of f)await Ed(s,t,e,y.id_user,a,y.id);for(const y of g){if(y.id_user===a)throw new Error("Usuário não pode ser seu próprio líder");await Ed(s,t,e,y.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(s.schema(e).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",t))}if(f.length){const r=f.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:a}).in("id",r).eq("alias",t))}if(g.length){const r=g.map(e=>({alias:t,id_user:e.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(s.schema(e).from("leaders").insert(r))}const v=(await Promise.all(b)).find(e=>e?.error);if(v?.error)throw v.error;return{unlinked:h.length,updated:f.length,created:g.length}},onSuccess:e=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{o.toast.error(e.message||"Erro ao sincronizar subordinados")}})}async function Ed(e,t,a,s,r,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=r;for(;c;){if(d.has(c))throw new Error("Esta associação criaria um ciclo na hierarquia");if(c===s)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 Td({leader:t,expandedIds:a,onToggleExpand:s,onEdit:r}){const n=a.has(t.id),i=t.children.length>0,o=32*t.level;return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[e.jsx("td",{className:"py-3 px-4",children:e.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${o}px`},children:[i?e.jsx("button",{onClick:()=>s(t.id),className:"p-1 hover:bg-accent rounded",children:n?e.jsx(l.ChevronDown,{className:"h-4 w-4"}):e.jsx(l.ChevronRight,{className:"h-4 w-4"})}):e.jsx("div",{className:"w-6"}),e.jsx(l.User,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("button",{onClick:()=>{r(t)},className:"font-medium hover:text-primary hover:underline text-left",children:t.name||t.id_user||t.email})]})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsx("span",{className:"text-sm",children:t.subordinatesCount||0})})]}),i&&n&&t.children.map(t=>e.jsx(Td,{leader:t,expandedIds:a,onToggleExpand:s,onEdit:r},t.id))]})}var Ad=function(e,t){for(var a={};e.length;){var s=e[0],r=s.code,n=s.message,i=s.path.join(".");if(!a[i])if("unionErrors"in s){var o=s.unionErrors[0].errors[0];a[i]={message:o.message,type:o.code}}else a[i]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=a[i].types,d=l&&l[s.code];a[i]=u.appendErrors(i,t,a,r,d?[].concat(d,s.message):s.message)}e.shift()}return a},_d=function(e,t,a){return void 0===a&&(a={}),function(s,r,n){try{return Promise.resolve(function(r,i){try{var o=Promise.resolve(e["sync"===a.mode?"parse":"parseAsync"](s,t)).then(function(e){return n.shouldUseNativeValidation&&V.validateFieldsNatively({},n),{errors:{},values:a.raw?s: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:V.toNestErrors(Ad(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const Id=U.z.object({id_leader:U.z.string().nullable(),id_users:U.z.array(U.z.string()).min(1,"Selecione pelo menos um liderado")}),Rd=U.z.object({id_leader:U.z.string().nullable(),id_users:U.z.array(U.z.string())});function Ld({value:a,onChange:s,excludeUserIds:r=[],error:n}){const{data:i=[],isLoading:o}=gn(),[d,c]=t.useState(""),u=t.useRef(null),m=t.useRef(0),{t:p}=Ya(),h=i.filter(e=>!r.includes(e.userId||"")).filter(e=>{const t=d.toLowerCase(),a=e.userName?.toLowerCase().includes(t);return a}).sort((e,t)=>{const s=a.includes(e.userId),r=a.includes(t.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",i=t.userName||t.userEmail||"";return n.localeCompare(i)});return t.useEffect(()=>{u.current&&m.current>0&&(u.current.scrollTop=m.current)},[h]),o?e.jsxs("div",{className:"flex items-center justify-center p-4",children:[e.jsx(l.Loader2,{className:"h-6 w-6 animate-spin"}),e.jsx("span",{className:"ml-2",children:p("loading_data")})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ct,{placeholder:p("search_user"),value:d,onChange:e=>c(e.target.value)}),e.jsx("div",{ref:u,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===h.length?e.jsx("p",{className:"text-sm text-muted-foreground",children:p("search_user")}):e.jsx("div",{className:"space-y-2",children:h.map(t=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Gt,{id:t.userId,checked:a.includes(t.userId),onCheckedChange:()=>{return e=t.userId,u.current&&(m.current=u.current.scrollTop),void(a.includes(e)?s(a.filter(t=>t!==e)):s([...a,e]));var e}}),e.jsx(mt,{htmlFor:t.userId,className:"flex-1 cursor-pointer",children:t.userName||t.userEmail})]},t.userId))})}),a.length>0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:p("selected_count",{count:a.length})}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function Md({leader:a,prefilledLeaderId:s,onSuccess:r}){const{t:n}=Ya(),{alias:i}=ar(),o=!!a,d=a?.id.startsWith("virtual-"),c=kd(),m=wd(),p=Cd(),h=Pd(),f=Sd(),{data:x=[]}=jd(),{data:g=[]}=gn(),[b,v]=t.useState(""),y=Nd(x).map(e=>e.id_user),N=o?Nd(x).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user):[],j=u.useForm({resolver:_d(o?Rd:Id),defaultValues:{id_leader:s||(o?a?.id_leader:null)||null,id_users:o?N:[]}});t.useEffect(()=>{if(a){const e=Nd(x).filter(e=>e.id_leader===a.id_user).map(e=>e.id_user);j.reset({id_leader:a.id_leader||null,id_users:e})}else s?j.reset({id_leader:s,id_users:[]}):j.reset({id_leader:null,id_users:[]})},[i,a?.id,a?.id_user,a?.id_leader,s,x]);const w=c.isPending||m.isPending||p.isPending||h.isPending||f.isPending,k=j.watch("id_leader"),C=j.watch("id_users"),S=o?[a.id_user,...y.filter(e=>e!==a.id_user&&!C.includes(e)&&!N.includes(e))]:[k,...y.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:j.handleSubmit(async e=>{try{if(o)if(d){await m.mutateAsync({id_user:a.id_user,id_leader:e.id_leader});const t=g.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await h.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{await p.mutateAsync({id:a.id,id_leader:e.id_leader});const t=g.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await h.mutateAsync({leaderUserId:a.id_user,selectedUsers:t})}else{const t=g.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await c.mutateAsync({id_leader:e.id_leader,users:t})}r?.()}catch(t){}}),className:"space-y-4",children:[o&&e.jsxs("div",{children:[e.jsx(mt,{children:n("leader")}),e.jsx(ct,{value:g.find(e=>e.userId===a.id_user)?.userName||a.name||a.id_user,disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(mt,{children:n("superior")}),e.jsxs(Ft,{value:k||"none",onValueChange:e=>j.setValue("id_leader","none"===e?null:e),children:[e.jsx(Ut,{children:e.jsx($t,{placeholder:n("select_placeholder")})}),e.jsxs(Bt,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(ct,{placeholder:n("superior_search"),value:b,onChange:e=>v(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(mn,{className:"h-[200px]",children:[e.jsx(Ht,{value:"none",children:"[Nenhum]"}),g.filter(e=>{const t=o?e.userId!==a.id_user:!C.includes(e.userId),s=!b||e.userName?.toLowerCase().includes(b.toLowerCase());return t&&s}).sort((e,t)=>{const a=e.userName||e.userEmail||"",s=t.userName||t.userEmail||"";return a.localeCompare(s)}).map(t=>e.jsx(Ht,{value:t.userId,children:t.userName},t.userId))]})]})]},`superior-select-${i}`),j.formState.errors.id_leader&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:j.formState.errors.id_leader.message})]}),e.jsxs("div",{children:[e.jsxs(mt,{children:[n("subordinates")," *"]}),e.jsx(Ld,{value:C,onChange:e=>j.setValue("id_users",e),excludeUserIds:S,error:j.formState.errors.id_users?.message},`users-multiselect-${i}`)]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(lt,{type:"submit",disabled:w||!o&&0===C.length,children:w&&!f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),n(o?"updating":"saving")]}):o?C.length>0?n("update_success",{count:C.length}):n("update"):n("create_success",{count:C.length})}),o&&!k&&0===C.length&&e.jsx(lt,{type:"button",variant:"destructive",disabled:w,onClick:async()=>{if(a&&window.confirm(n("remove_confirm")))try{await f.mutateAsync(a.id),r?.()}catch(e){}},className:"ml-auto",children:f.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),n("removing")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Trash2,{className:"mr-2 h-4 w-4"}),n("remove")]})})]})]})}function Od({open:t,onOpenChange:a,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(vt,{open:t,onOpenChange:a,children:e.jsxs(kt,{className:"sm:max-w-[500px]",children:[e.jsx(Ct,{children:e.jsx(Pt,{children:n})}),e.jsx(Md,{leader:s,prefilledLeaderId:r,onSuccess:()=>a(!1)})]})})}const Dd="leadership-expanded-nodes",Fd=(e,t)=>{try{localStorage.setItem(`${Dd}-${e}`,JSON.stringify(Array.from(t)))}catch(a){}};function zd(e){const[a,s]=t.useState(!1),[r,n]=t.useState(0),{t:i}=Ya(),{uploadFunction:o,deleteFunction:l,defaultOptions:d,onSuccess:c,onError:u}=e||{};return{upload:async(e,t)=>{if(!o){const e=new Error("uploadFunction não fornecida");throw oa({title:"Erro de configuração",description:"Função de upload não configurada. Verifique a documentação.",variant:"destructive"}),e}s(!0),n(0);try{const a={...d,...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 s=await o(e,a);return n(100),oa({title:"Sucesso",description:i("file_upload_success")}),c?.(s),s}catch(a){const e=a instanceof Error?a:new Error("Erro ao fazer upload");throw oa({title:"Erro",description:e.message,variant:"destructive"}),u?.(e),e}finally{s(!1)}},deleteMedia:async(e,t)=>{if(!l){const e=new Error("deleteFunction não fornecida");throw oa({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await l(e,t),oa({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(a){throw oa({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),a}},uploading:a,progress:r}}function $d(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 Ud(e,t){const a=$d(e);if(!a)return e;return`https://www.youtube.com/embed/${a}${t?"?autoplay=1&mute=1":""}`}function Vd(e){const t=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function qd(e,t){const a=Vd(e);if(!a)return e;return`https://player.vimeo.com/video/${a}${t?"?autoplay=1&muted=1":""}`}function Bd(e){if(!e)return;const t=e.match(/src="([^"]+)"/);return t?t[1]:void 0}function Wd(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Hd(e,t){return e/t}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return o.toast}}),exports.AUTH_CONFIG=Is,exports.Accordion=qn,exports.AccordionContent=Hn,exports.AccordionItem=Bn,exports.AccordionTrigger=Wn,exports.ActionButton=dt,exports.ActionMenu=kl,exports.ActionMenuItems=qr,exports.Alert=Dn,exports.AlertDescription=zn,exports.AlertDialog=rr,exports.AlertDialogAction=pr,exports.AlertDialogCancel=hr,exports.AlertDialogContent=lr,exports.AlertDialogDescription=mr,exports.AlertDialogFooter=cr,exports.AlertDialogHeader=dr,exports.AlertDialogOverlay=or,exports.AlertDialogPortal=ir,exports.AlertDialogTitle=ur,exports.AlertDialogTrigger=nr,exports.AlertTitle=Fn,exports.AppHeader=Wl,exports.AppLayout=nd,exports.AppSidebar=rd,exports.AspectRatio=Kn,exports.AuthErrorInterceptor=Ss,exports.AuthProvider=({children:a})=>{const[s,r]=t.useState({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=g.useQueryClient()}catch{}const[i,o]=t.useState(!1),[l,d]=t.useState(0),c=t.useCallback(e=>{r(t=>({...t,...e}))},[]),u=t.useCallback(e=>{r(t=>({...t,isLoading:e}))},[]),m=t.useCallback(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),p=t.useCallback(async e=>{try{u(!0);const a=us.getAccessToken();if(!a)return;const r=await js.generateToken(a,e.alias,void 0,!0);if(!r)return;us.setSupabaseToken(r),us.setSelectedAlias(e.alias);const i=us.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||us.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let m=null,p=null;if(s.user?.id&&o&&l)try{const e=(await _s.fetchActiveUsersMap(o,l)).get(s.user.id);if(e){const t=Ys(e);m=t.placeId,p=t.placeName}}catch(t){}c({alias:o,selectedUnit:d,placeId:m,placeName:p,activePlaceId:m,activePlaceName:p}),n&&(await n.clear(),await new Promise(e=>setTimeout(e,100)))}catch(t){}finally{u(!1)}},[c,n,u,s.user]),h=t.useCallback(async()=>await er.processCallback(),[]),f=t.useCallback(async()=>{er.logout(),m(),n&&await n.clear()},[m,n]),x=t.useCallback(e=>{o(e)},[]),b=t.useCallback(()=>{d(e=>e+1)},[]),v=t.useCallback(()=>{d(e=>e+1)},[]);t.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const t=setInterval(()=>{e&&(us.areAllTokensValid()||e&&f())},6e5);return()=>{e=!1,clearInterval(t)}},[s.isAuthenticated,f]),t.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const t=await er.initialize();if(!e)return;t&&t.isAuthenticated?c({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&&u(!1)}catch(t){e&&(Ss.handleError(t),u(!1))}})(),()=>{e=!1}},[c,u,f]);const y=t.useMemo(()=>({...s,logout:f,processCallback:h,switchUnit:p,availableUnits:s.companies,isSearchVisible:i,setSearchVisible:x,clearSearch:b,refreshData:v}),[s.user,s.companies,s.alias,s.isAuthenticated,s.isLoading,s.selectedUnit,s.userId,s.userAlias,s.placeId,s.placeName,s.activePlaceId,s.activePlaceName,f,h,p,i,x,b,v]);return e.jsx(tr.Provider,{value:y,children:a})},exports.AuthService=er,exports.Avatar=Gn,exports.AvatarFallback=Xn,exports.AvatarImage=Qn,exports.Badge=Jt,exports.BaseForm=vn,exports.Blockquote=mo,exports.Breadcrumb=Jn,exports.BreadcrumbEllipsis=si,exports.BreadcrumbItem=Zn,exports.BreadcrumbLink=ei,exports.BreadcrumbList=Yn,exports.BreadcrumbPage=ti,exports.BreadcrumbSeparator=ai,exports.BulkActionBar=jn,exports.Button=lt,exports.ButtonGroup=ni,exports.CRUD_CONFIG=Rs,exports.Calendar=Ei,exports.CallbackPage=()=>{const{processCallback:a}=ar(),[s,r]=t.useState(null),[n,i]=t.useState(!1);t.useEffect(()=>{(async()=>{try{if(await a()){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 r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro durante a autenticação. Tente novamente.")}})()},[a]);const o=async()=>{i(!0),r(null);try{await a()||r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro ao tentar novamente.")}finally{i(!1)}},d=()=>{window.location.href="/"};return s?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(pt,{className:"w-full max-w-md",children:[e.jsx(ht,{className:"text-center",children:e.jsxs(ft,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[e.jsx(l.AlertCircle,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),e.jsxs(gt,{className:"space-y-4",children:[e.jsx(Dn,{variant:"destructive",children:e.jsx(zn,{children:s})}),e.jsx("div",{className:"text-sm text-muted-foreground",children:e.jsx("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(lt,{onClick:o,disabled:n,className:"flex-1",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Zt,{size:"sm",className:"mr-2"}),"Tentando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.RefreshCw,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),e.jsx(lt,{onClick:d,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(pt,{className:"w-full max-w-md",children:[e.jsx(ht,{className:"text-center",children:e.jsx(ft,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(gt,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(Zt,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=pt,exports.CardContent=gt,exports.CardDescription=xt,exports.CardFooter=bt,exports.CardHeader=ht,exports.CardSkeleton=Cr,exports.CardTitle=ft,exports.Cards=function({data:t,renderCard:a,isLoading:s=!1,emptyMessage:r="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return s?e.jsx(Wi,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((t,a)=>e.jsx(Ea,{className:"h-48 w-full"},a))}):0===t.length?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:r})})}):e.jsx(Wi,{cols:n?String(n):"auto-fit",gap:i,className:o,children:t.map(a)})},exports.ChatbotPage=function(){const{t:a}=Ya(),[s,r]=t.useState(!1),[n,i]=t.useState(""),{messages:o,isLoading:d,error:c,sendMessage:u}=pd(),m=t.useRef(null),p=t.useRef(null);t.useEffect(()=>{if(m.current){const e=m.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[o]),t.useEffect(()=>{s&&p.current&&p.current.focus()},[s]),t.useEffect(()=>{const e=e=>{"Escape"===e.key&&s&&r(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[s]);const h=()=>{n.trim()&&!d&&(u(n),i(""))};return e.jsxs(e.Fragment,{children:[e.jsx(lt,{onClick:()=>r(!s),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:s?e.jsx(l.X,{className:"h-6 w-6"}):e.jsx(l.MessageCircle,{className:"h-6 w-6"})}),s&&e.jsxs(pt,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[e.jsxs(ht,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsx(ft,{className:"text-lg font-semibold",children:a("title")}),e.jsx(lt,{variant:"ghost",size:"icon",onClick:()=>r(!1),className:"h-8 w-8",children:e.jsx(l.X,{className:"h-4 w-4"})})]}),e.jsxs(gt,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e.jsx(mn,{ref:m,className:"flex-1 px-4",children:e.jsxs("div",{className:"space-y-4 py-4",children:[o.map(t=>e.jsx("div",{className:"flex "+("user"===t.role?"justify-end":"justify-start"),children:e.jsx("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.jsx(hd,{content:t.content}):e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:t.content})})},t.id)),d&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-muted rounded-lg px-4 py-2",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),e.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),c&&e.jsx("div",{className:"text-center text-sm text-destructive py-2",children:c})]})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx(ct,{ref:p,value:n,onChange:e=>i(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),h())},placeholder:a("placeholder"),disabled:d,className:"flex-1"}),e.jsx(lt,{onClick:h,disabled:d||!n.trim(),size:"icon",children:e.jsx(l.Send,{className:"h-4 w-4"})})]})})]})]})]})},exports.Checkbox=Gt,exports.Collapsible=Ti,exports.CollapsibleContent=_i,exports.CollapsibleTrigger=Ai,exports.ColorPicker=un,exports.Combobox=ts,exports.Command=ya,exports.CommandDialog=({children:t,...a})=>e.jsx("div",{...a,children:e.jsx(ya,{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})}),exports.CommandEmpty=wa,exports.CommandGroup=ka,exports.CommandInput=Na,exports.CommandItem=Sa,exports.CommandList=ja,exports.CommandSeparator=Ca,exports.CommandShortcut=Pa,exports.ContextMenu=Wr,exports.ContextMenuCheckboxItem=tn,exports.ContextMenuContent=Zr,exports.ContextMenuGroup=Kr,exports.ContextMenuItem=en,exports.ContextMenuLabel=sn,exports.ContextMenuPortal=Gr,exports.ContextMenuRadioGroup=Xr,exports.ContextMenuRadioItem=an,exports.ContextMenuSeparator=rn,exports.ContextMenuShortcut=nn,exports.ContextMenuSub=Qr,exports.ContextMenuSubContent=Yr,exports.ContextMenuSubTrigger=Jr,exports.ContextMenuTrigger=Hr,exports.CrudCards=function({manager:t,config:a,onEdit:s,onDelete:r}){const{t:n}=Ya();return t.isLoading?e.jsx(Wi,{children:Array.from({length:3}).map((t,a)=>e.jsxs(pt,{children:[e.jsxs(ht,{children:[e.jsx(Ea,{className:"h-4 w-3/4"}),e.jsx(Ea,{className:"h-3 w-1/2"})]}),e.jsx(gt,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ea,{className:"h-3 w-full"}),e.jsx(Ea,{className:"h-3 w-2/3"})]})})]},a))}):e.jsx(Ii.Root,{children:t.entities.map(t=>e.jsxs(Ii.Item,{onClick:()=>s(t),children:[e.jsx(ht,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ft,{className:"text-base leading-6 truncate",children:t.title||t.name||n("no_title")}),e.jsx(xt,{className:"text-sm",children:i.format(new Date(t.created_at),"dd/MM/yyyy HH:mm",{locale:Pi})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-2",children:[t.link&&e.jsx(lt,{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),o.toast.info(n("link_copied")))}catch(t){window.location.href=e}})(t.link)},title:n("open_external_link"),children:e.jsx(l.ExternalLink,{className:"h-4 w-4"})}),e.jsx("div",{onClick:e=>e.stopPropagation(),children:e.jsx(Br,{onEdit:()=>s(t),onDelete:r?()=>r(t):void 0,canDelete:!!r})})]})]})}),e.jsx(gt,{className:"pt-0",children:e.jsx("div",{className:"space-y-2",children:a.cardFields?.map(a=>{const s=t[a.key];return s?e.jsx(Ii.Field,{label:a.label,value:a.render?a.render(s,t):String(s)},String(a.key)):null})})})]},t.id))})},exports.CrudPageInternal=En,exports.CrudPagination=Nn,exports.CrudPrimitiveFilterBar=function({searchValue:t="",onSearchChange:a,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:i="horizontal"}){const{t:o}=Ya(),d=t||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===i?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[a&&e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(l.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ct,{type:"text",placeholder:o("search"),value:t,onChange:e=>a(e.target.value),className:"pl-9 h-9"})]}),s.map((t,a)=>e.jsx("div",{className:"vertical"===i?"w-full":"",children:t},a)),n&&d&&r&&e.jsxs(lt,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[e.jsx(l.X,{size:14,className:"mr-1"}),o("clear_filters")]})]})},exports.CrudPrimitivePagination=yn,exports.CrudPrimitiveTable=function({data:a,columns:s,sortField:r,sortDirection:n,onSort:i,onRowClick:o,renderActions:d,isLoading:c=!1,emptyMessage:u="Nenhum item encontrado",className:m,enableSelection:p=!1,selectedIds:h=[],onSelectItem:f,onSelectAll:x,isAllSelected:g=!1}){const b=t.useMemo(()=>{const e=s.reduce((e,t)=>t.width?e:e+(t.weight??1),0);return s.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}%`})},[s]);return c?e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((t,a)=>e.jsx(Ea,{className:"h-12 w-full"},a))})}):0===a.length?e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{children:u})})}):e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsxs(xr,{className:m,children:[e.jsx(gr,{className:"sticky top-0 bg-background z-10",children:e.jsxs(yr,{children:[p&&e.jsx(Nr,{className:"w-[40px]",children:e.jsx(Gt,{checked:g,onCheckedChange:x,"aria-label":"Selecionar todos"})}),s.map((t,a)=>{return e.jsx(Nr,{className:t.className,style:{width:b[a]},children:t.sortable&&i?e.jsxs("button",{onClick:()=>i(String(t.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[t.header,(s=String(t.key),r!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===n?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]}):e.jsx("span",{className:"font-medium",children:t.header})},String(t.key));var s}),d&&e.jsx(Nr,{className:"w-[80px] text-right",children:"Ações"})]})}),e.jsx(br,{children:a.map(t=>e.jsxs(yr,{onClick:()=>o?.(t),className:o?"cursor-pointer":"",children:[p&&e.jsx(jr,{children:e.jsx(Gt,{checked:h.includes(t.id),onCheckedChange:()=>f?.(t.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${t.id}`})}),s.map(a=>e.jsx(jr,{className:a.className,children:a.render?a.render(t):String(t[a.key]??"-")},String(a.key))),d&&e.jsx(jr,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(t)})]},t.id))})]})})},exports.CrudTable=ln,exports.DataList=Ii,exports.DatePicker=function({date:t,onDateChange:a,placeholder:s="Pick a date",disabled:r=!1,className:n,disabledDates:o}){return e.jsxs(ga,{children:[e.jsx(ba,{asChild:!0,children:e.jsxs(lt,{variant:"outline",disabled:r,className:nt("w-full justify-start text-left font-normal",!t&&"text-muted-foreground",n),children:[e.jsx(l.Calendar,{className:"mr-2 h-4 w-4"}),t?i.format(t,"PPP"):e.jsx("span",{children:s})]})}),e.jsx(va,{className:"w-auto p-0",align:"start",children:e.jsx(Ei,{mode:"single",selected:t,onSelect:a,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})},exports.DeleteConfirmationDialog=fr,exports.Dialog=vt,exports.DialogClose=jt,exports.DialogContent=kt,exports.DialogDescription=Et,exports.DialogFooter=St,exports.DialogHeader=Ct,exports.DialogOverlay=wt,exports.DialogPortal=Nt,exports.DialogTitle=Pt,exports.DialogTrigger=yt,exports.Drawer=Ri,exports.DrawerClose=Oi,exports.DrawerContent=Fi,exports.DrawerDescription=Vi,exports.DrawerFooter=$i,exports.DrawerHeader=zi,exports.DrawerOverlay=Di,exports.DrawerPortal=Mi,exports.DrawerTitle=Ui,exports.DrawerTrigger=Li,exports.DropdownMenu=Er,exports.DropdownMenuCheckboxItem=Fr,exports.DropdownMenuContent=Or,exports.DropdownMenuGroup=Ar,exports.DropdownMenuItem=Dr,exports.DropdownMenuLabel=$r,exports.DropdownMenuPortal=_r,exports.DropdownMenuRadioGroup=Rr,exports.DropdownMenuRadioItem=zr,exports.DropdownMenuSeparator=Ur,exports.DropdownMenuShortcut=Vr,exports.DropdownMenuSub=Ir,exports.DropdownMenuSubContent=Mr,exports.DropdownMenuSubTrigger=Lr,exports.DropdownMenuTrigger=Tr,exports.EmailService=ud,exports.EmptyState=Pr,exports.EntitySelect=ts,exports.ErrorBoundary=ld,exports.FilterBar=Pn,exports.Form=Tt,exports.FormControl=Mt,exports.FormDescription=Ot,exports.FormField=({...t})=>e.jsx(At.Provider,{value:{name:t.name},children:e.jsx(u.Controller,{...t})}),exports.FormItem=Rt,exports.FormLabel=Lt,exports.FormMessage=Dt,exports.FormSkeleton=function({fields:t=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:t}).map((t,a)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ea,{className:"h-4 w-24"}),e.jsx(Ea,{className:"h-10 w-full"})]},a)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Ea,{className:"h-10 w-20"}),e.jsx(Ea,{className:"h-10 w-20"})]})]})},exports.Grid=Wi,exports.H1=to,exports.H2=ao,exports.H3=so,exports.H4=ro,exports.HeaderSkeleton=function(){return e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{className:"flex items-center space-x-3",children:[e.jsx(Ea,{className:"h-8 w-8 rounded-full"}),e.jsx(Ea,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ea,{className:"h-8 w-8"}),e.jsx(Ea,{className:"h-8 w-24"})]})]})},exports.I18nextProvider=function({i18n:e,defaultNS:a,children:s}){const r=t.useMemo(()=>({i18n:e,defaultNS:a}),[e,a]);return t.createElement(Ua.Provider,{value:r},s)},exports.IconPicker=fn,exports.ImageEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const{t:c}=Ya(),[u,m]=t.useState(a||{alignment:"center",allowDownload:!1}),p=t.useRef(null),{upload:h,uploading:f}=zd({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),x=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("url")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ct,{type:"url",placeholder:c("url_placeholder"),value:u.imageUrl||"",onChange:e=>x("imageUrl",e.target.value),className:"flex-1"}),i&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await h(t),a={...u,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(lt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),c("uploading")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),c("upload")]})})]})]}),u.imageFile&&e.jsx("p",{className:"text-xs text-muted-foreground",children:c("image.fileInfo",{name:u.imageFile,size:Math.round((u.imageSize||0)/1024)})})]}),u.imageUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("preview")}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:e.jsx("div",{className:"flex "+("left"===u.alignment?"justify-start":"right"===u.alignment?"justify-end":"justify-center"),children:e.jsx("img",{src:u.imageUrl,alt:u.alt||"Preview",style:{width:u.width?`${u.width}px`:"auto",height:u.height?`${u.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{htmlFor:"caption",children:c("caption")}),e.jsx(Qt,{id:"caption",placeholder:c("caption"),value:u.caption||"",onChange:e=>x("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{htmlFor:"alt",children:c("alt")}),e.jsx(ct,{id:"alt",placeholder:c("alt"),value:u.alt||"",onChange:e=>x("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("alignment")}),e.jsxs(Ft,{value:u.alignment||"center",onValueChange:e=>x("alignment",e),children:[e.jsx(Ut,{children:e.jsx($t,{})}),e.jsxs(Bt,{children:[e.jsx(Ht,{value:"left",children:c("left")}),e.jsx(Ht,{value:"center",children:c("center")}),e.jsx(Ht,{value:"right",children:c("right")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{htmlFor:"width",children:c("width")}),e.jsx(ct,{id:"width",type:"number",placeholder:"px",value:u.width||"",onChange:e=>x("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{htmlFor:"height",children:c("height")}),e.jsx(ct,{id:"height",type:"number",placeholder:"px",value:u.height||"",onChange:e=>x("height",e.target.value?Number(e.target.value):void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"allowDownload",type:"checkbox",checked:u.allowDownload||!1,onChange:e=>x("allowDownload",e.target.checked),className:"h-4 w-4"}),e.jsx(mt,{htmlFor:"allowDownload",className:"cursor-pointer",children:c("allow_download")})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(lt,{variant:"outline",onClick:n,children:c("cancel")}),e.jsx(lt,{onClick:()=>{u.imageUrl?r(u):oa({title:c("error"),description:c("error_no_image"),variant:"destructive"})},disabled:!u.imageUrl,children:c("save")})]})]})},exports.ImageRenderer=function({content:t,className:a="",style:s}){if(!t.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[t.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${a}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:t.imageUrl,alt:t.alt||"",style:{width:t.width?`${t.width}px`:"auto",height:t.height?`${t.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),t.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:t.caption}),t.allowDownload&&t.imageUrl&&e.jsxs("a",{href:t.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[e.jsx(l.Download,{className:"h-4 w-4"}),"Baixar imagem"]})]})})},exports.InlineCode=uo,exports.Input=ct,exports.InputGroup=Hi,exports.InputGroupAddon=Gi,exports.InputGroupButton=Xi,exports.InputGroupInput=Ji,exports.InputGroupTextarea=Yi,exports.Kbd=Zi,exports.LOGO_CONFIG=Fs,exports.Label=mt,exports.Large=oo,exports.Lead=io,exports.LeaderRow=Td,exports.LeadershipDialog=Od,exports.LeadershipForm=Md,exports.LeadershipPage=function(){const{alias:a}=ar(),{t:s}=Ya(),{data:r,isLoading:n,error:i,refetch:o}=jd(),{data:d=[]}=gn({enabled:!0}),[c,u]=t.useState(()=>a?(e=>{try{const t=localStorage.getItem(`${Dd}-${e}`);if(t)return new Set(JSON.parse(t))}catch(i){}return new Set})(a):new Set),[m,p]=t.useState(!1),[h,f]=t.useState(),[x,g]=t.useState(null),b=d.filter(e=>e.userName&&"Nome não disponível"!==e.userName),v=new Set(b.map(e=>e.userId)),y=b.length-(r?Nd(r).filter(e=>v.has(e.id_user)&&"[Não encontrado]"!==e.name).length:0);t.useEffect(()=>{if(r&&r.length>0&&a){if(!localStorage.getItem(`${Dd}-${a}`)){const e=r.map(e=>e.id),t=new Set(e);u(t),Fd(a,t)}}},[r,a]);const N=e=>{u(t=>{const s=new Set(t);return s.has(e)?s.delete(e):s.add(e),a&&Fd(a,s),s})},j=e=>{f(e),g(null),p(!0)};return n?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx(l.RefreshCw,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:s("loading")})]})}):i?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),e.jsx(lt,{onClick:()=>o(),children:"Tentar novamente"})]})}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex items-center justify-between p-4 border-b",children:e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(lt,{size:"sm",onClick:()=>{f(void 0),g(null),p(!0)},children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsxs(lt,{variant:"outline",size:"sm",onClick:()=>{if(!r)return;const e=Nd(r).filter(e=>e.children.length>0).map(e=>e.id),t=new Set(e);u(t),a&&Fd(a,t)},disabled:!r||0===r.length,children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),e.jsxs(lt,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;u(e),a&&Fd(a,e)},disabled:!r||0===r.length,children:[e.jsx(l.ChevronRight,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[e.jsx(l.Users,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[y," usuário",1!==y?"s":""," não associado",1!==y?"s":""]})]})})]})}),r&&0!==r.length?e.jsx(mn,{className:"flex-1",children:e.jsx("div",{children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),e.jsx("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),e.jsx("tbody",{children:r.map(t=>e.jsx(Td,{leader:t,expandedIds:c,onToggleExpand:N,onEdit:j},t.id))})]})})}):e.jsx("div",{className:"flex items-center justify-center flex-1",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),e.jsx(Od,{open:m,onOpenChange:()=>{p(!1),f(void 0),g(null)},leader:h,prefilledLeaderId:x,title:h?s("edit")+" "+s("name"):x?s("add")+" Liderado":s("add")+" Líder Raiz"},`leadership-dialog-${a}`)]})},exports.List=po,exports.LoadingState=function({isLoading:t,children:a,className:s,type:r="spinner",size:n="md"}){return t?"overlay"===r?e.jsxs("div",{className:nt("relative",s),children:[a,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(Zt,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:nt("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:nt("flex items-center justify-center py-8",s),children:e.jsx(Zt,{size:n})}):e.jsx(e.Fragment,{children:a})},exports.LocaleProvider=({children:a})=>{const{user:s,alias:r}=ar(),[n,i]=t.useState({locale:"pt-BR",timezone:"America/Sao_Paulo",datetimeFormat:"dd/MM/yyyy HH:mm"}),[o,l]=t.useState(!0);t.useEffect(()=>{(async()=>{if(s?.id&&r)try{const e=await Sl.getUserPreferences(s.id,r);e&&(i({locale:e.locale,timezone:e.timezone,datetimeFormat:e.datetimeFormat}),await st.changeLanguage(e.locale),localStorage.setItem("i18nextLng",e.locale))}catch(e){}finally{l(!1)}else l(!1)})()},[s?.id,r]);const d=t.useCallback(async e=>{if(s?.id&&r)try{await Sl.updatePreferences(s.id,r,{locale:e}),i(t=>({...t,locale:e})),await st.changeLanguage(e),localStorage.setItem("i18nextLng",e)}catch(t){throw t}},[s?.id,r]),c=t.useCallback(async e=>{if(s?.id&&r)try{await Sl.updatePreferences(s.id,r,{timezone:e}),i(t=>({...t,timezone:e}))}catch(t){throw t}},[s?.id,r]),u=t.useCallback(async e=>{if(s?.id&&r)try{await Sl.updatePreferences(s.id,r,{datetime_format:e}),i(t=>({...t,datetimeFormat:e}))}catch(t){throw t}},[s?.id,r]);return e.jsx(Rl.Provider,{value:{...n,setLocale:d,setTimezone:c,setDatetimeFormat:u,isLoading:o},children:a})},exports.LocaleSelector=Fl,exports.LoginPage=()=>e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(pt,{className:"w-full max-w-md",children:[e.jsx(ht,{className:"text-center",children:e.jsx(ft,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(gt,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(lt,{onClick:async()=>{Ms()?await er.loginDev():er.loginProd()},className:"w-full",size:"lg",children:Ms()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=zs,exports.ManageAccessModal=fd,exports.MarkdownMessage=hd,exports.MultiSelect=ts,exports.Muted=co,exports.NativeSelect=eo,exports.NavigationProvider=Ul,exports.P=no,exports.PageBreadcrumb=function({items:t,maxItems:a=3,className:s}){return t.length>a&&(t[0],t.slice(-(a-1))),t.length,e.jsx(Jn,{className:s})},exports.PageMetadataProvider=Un,exports.Pagination=ho,exports.PaginationContent=fo,exports.PaginationEllipsis=yo,exports.PaginationItem=xo,exports.PaginationLink=go,exports.PaginationNext=vo,exports.PaginationPrevious=bo,exports.PlaceCard=xd,exports.PlacesList=function({places:t,isLoading:a,manageAccessConfig:s}){const{t:r}=Ya();return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r("loading_data")})]})}):t&&0!==t.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),t.map(t=>e.jsx(xd,{place:t,manageAccessConfig:s},t.id))]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[e.jsx(l.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.Popover=ga,exports.PopoverContent=va,exports.PopoverTrigger=ba,exports.Progress=_n,exports.ProtectedRoute=({children:a})=>{const{isAuthenticated:s,isLoading:r}=ar();if(t.useEffect(()=>{if(!s)return;const e=()=>{us.areAllTokensValid()||er.logout()};e();const t=setInterval(e,3e5);return()=>clearInterval(t)},[s]),t.useEffect(()=>{if(r)return;if(s)return;if(us.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 n=Ms();(async()=>{n?await er.loginDev():er.loginProd()})()},[s,r]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(pt,{className:"w-full max-w-md",children:[e.jsx(ht,{className:"text-center",children:e.jsx(ft,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(gt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!s){return new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token")?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(pt,{className:"w-full max-w-md",children:[e.jsx(ht,{className:"text-center",children:e.jsx(ft,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(gt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:e.jsxs(pt,{className:"w-full max-w-md",children:[e.jsx(ht,{className:"text-center",children:e.jsx(ft,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(gt,{className:"text-center",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:Ms()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:a})},exports.QUALIEX_CONFIG=Os,exports.QUERY_KEYS={crud:e=>[e],list:(e,t)=>[e,"list",t],detail:(e,t)=>[e,"detail",t]},exports.QualiexEnrichmentService=Ws,exports.QualiexErrorInterceptor=Es,exports.QualiexUserField=bn,exports.RadioGroup=No,exports.RadioGroupItem=jo,exports.ResizableRail=sd,exports.SEARCH_CONFIG=Ls,exports.ScrollArea=mn,exports.ScrollBar=pn,exports.Searchbar=ko,exports.Select=Ft,exports.SelectContent=Bt,exports.SelectGroup=zt,exports.SelectItem=Ht,exports.SelectLabel=Wt,exports.SelectScrollDownButton=qt,exports.SelectScrollUpButton=Vt,exports.SelectSearch=ts,exports.SelectSeparator=Kt,exports.SelectTrigger=Ut,exports.SelectValue=$t,exports.Separator=Co,exports.Sheet=So,exports.SheetClose=Eo,exports.SheetContent=Io,exports.SheetDescription=Oo,exports.SheetFooter=Lo,exports.SheetHeader=Ro,exports.SheetOverlay=Ao,exports.SheetPortal=To,exports.SheetTitle=Mo,exports.SheetTrigger=Po,exports.Sidebar=Wo,exports.SidebarContent=Zo,exports.SidebarFooter=Jo,exports.SidebarGroup=el,exports.SidebarGroupAction=al,exports.SidebarGroupContent=sl,exports.SidebarGroupLabel=tl,exports.SidebarHeader=td,exports.SidebarInput=Qo,exports.SidebarInset=Go,exports.SidebarMenu=rl,exports.SidebarMenuAction=ll,exports.SidebarMenuBadge=dl,exports.SidebarMenuButton=ol,exports.SidebarMenuItem=nl,exports.SidebarMenuSkeleton=cl,exports.SidebarMenuSub=ul,exports.SidebarMenuSubButton=pl,exports.SidebarMenuSubItem=ml,exports.SidebarProvider=Bo,exports.SidebarRail=Ko,exports.SidebarSeparator=Yo,exports.SidebarSkeleton=function(){return e.jsx("div",{className:"w-64 border-r bg-muted/10",children:e.jsxs("div",{className:"p-4",children:[e.jsx(Ea,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((t,a)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(Ea,{className:"h-4 w-4"}),e.jsx(Ea,{className:"h-4 w-20"})]},a))})]})})},exports.SidebarTrigger=Ho,exports.Skeleton=Ea,exports.Slider=hl,exports.Small=lo,exports.SonnerToaster=({...t})=>{const{theme:a="system"}=M.useTheme();return e.jsx(o.Toaster,{theme:a,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",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"}},...t})},exports.Spinner=Zt,exports.Stack=Sn,exports.StatusSelect=function({value:t,onChange:a,activeLabel:s,inactiveLabel:r,allLabel:n,placeholder:i,className:o="w-full sm:w-[180px]"}){const{t:l}=Ya(),d=[{id:"active",name:s||l("active")},{id:"inactive",name:r||l("inactive")},{id:"all",name:n||l("all")}];return e.jsx(ts,{value:t,onChange:e=>a(e),options:d,getOptionValue:e=>e.id,getOptionLabel:e=>e.name,placeholder:i||l("select"),className:o})},exports.Switch=xn,exports.TabPageContent=function({children:t,className:a}){return e.jsx("div",{className:nt("space-y-6",a),children:t})},exports.TabPageHeader=function({title:t,description:a,actions:s,className:r}){return e.jsxs("div",{className:nt("space-y-4",r),children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:t}),a&&e.jsx("p",{className:"text-muted-foreground text-sm",children:a})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx(Co,{})]})},exports.TabPageLayout=function({children:t,className:a}){return e.jsx("div",{className:nt("flex flex-col h-full",a),children:e.jsx(mn,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:t})})})},exports.Table=xr,exports.TableBody=br,exports.TableCaption=wr,exports.TableCell=jr,exports.TableFooter=vr,exports.TableHead=Nr,exports.TableHeader=gr,exports.TableRow=yr,exports.TableRowActions=Br,exports.TableSkeleton=kr,exports.Tabs=fl,exports.TabsContent=bl,exports.TabsList=xl,exports.TabsTrigger=gl,exports.Textarea=Qt,exports.Toast=ma,exports.ToastAction=pa,exports.ToastClose=ha,exports.ToastDescription=xa,exports.ToastProvider=da,exports.ToastTitle=fa,exports.ToastViewport=ca,exports.Toaster=function(){const{toasts:t}=la();return e.jsxs(da,{children:[t.map(function({id:t,title:a,description:s,action:r,...n}){return e.jsxs(ma,{...n,children:[e.jsxs("div",{className:"grid gap-1",children:[a&&e.jsx(fa,{children:a}),s&&e.jsx(xa,{children:s})]}),r,e.jsx(ha,{})]},t)}),e.jsx(ca,{})]})},exports.Toggle=yl,exports.ToggleGroup=jl,exports.ToggleGroupItem=wl,exports.TokenManager=us,exports.TokenService=ss,exports.Tooltip=Fo,exports.TooltipContent=$o,exports.TooltipProvider=Do,exports.TooltipTrigger=zo,exports.TranslationLoader=function({children:a}){const{ready:s}=Ya(),[r,n]=t.useState(!0);return t.useEffect(()=>{s&&r&&n(!1)},[s,r]),r&&!s?e.jsx("div",{className:"flex items-center justify-center min-h-screen bg-background",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Zt,{size:"lg"}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Carregando traduções..."})]})}):e.jsx(e.Fragment,{children:a})},exports.VideoEditor=function({value:a,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const{t:c}=Ya(),[u,m]=t.useState(a||{inputType:"url",controls:!0}),p=t.useRef(null),h=t.useRef(null),{upload:f,uploading:x}=zd({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["video/*"],maxSize:104857600}}),{upload:g,uploading:b}=zd({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),v=t.useMemo(()=>Wd(u.videoUrl||Bd(u.embedCode)||""),[u.videoUrl,u.embedCode]),y=(e,t)=>{const a={...u,[e]:t};m(a),s(a)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("input_type")}),e.jsxs(Ft,{value:u.inputType||"url",onValueChange:e=>y("inputType",e),children:[e.jsx(Ut,{children:e.jsx($t,{})}),e.jsxs(Bt,{children:[e.jsx(Ht,{value:"url",children:c("url")}),e.jsx(Ht,{value:"upload",children:c("input_type_upload")}),e.jsx(Ht,{value:"embed",children:c("input_type_embed")})]})]})]}),"upload"===u.inputType&&i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("file")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:p,type:"file",accept:"video/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await f(t),a={...u,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:u.title||t.name.replace(/\.[^/.]+$/,"")};m(a),s(a)}catch(a){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(lt,{type:"button",variant:"outline",onClick:()=>p.current?.click(),disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),c("uploading")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),c("select_video")]})}),u.videoFile&&e.jsx("span",{className:"text-xs text-muted-foreground truncate self-center",children:c("video.fileInfo",{name:u.videoFile,size:Math.round((u.videoSize||0)/1024/1024)})})]})]}),"embed"===u.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("embed")}),e.jsx(Qt,{placeholder:c("embed"),value:u.embedCode||"",onChange:e=>y("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("thumbnail")}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ct,{type:"url",placeholder:c("thumbnail"),value:u.thumbnail||"",onChange:e=>y("thumbnail",e.target.value),className:"flex-1"}),e.jsx("input",{ref:h,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await g(t),a={...u,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};m(a),s(a)}catch(a){}finally{h.current&&(h.current.value="")}},className:"hidden"}),e.jsx(lt,{type:"button",variant:"outline",onClick:()=>h.current?.click(),disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),c("video.uploading")]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),c("upload")]})})]}),u.thumbnailFile&&e.jsx("p",{className:"text-xs text-muted-foreground",children:c("video.thumbnailFileInfo",{name:u.thumbnailFile})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{htmlFor:"title",children:c("title")}),e.jsx(ct,{id:"title",placeholder:c("title"),value:u.title||"",onChange:e=>y("title",e.target.value)})]}),e.jsxs("div",{className:"flex gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"autoplay",type:"checkbox",checked:u.autoplay||!1,onChange:e=>y("autoplay",e.target.checked),className:"h-4 w-4"}),e.jsx(mt,{htmlFor:"autoplay",className:"cursor-pointer",children:c("video.autoplay")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"controls",type:"checkbox",checked:!1!==u.controls,onChange:e=>y("controls",e.target.checked),className:"h-4 w-4"}),e.jsx(mt,{htmlFor:"controls",className:"cursor-pointer",children:c("video.controls")})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(mt,{children:c("preview")}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const t=u.videoUrl||Bd(u.embedCode)||"";if(!t)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:c("no_content_preview")});if("file"===v)return e.jsxs("video",{controls:!1!==u.controls,autoPlay:u.autoplay,poster:u.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e.jsx("source",{src:t}),c("unsupported")]});const a="youtube"===v?Ud(t,u.autoplay):qd(t,u.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:u.title||c("video"),src:a,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(lt,{variant:"outline",onClick:n,children:c("cancel")}),e.jsx(lt,{onClick:()=>{u.videoUrl||u.embedCode?r(u):oa({title:c("error"),description:c("error_no_video"),variant:"destructive"})},disabled:!(u.videoUrl||u.embedCode),children:c("save")})]})]})},exports.VideoRenderer=function({content:t,className:a="",style:s}){const r=t.videoUrl||Bd(t.embedCode)||"";if(!r)return null;const n=Wd(r),{t:i}=Ya();return e.jsx(pt,{className:`overflow-hidden my-4 ${a}`,style:s,children:e.jsxs(gt,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==t.controls,autoPlay:t.autoplay,poster:t.thumbnail,className:"w-full h-auto",playsInline:!0,muted:t.autoplay,children:[e.jsx("source",{src:r}),"Seu navegador não suporta vídeos HTML5."]}):e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:t.title||i("video"),src:"youtube"===n?Ud(r,t.autoplay):qd(r,t.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),t.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:t.title})})]})})},exports.WizardBreadcrumb=Rn,exports.WizardButtons=Mn,exports.WizardForm=function({title:a,sections:s,initialData:r,onSubmit:n,onCancel:i,open:o,submitButtonText:l,isLoading:d=!1,usersData:c,showProgressIndicator:u=!0,progressType:m="stepper",validateOnNext:p=!0,allowSkipSections:h=!1,previousButtonText:f,nextButtonText:x,onStepChange:g,onStepValidationFail:b,renderProgressIndicator:v,renderButtons:y,currentStepIndex:N,onCurrentStepChange:j}){const[w,k]=t.useState(0),C=N??w,S=j??k,P=t.useRef(null),[E,T]=t.useState(null),A=t.useCallback(e=>{P.current=e,T(e)},[]),_=t.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:I,errors:R,updateField:L,handleSubmit:M}=dn(_,r,void 0,o);t.useEffect(()=>{o&&S(0)},[o,S]);const O=t.useCallback(()=>{const e=s[C];if(!e)return!0;const t=e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e),a={};let r=!0;return t.forEach(e=>{const t=I[e.name];if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length)&&(a[e.name]=`${e.label} é obrigatório`,r=!1),e.validation&&"function"==typeof e.validation){const s=e.validation(t,I);s&&(a[e.name]=s,r=!1)}}),!r&&b&&b(C,a),r},[s,C,I,b]),D=t.useCallback(()=>{if(p&&!O())return;const e=C+1;e<s.length&&(S(e),g?.(e,s[e].id))},[C,s,p,O,S,g]),F=t.useCallback(()=>{const e=C-1;e>=0&&(S(e),g?.(e,s[e].id))},[C,s,S,g]),z=t.useCallback(()=>{let e=!0;for(let t=0;t<s.length;t++){s[t].fields.flatMap(e=>"group"===e.type?e.fields||[]:e).forEach(t=>{const a=I[t.name];t.required&&(""===a||null==a||Array.isArray(a)&&0===a.length)&&(e=!1)})}e&&M(n)()},[s,I,M,n]),$=t.useMemo(()=>s.map((e,t)=>({index:t,id:e.id,label:e.label||e.id,isActive:t===C,isCompleted:t<C,isDisabled:e.disabled||!1})),[s,C]),U=0===C,V=C===s.length-1,q=t.useMemo(()=>{if(!u)return null;if(v)return v(C,s.length,s);const t=h?e=>{S(e),g?.(e,s[e].id)}:void 0;switch(m){case"breadcrumb":return e.jsx(Rn,{steps:$,currentStepIndex:C,onStepClick:t});case"progressbar":return e.jsx(Ln,{steps:$,currentStepIndex:C});default:return e.jsx(In,{steps:$,currentStepIndex:C,onStepClick:t})}},[u,v,m,$,C,s,h,S,g]),B=t.useMemo(()=>{const t={isFirstStep:U,isLastStep:V,canGoNext:C<s.length-1,canGoPrevious:C>0,isLoading:d,onPrevious:F,onNext:D,onSubmit:z,previousButtonText:f,nextButtonText:x,submitButtonText:l};return y?y(t):e.jsx(Mn,{...t})},[U,V,C,s.length,d,F,D,z,f,x,l,y]),W=t=>{const a=(t.computedValue,I[t.name]),s=void 0!==a?a:"",r=R[t.name];switch(t.type){case"group":return e.jsxs("div",{className:"space-y-2",children:[t.label&&e.jsx(mt,{className:"text-sm font-medium",children:t.label}),e.jsx("div",{className:nt("grid gap-4",1===t.columns&&"grid-cols-1",2===t.columns&&"grid-cols-1 md:grid-cols-2",3===t.columns&&"grid-cols-1 md:grid-cols-3",4===t.columns&&"grid-cols-1 md:grid-cols-4",!t.columns&&"grid-cols-1"),children:t.fields?.map(e=>W(e))})]},t.name);case"number":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ct,{id:t.name,type:"number",value:s,onChange:e=>L(t.name,""===e.target.value?"":Number(e.target.value)),placeholder:t.placeholder,disabled:t.disabled||void 0!==t.computedValue,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"textarea":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Qt,{id:t.name,value:s,onChange:e=>L(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled,rows:t.rows||3,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"select":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ft,{value:s,onValueChange:e=>L(t.name,e),children:[e.jsx(Ut,{className:r?"border-destructive":"",children:e.jsx($t,{placeholder:t.placeholder||`Selecione ${t.label}`})}),e.jsx(Bt,{children:t.options?.map(t=>e.jsx(Ht,{value:String(t.value),children:t.label},t.value))})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"multiselect":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ts,{options:t.options||[],value:Array.isArray(s)?s:[],onChange:e=>L(t.name,e),placeholder:t.placeholder,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"color":case"color-picker":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(un,{value:s,onChange:e=>L(t.name,e),label:""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"icon-picker":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(fn,{value:s,onChange:e=>L(t.name,e),label:""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"user-select":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(bn,{value:s,onChange:e=>L(t.name,e),placeholder:t.placeholder,disabled:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name);case"custom":return t.render?e.jsxs("div",{className:"space-y-2",children:[t.label&&e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),t.render({value:s,onChange:e=>L(t.name,e),error:r,disabled:t.disabled}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name):null;default:return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(mt,{htmlFor:t.name,children:[t.label,t.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(ct,{id:t.name,type:t.type||"text",value:s,onChange:e=>L(t.name,e.target.value),placeholder:t.placeholder,disabled:t.disabled||void 0!==t.computedValue,className:r?"border-destructive":""}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r})]},t.name)}},H=s[C];return e.jsx(vt,{open:o,onOpenChange:i,children:e.jsxs(kt,{ref:A,className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Ct,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:e.jsx(Pt,{className:"text-white",children:a})}),q,e.jsx("div",{className:"space-y-4 py-4",children:H?.fields.map(e=>W(e))}),e.jsx("div",{className:"flex justify-between pt-4 border-t",children:B})]})})},exports.WizardProgressBar=Ln,exports.WizardStepper=In,exports.assets=Yl,exports.badgeVariants=Xt,exports.buildHierarchy=yd,exports.buttonGroupVariants=ri,exports.buttonVariants=ot,exports.calculateAspectRatio=Hd,exports.cn=nt,exports.createCrudPage=function(t){return({manager:a})=>{const{manager:s,config:r,onSave:n,onEdit:i,onToggleStatus:o}=t,l=a??s,d={entityName:r.entityName,entityNamePlural:r.entityNamePlural,filters:r.filters||[],columns:r.columns,cardFields:r.cardFields||[],enableBulkActions:r.enableBulkActions??!1,bulkActions:r.bulkActions||[],customActions:r.customActions,customRowActions:r.customRowActions,customListView:r.customListView,onEdit:i||r.onEdit};return e.jsx(En,{manager:l,config:d,formSections:r.formSections,onSave:n,onToggleStatus:o,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,t){const a=Cl({basePath:e,newPath:t.newPath,editPath:t.editPath});return{useCustomRouting:!0,onNew:a.onNew,onEdit:a.onEdit}},exports.createRoutingHandlers=Cl,exports.createService=Gs,exports.createSimpleSaveHandler=function(e,t,a){return s=>{if(s.id){const t=a(s);e.updateEntity(s.id,t)}else{const a=t(s);e.createEntity(a)}}},exports.createSimpleService=function(e){const t=Gs({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,s)=>sr({queryKey:e.tableName,service:{...t,getAll:async(e={})=>await t.getAll({...e})},entityName:e.entityName,additionalFilters:a,onSuccess:s})}},exports.debounce=(e,t)=>{let a;return(...s)=>{clearTimeout(a),a=setTimeout(()=>e(...s),t)}},exports.deriveEmailField=Us,exports.deriveNameField=$s,exports.deriveUsernameField=Vs,exports.detectVideoProvider=Wd,exports.emailService=md,exports.errorService=hs,exports.extractImageFileName=function(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"}},exports.extractVimeoId=Vd,exports.extractYouTubeId=$d,exports.filterAndPromoteOrphans=function(e,t){const a=e.map(e=>({...e})),s=new Set(a.filter(e=>!t.has(e.id_user)).map(e=>e.id_user));return a.forEach(e=>{if(e.id_leader&&s.has(e.id_leader)){let t=e.id_leader;for(;t&&s.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))},exports.flattenTree=Nd,exports.formatCurrency=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDate=cd,exports.formatDatetime=e=>{if(!e)return"";const t=i.parseISO(e);if(!i.isValid(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"})}`},exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=function(e,t,a={}){const s=[];return Object.keys(t).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const a=t[e],r={key:e,header:An(e),label:An(e),...Tn(e,a),sortable:!0,searchable:"string"==typeof a};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...a}},exports.getQualiexConfig=Ds,exports.getSupabaseClient=Ns,exports.handleExternalLink=rt,exports.i18n=st,exports.inputGroupAddonVariants=Ki,exports.inputGroupButtonVariants=Qi,exports.isDevEnvironment=Ms,exports.isImageUrl=function(e){const t=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>t.includes(e))},exports.logoSrc=Zl,exports.normalizeVideoUrl=function(e,t,a){switch(t||Wd(e)){case"youtube":return Ud(e,a);case"vimeo":return qd(e,a);default:return e}},exports.normalizeVimeoUrl=qd,exports.normalizeYouTubeUrl=Ud,exports.parseIframeSrc=Bd,exports.placeService=vd,exports.qualiexApi=_s,exports.resizeKeepingAspect=function(e,t,a,s){const r=Hd(e,t);return a&&!s?{width:a,height:Math.round(a/r)}:s&&!a?{width:Math.round(s*r),height:s}:{width:e,height:t}},exports.resolveFieldMappings=qs,exports.searchbarVariants=wo,exports.setupQualiexCore=function(e){return{queryClient:e.queryClient||new g.QueryClient({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}},exports.slugify=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),exports.smallLogoSrc=ed,exports.toast=oa,exports.toggleVariants=vl,exports.translationService=Tl,exports.trimTextFields=it,exports.useActiveModules=Kl,exports.useAllQualiexUsers=(e={})=>{const{alias:t}=ar(),{enabled:a=!0}=e;return g.useQuery({queryKey:["qualiex-all-users",t],queryFn:async()=>t?_s.getAllUsers(t):[],enabled:a&&!!t,staleTime:3e5,retry:2})},exports.useAuth=ar,exports.useBaseForm=dn,exports.useCreateLeaderMutation=function(){const e="common",{alias:t}=ar(),a=g.useQueryClient(),s=Ns();return g.useMutation({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 s.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 Ed(s,t,e,a.id_user,a.id_leader);const{data:r,error:n}=await s.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 r},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",t]}),o.toast.success("Líder adicionado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao adicionar líder")}})},exports.useCreateMultipleLeadersMutation=kd,exports.useCreateSingleLeaderMutation=wd,exports.useCrud=sr,exports.useDebounce=Bl,exports.useFormField=_t,exports.useI18nFormatters=()=>{const{locale:e,timezone:t,datetimeFormat:a}=Ll();return{formatDatetime:e=>((e,t="dd/MM/yyyy HH:mm")=>{if(!e)return"";const a=i.parseISO(e);return i.isValid(a)?i.format(a,t):"Invalid date"})(e,a,t),formatDate:t=>cd(t,e),locale:e,timezone:t,datetimeFormat:a}},exports.useLeadershipApi=jd,exports.useLocale=Ll,exports.useMediaUpload=zd,exports.useNavigation=Vl,exports.useOpenAIChat=pd,exports.usePageMetadata=function(e){const{setMetadata:a,clearMetadata:s}=Vn();t.useEffect(()=>(a(e),()=>s()),[e.title,e.subtitle,a,s])},exports.usePageMetadataContext=Vn,exports.usePageTitle=ql,exports.usePermissionQuery=Hl,exports.useQualiexUsers=gn,exports.useRemoveLeaderMutation=Sd,exports.useRouteBreadcrumbs=function(){const e=b.useLocation();return(()=>{const t=e.pathname.split("/").filter(Boolean),a=[{label:"Exemplos",href:"/"}];let s="";return t.forEach((e,r)=>{s+=`/${e}`;const n=r===t.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");a.push({label:i,href:n?void 0:s,isCurrentPage:n})}),a})()},exports.useSidebar=qo,exports.useSidebarResize=ad,exports.useSyncSubordinatesMutation=Pd,exports.useToast=la,exports.useTranslation=Ya,exports.useUpdateLeaderMutation=Cd;