forlogic-core 1.8.16 → 1.9.0
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/README.md +33 -0
- package/dist/README.md +33 -0
- package/dist/index.esm.js +1 -10
- package/dist/index.js +1 -10
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react"),t=require("@radix-ui/react-slot"),n=require("class-variance-authority"),r=require("clsx"),a=require("tailwind-merge"),s=require("date-fns"),i=require("sonner"),o=require("lucide-react"),l=require("@radix-ui/react-label"),c=require("@radix-ui/react-dialog"),u=require("react-hook-form"),d=require("@radix-ui/react-select"),m=require("@radix-ui/react-checkbox"),p=require("@radix-ui/react-toast"),f=require("@radix-ui/react-popover"),h=require("@supabase/supabase-js"),g=require("@tanstack/react-query"),x=require("react-router-dom"),y=require("@radix-ui/react-alert-dialog"),v=require("@radix-ui/react-dropdown-menu"),b=require("@radix-ui/react-scroll-area"),w=require("@radix-ui/react-accordion"),N=require("@radix-ui/react-aspect-ratio"),j=require("@radix-ui/react-avatar"),k=require("react-day-picker"),C=require("@radix-ui/react-collapsible"),S=require("@radix-ui/react-progress"),E=require("@radix-ui/react-radio-group"),I=require("@radix-ui/react-separator"),T=require("@radix-ui/react-tooltip"),A=require("@radix-ui/react-slider"),P=require("next-themes");require("react-dom");var _=require("@radix-ui/react-tabs"),D=require("@radix-ui/react-toggle"),F=require("@radix-ui/react-toggle-group"),R=require("zod"),L=require("@hookform/resolvers");function M(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var O=M(e),z=M(l),U=M(c),B=M(d),$=M(m),q=M(p),V=M(f),H=M(y),W=M(v),Q=M(b),K=M(w),X=M(N),Y=M(j),G=M(C),J=M(S),Z=M(E),ee=M(I),te=M(T),ne=M(A),re=M(_),ae=M(D),se=M(F);function ie(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oe,le={exports:{}},ce={};var ue,de,me={};
|
|
2
|
-
/**
|
|
3
|
-
* @license React
|
|
4
|
-
* react-jsx-runtime.development.js
|
|
5
|
-
*
|
|
6
|
-
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
7
|
-
*
|
|
8
|
-
* This source code is licensed under the MIT license found in the
|
|
9
|
-
* LICENSE file in the root directory of this source tree.
|
|
10
|
-
*/function pe(){return ue||(ue=1,"production"!==process.env.NODE_ENV&&function(){var t=e,n=Symbol.for("react.element"),r=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),h=Symbol.iterator;var g=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function x(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];!function(e,t,n){var r=g.ReactDebugCurrentFrame,a=r.getStackAddendum();""!==a&&(t+="%s",n=n.concat([a]));var s=n.map(function(e){return String(e)});s.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,s)}("error",e,n)}var y;function v(e){return e.displayName||"Context"}function b(e){if(null==e)return null;if("number"==typeof e.tag&&x("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),"function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case a:return"Fragment";case r:return"Portal";case i:return"Profiler";case s:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case l:return v(e)+".Consumer";case o:return v(e._context)+".Provider";case c:return function(e,t,n){var r=e.displayName;if(r)return r;var a=t.displayName||t.name||"";return""!==a?n+"("+a+")":n}(e,e.render,"ForwardRef");case m:var t=e.displayName||null;return null!==t?t:b(e.type)||"Memo";case p:var n=e,f=n._payload,h=n._init;try{return b(h(f))}catch(g){return null}}return null}y=Symbol.for("react.module.reference");var w,N,j,k,C,S,E,I=Object.assign,T=0;function A(){}A.__reactDisabledLog=!0;var P,_=g.ReactCurrentDispatcher;function D(e,t,n){if(void 0===P)try{throw Error()}catch(a){var r=a.stack.trim().match(/\n( *(at )?)/);P=r&&r[1]||""}return"\n"+P+e}var F,R=!1,L="function"==typeof WeakMap?WeakMap:Map;function M(e,t){if(!e||R)return"";var n,r=F.get(e);if(void 0!==r)return r;R=!0;var a,s=Error.prepareStackTrace;Error.prepareStackTrace=void 0,a=_.current,_.current=null,function(){if(0===T){w=console.log,N=console.info,j=console.warn,k=console.error,C=console.group,S=console.groupCollapsed,E=console.groupEnd;var e={configurable:!0,enumerable:!0,value:A,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}T++}();try{if(t){var i=function(){throw Error()};if(Object.defineProperty(i.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(i,[])}catch(f){n=f}Reflect.construct(e,[],i)}else{try{i.call()}catch(f){n=f}e.call(i.prototype)}}else{try{throw Error()}catch(f){n=f}e()}}catch(h){if(h&&n&&"string"==typeof h.stack){for(var o=h.stack.split("\n"),l=n.stack.split("\n"),c=o.length-1,u=l.length-1;c>=1&&u>=0&&o[c]!==l[u];)u--;for(;c>=1&&u>=0;c--,u--)if(o[c]!==l[u]){if(1!==c||1!==u)do{if(c--,--u<0||o[c]!==l[u]){var d="\n"+o[c].replace(" at new "," at ");return e.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",e.displayName)),"function"==typeof e&&F.set(e,d),d}}while(c>=1&&u>=0);break}}}finally{R=!1,_.current=a,function(){if(0===--T){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:I({},e,{value:w}),info:I({},e,{value:N}),warn:I({},e,{value:j}),error:I({},e,{value:k}),group:I({},e,{value:C}),groupCollapsed:I({},e,{value:S}),groupEnd:I({},e,{value:E})})}T<0&&x("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}(),Error.prepareStackTrace=s}var m=e?e.displayName||e.name:"",p=m?D(m):"";return"function"==typeof e&&F.set(e,p),p}function O(e,t,n){if(null==e)return"";if("function"==typeof e)return M(e,!(!(r=e.prototype)||!r.isReactComponent));var r;if("string"==typeof e)return D(e);switch(e){case u:return D("Suspense");case d:return D("SuspenseList")}if("object"==typeof e)switch(e.$$typeof){case c:return M(e.render,!1);case m:return O(e.type,t,n);case p:var a=e,s=a._payload,i=a._init;try{return O(i(s),t,n)}catch(o){}}return""}F=new L;var z=Object.prototype.hasOwnProperty,U={},B=g.ReactDebugCurrentFrame;function $(e){if(e){var t=e._owner,n=O(e.type,e._source,t?t.type:null);B.setExtraStackFrame(n)}else B.setExtraStackFrame(null)}var q=Array.isArray;function V(e){return q(e)}function H(e){return""+e}function W(e){if(function(e){try{return H(e),!1}catch(t){return!0}}(e))return x("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",function(e){return"function"==typeof Symbol&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object"}(e)),H(e)}var Q,K,X=g.ReactCurrentOwner,Y={key:!0,ref:!0,__self:!0,__source:!0};function G(e,t,r,a,s){var i,o={},l=null,c=null;for(i in void 0!==r&&(W(r),l=""+r),function(e){if(z.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return void 0!==e.key}(t)&&(W(t.key),l=""+t.key),function(e){if(z.call(e,"ref")){var t=Object.getOwnPropertyDescriptor(e,"ref").get;if(t&&t.isReactWarning)return!1}return void 0!==e.ref}(t)&&(c=t.ref,function(e){"string"==typeof e.ref&&X.current}(t)),t)z.call(t,i)&&!Y.hasOwnProperty(i)&&(o[i]=t[i]);if(e&&e.defaultProps){var u=e.defaultProps;for(i in u)void 0===o[i]&&(o[i]=u[i])}if(l||c){var d="function"==typeof e?e.displayName||e.name||"Unknown":e;l&&function(e,t){var n=function(){Q||(Q=!0,x("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}(o,d),c&&function(e,t){var n=function(){K||(K=!0,x("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",t))};n.isReactWarning=!0,Object.defineProperty(e,"ref",{get:n,configurable:!0})}(o,d)}return function(e,t,r,a,s,i,o){var l={$$typeof:n,type:e,key:t,ref:r,props:o,_owner:i,_store:{}};return Object.defineProperty(l._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(l,"_self",{configurable:!1,enumerable:!1,writable:!1,value:a}),Object.defineProperty(l,"_source",{configurable:!1,enumerable:!1,writable:!1,value:s}),Object.freeze&&(Object.freeze(l.props),Object.freeze(l)),l}(e,l,c,s,a,X.current,o)}var J,Z=g.ReactCurrentOwner,ee=g.ReactDebugCurrentFrame;function te(e){if(e){var t=e._owner,n=O(e.type,e._source,t?t.type:null);ee.setExtraStackFrame(n)}else ee.setExtraStackFrame(null)}function ne(e){return"object"==typeof e&&null!==e&&e.$$typeof===n}function re(){if(Z.current){var e=b(Z.current.type);if(e)return"\n\nCheck the render method of `"+e+"`."}return""}J=!1;var ae={};function se(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var n=function(e){var t=re();if(!t){var n="string"==typeof e?e:e.displayName||e.name;n&&(t="\n\nCheck the top-level render call using <"+n+">.")}return t}(t);if(!ae[n]){ae[n]=!0;var r="";e&&e._owner&&e._owner!==Z.current&&(r=" It was passed a child from "+b(e._owner.type)+"."),te(e),x('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',n,r),te(null)}}}function ie(e,t){if("object"==typeof e)if(V(e))for(var n=0;n<e.length;n++){var r=e[n];ne(r)&&se(r,t)}else if(ne(e))e._store&&(e._store.validated=!0);else if(e){var a=function(e){if(null===e||"object"!=typeof e)return null;var t=h&&e[h]||e["@@iterator"];return"function"==typeof t?t:null}(e);if("function"==typeof a&&a!==e.entries)for(var s,i=a.call(e);!(s=i.next()).done;)ne(s.value)&&se(s.value,t)}}function oe(e){var t,n=e.type;if(null!=n&&"string"!=typeof n){if("function"==typeof n)t=n.propTypes;else{if("object"!=typeof n||n.$$typeof!==c&&n.$$typeof!==m)return;t=n.propTypes}if(t){var r=b(n);!function(e,t,n,r,a){var s=Function.call.bind(z);for(var i in e)if(s(e,i)){var o=void 0;try{if("function"!=typeof e[i]){var l=Error((r||"React class")+": "+n+" type `"+i+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[i]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw l.name="Invariant Violation",l}o=e[i](t,i,r,n,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(c){o=c}!o||o instanceof Error||($(a),x("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",r||"React class",n,i,typeof o),$(null)),o instanceof Error&&!(o.message in U)&&(U[o.message]=!0,$(a),x("Failed %s type: %s",n,o.message),$(null))}}(t,e.props,"prop",r,e)}else if(void 0!==n.PropTypes&&!J){J=!0,x("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b(n)||"Unknown")}"function"!=typeof n.getDefaultProps||n.getDefaultProps.isReactClassApproved||x("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}var le={};function ce(e,t,r,h,g,v){var w=function(e){return"string"==typeof e||"function"==typeof e||e===a||e===i||e===s||e===u||e===d||e===f||"object"==typeof e&&null!==e&&(e.$$typeof===p||e.$$typeof===m||e.$$typeof===o||e.$$typeof===l||e.$$typeof===c||e.$$typeof===y||void 0!==e.getModuleId)}(e);if(!w){var N="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(N+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var j;N+=re(),null===e?j="null":V(e)?j="array":void 0!==e&&e.$$typeof===n?(j="<"+(b(e.type)||"Unknown")+" />",N=" Did you accidentally export a JSX literal instead of a component?"):j=typeof e,x("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",j,N)}var k=G(e,t,r,g,v);if(null==k)return k;if(w){var C=t.children;if(void 0!==C)if(h)if(V(C)){for(var S=0;S<C.length;S++)ie(C[S],e);Object.freeze&&Object.freeze(C)}else x("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ie(C,e)}if(z.call(t,"key")){var E=b(e),I=Object.keys(t).filter(function(e){return"key"!==e}),T=I.length>0?"{key: someKey, "+I.join(": ..., ")+": ...}":"{key: someKey}";if(!le[E+T])x('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />',T,E,I.length>0?"{"+I.join(": ..., ")+": ...}":"{}",E),le[E+T]=!0}return e===a?function(e){for(var t=Object.keys(e.props),n=0;n<t.length;n++){var r=t[n];if("children"!==r&&"key"!==r){te(e),x("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",r),te(null);break}}null!==e.ref&&(te(e),x("Invalid attribute `ref` supplied to `React.Fragment`."),te(null))}(k):oe(k),k}var ue=function(e,t,n){return ce(e,t,n,!1)},de=function(e,t,n){return ce(e,t,n,!0)};me.Fragment=a,me.jsx=ue,me.jsxs=de}()),me}var fe=(de||(de=1,"production"===process.env.NODE_ENV?le.exports=function(){if(oe)return ce;oe=1;var t=e,n=Symbol.for("react.element"),r=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,s=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function o(e,t,r){var o,l={},c=null,u=null;for(o in void 0!==r&&(c=""+r),void 0!==t.key&&(c=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,o)&&!i.hasOwnProperty(o)&&(l[o]=t[o]);if(e&&e.defaultProps)for(o in t=e.defaultProps)void 0===l[o]&&(l[o]=t[o]);return{$$typeof:n,type:e,key:c,ref:u,props:l,_owner:s.current}}return ce.Fragment=r,ce.jsx=o,ce.jsxs=o,ce}():le.exports=pe()),le.exports);function he(e,t){t?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{i.toast.info("Link copiado para a área de transferência")})}function ge(...e){return a.twMerge(r.clsx(e))}const xe=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(xe);if("object"==typeof e&&e.constructor===Object){const t={};for(const[n,r]of Object.entries(e))t[n]=xe(r);return t}return e},ye=n.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium 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 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",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:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6"}},defaultVariants:{variant:"default",size:"default"}}),ve=O.forwardRef(({className:e,variant:n,size:r,asChild:a=!1,...s},i)=>{const o=a?t.Slot:"button";return fe.jsx(o,{className:ge(ye({variant:n,size:r,className:e})),ref:i,...s})});ve.displayName="Button";const be=e.forwardRef(({variant:e="default",className:t,children:n,...r},a)=>fe.jsx(ve,{ref:a,variant:"action",size:"sm",className:ge("h-7 px-2 text-xs",t),...r,children:n||fe.jsx(o.EllipsisVertical,{size:12})}));be.displayName="ActionButton";const we=O.forwardRef(({className:e,type:t,...n},r)=>fe.jsx("input",{type:t,className:ge("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",e),ref:r,...n}));we.displayName="Input";const Ne=n.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),je=O.forwardRef(({className:e,...t},n)=>fe.jsx(z.Root,{ref:n,className:ge(Ne(),e),...t}));je.displayName=z.Root.displayName;const ke=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));ke.displayName="Card";const Ce=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("flex flex-col space-y-1.5 p-6",e),...t}));Ce.displayName="CardHeader";const Se=O.forwardRef(({className:e,...t},n)=>fe.jsx("h3",{ref:n,className:ge("text-2xl font-semibold leading-none tracking-tight",e),...t}));Se.displayName="CardTitle";const Ee=O.forwardRef(({className:e,...t},n)=>fe.jsx("p",{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));Ee.displayName="CardDescription";const Ie=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("p-6 pt-0",e),...t}));Ie.displayName="CardContent";const Te=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("flex items-center p-6 pt-0",e),...t}));Te.displayName="CardFooter";const Ae=U.Root,Pe=U.Trigger,_e=U.Portal,De=U.Close,Fe=O.forwardRef(({className:e,...t},n)=>fe.jsx(U.Overlay,{ref:n,className:ge("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",e),...t}));Fe.displayName=U.Overlay.displayName;const Re=O.forwardRef(({className:e,children:t,...n},r)=>fe.jsxs(_e,{children:[fe.jsx(Fe,{}),fe.jsxs(U.Content,{ref:r,className:ge("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 bg-background p-6 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%] rounded-lg max-h-[90vh] overflow-auto",e),...n,children:[t,fe.jsxs(U.Close,{className:"absolute right-4 top-4 z-10 rounded-sm text-white opacity-70 ring-offset-background transition-opacity hover:opacity-100 hover:text-white focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[fe.jsx(o.X,{className:"h-4 w-4"}),fe.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Re.displayName=U.Content.displayName;const Le=({className:e,...t})=>fe.jsx("div",{className:ge("flex flex-col space-y-1.5 text-center sm:text-left bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-3 rounded-t-lg",e),...t});Le.displayName="DialogHeader";const Me=({className:e,...t})=>fe.jsx("div",{className:ge("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Me.displayName="DialogFooter";const Oe=O.forwardRef(({className:e,...t},n)=>fe.jsx(U.Title,{ref:n,className:ge("text-lg font-semibold leading-none tracking-tight",e),...t}));Oe.displayName=U.Title.displayName;const ze=O.forwardRef(({className:e,...t},n)=>fe.jsx(U.Description,{ref:n,className:ge("text-sm text-white",e),...t}));ze.displayName=U.Description.displayName;const Ue=u.FormProvider,Be=O.createContext({}),$e=()=>{const e=O.useContext(Be),t=O.useContext(qe),{getFieldState:n,formState:r}=u.useFormContext(),a=n(e.name,r);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:s}=t;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...a}},qe=O.createContext({}),Ve=O.forwardRef(({className:e,...t},n)=>{const r=O.useId();return fe.jsx(qe.Provider,{value:{id:r},children:fe.jsx("div",{ref:n,className:ge("space-y-2",e),...t})})});Ve.displayName="FormItem";const He=O.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:a}=$e();return fe.jsx(je,{ref:n,className:ge(r&&"text-destructive",e),htmlFor:a,...t})});He.displayName="FormLabel";const We=O.forwardRef(({...e},n)=>{const{error:r,formItemId:a,formDescriptionId:s,formMessageId:i}=$e();return fe.jsx(t.Slot,{ref:n,id:a,"aria-describedby":r?`${s} ${i}`:`${s}`,"aria-invalid":!!r,...e})});We.displayName="FormControl";const Qe=O.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=$e();return fe.jsx("p",{ref:n,id:r,className:ge("text-sm text-muted-foreground",e),...t})});Qe.displayName="FormDescription";const Ke=O.forwardRef(({className:e,children:t,...n},r)=>{const{error:a,formMessageId:s}=$e(),i=a?String(a?.message):t;return i?fe.jsx("p",{ref:r,id:s,className:ge("text-sm font-medium text-destructive",e),...n,children:i}):null});Ke.displayName="FormMessage";const Xe=B.Root,Ye=B.Group,Ge=B.Value,Je=O.forwardRef(({className:e,children:t,...n},r)=>fe.jsxs(B.Trigger,{ref:r,className:ge("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",e),...n,children:[t,fe.jsx(B.Icon,{asChild:!0,children:fe.jsx(o.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Je.displayName=B.Trigger.displayName;const Ze=O.forwardRef(({className:e,...t},n)=>fe.jsx(B.ScrollUpButton,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:fe.jsx(o.ChevronUp,{className:"h-4 w-4"})}));Ze.displayName=B.ScrollUpButton.displayName;const et=O.forwardRef(({className:e,...t},n)=>fe.jsx(B.ScrollDownButton,{ref:n,className:ge("flex cursor-default items-center justify-center py-1",e),...t,children:fe.jsx(o.ChevronDown,{className:"h-4 w-4"})}));et.displayName=B.ScrollDownButton.displayName;const tt=O.forwardRef(({className:e,children:t,position:n="popper",container:r,collisionBoundary:a,...s},i)=>fe.jsx(B.Portal,{container:r,children:fe.jsxs(B.Content,{ref:i,className:ge("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,collisionBoundary:a,...s,children:[fe.jsx(Ze,{}),fe.jsx(B.Viewport,{className:ge("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),fe.jsx(et,{})]})}));tt.displayName=B.Content.displayName;const nt=O.forwardRef(({className:e,...t},n)=>fe.jsx(B.Label,{ref:n,className:ge("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));nt.displayName=B.Label.displayName;const rt=O.forwardRef(({className:e,children:t,...n},r)=>fe.jsxs(B.Item,{ref:r,className:ge("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",e),...n,children:[fe.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:fe.jsx(B.ItemIndicator,{children:fe.jsx(o.Check,{className:"h-4 w-4"})})}),fe.jsx(B.ItemText,{children:t})]}));rt.displayName=B.Item.displayName;const at=O.forwardRef(({className:e,...t},n)=>fe.jsx(B.Separator,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));at.displayName=B.Separator.displayName;const st=O.forwardRef(({className:e,...t},n)=>fe.jsx($.Root,{ref:n,className:ge("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",e),...t,children:fe.jsx($.Indicator,{className:ge("flex items-center justify-center text-current"),children:fe.jsx(o.Check,{className:"h-4 w-4"})})}));st.displayName=$.Root.displayName;const it=O.forwardRef(({className:e,...t},n)=>fe.jsx("textarea",{className:ge("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",e),ref:n,...t}));it.displayName="Textarea";const ot=n.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"}}),lt=O.forwardRef(({className:e,variant:t,...n},r)=>fe.jsx("div",{ref:r,className:ge(ot({variant:t}),e),...n}));lt.displayName="Badge";const ct={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ut({size:e="md",className:t}){return fe.jsx(o.Loader2,{className:ge("animate-spin text-muted-foreground",ct[e],t)})}let dt=0;const mt=new Map,pt=e=>{if(mt.has(e))return;const t=setTimeout(()=>{mt.delete(e),xt({type:"REMOVE_TOAST",toastId:e})},1e6);mt.set(e,t)},ft=(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:n}=t;return n?pt(n):e.toasts.forEach(e=>{pt(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===n||void 0===n?{...e,open:!1}:e)}}case"REMOVE_TOAST":return void 0===t.toastId?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},ht=[];let gt={toasts:[]};function xt(e){gt=ft(gt,e),ht.forEach(e=>{e(gt)})}function yt({...e}){const t=(dt=(dt+1)%Number.MAX_SAFE_INTEGER,dt.toString()),n=()=>xt({type:"DISMISS_TOAST",toastId:t});return xt({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||n()}}}),{id:t,dismiss:n,update:e=>xt({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function vt(){const[e,t]=O.useState(gt);return O.useEffect(()=>(ht.push(t),()=>{const e=ht.indexOf(t);e>-1&&ht.splice(e,1)}),[e]),{...e,toast:yt,dismiss:e=>xt({type:"DISMISS_TOAST",toastId:e})}}const bt=q.Provider,wt=O.forwardRef(({className:e,...t},n)=>fe.jsx(q.Viewport,{ref:n,className:ge("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",e),...t}));wt.displayName=q.Viewport.displayName;const Nt=n.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"}}),jt=O.forwardRef(({className:e,variant:t,...n},r)=>fe.jsx(q.Root,{ref:r,className:ge(Nt({variant:t}),e),...n}));jt.displayName=q.Root.displayName;const kt=O.forwardRef(({className:e,...t},n)=>fe.jsx(q.Action,{ref:n,className:ge("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",e),...t}));kt.displayName=q.Action.displayName;const Ct=O.forwardRef(({className:e,...t},n)=>fe.jsx(q.Close,{ref:n,className:ge("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",e),"toast-close":"",...t,children:fe.jsx(o.X,{className:"h-4 w-4"})}));Ct.displayName=q.Close.displayName;const St=O.forwardRef(({className:e,...t},n)=>fe.jsx(q.Title,{ref:n,className:ge("text-sm font-semibold",e),...t}));St.displayName=q.Title.displayName;const Et=O.forwardRef(({className:e,...t},n)=>fe.jsx(q.Description,{ref:n,className:ge("text-sm opacity-90",e),...t}));Et.displayName=q.Description.displayName;const It=V.Root,Tt=V.Trigger,At=O.forwardRef(({className:e,align:t="center",sideOffset:n=4,container:r,...a},s)=>fe.jsx(V.Portal,{container:r,children:fe.jsx(V.Content,{ref:s,align:t,sideOffset:n,className:ge("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",e),...a})}));At.displayName=V.Content.displayName;const Pt=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));Pt.displayName="Command";const _t=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:fe.jsx("input",{ref:n,className:ge("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",e),...t})}));_t.displayName="CommandInput";const Dt=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));Dt.displayName="CommandList";const Ft=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("py-6 text-center text-sm text-muted-foreground",e),...t}));Ft.displayName="CommandEmpty";const Rt=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("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",e),...t}));Rt.displayName="CommandGroup";const Lt=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("-mx-1 h-px bg-border",e),...t}));Lt.displayName="CommandSeparator";const Mt=O.forwardRef(({className:e,disabled:t,onSelect:n,value:r,...a},s)=>fe.jsx("div",{ref:s,className:ge("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",e),"data-disabled":t,onClick:()=>!t&&n?.(r||""),...a}));Mt.displayName="CommandItem";const Ot=({className:e,...t})=>fe.jsx("span",{className:ge("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});function zt({className:e,...t}){return fe.jsx("div",{className:ge("animate-pulse rounded-md bg-muted",e),...t})}Ot.displayName="CommandShortcut";const Ut=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Bt({multiple:t,options:n,value:r,onChange:a,getOptionValue:s,getOptionLabel:i,placeholder:l,label:c,icon:u,emptyMessage:d,searchPlaceholder:m,disabled:p,required:f,className:h,sortOptions:g,maxDisplayedBadges:x,popoverContainer:y,onOpen:v,onClose:b}){const[w,N]=e.useState(!1),[j,k]=e.useState(""),C=e.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),S=e.useMemo(()=>{if(!y)return;let e=y,t=0;try{for(;e&&t<3;){const n=window.getComputedStyle(e),r=n.overflowY||n.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,t++}}catch{}return e??void 0},[y]),E=e.useMemo(()=>{const e=n.map(e=>({original:e,value:s(e),label:i(e)}));return g?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[n,s,i,g]),I=e.useMemo(()=>{if(!j)return E;const e=Ut(j);return E.filter(t=>Ut(t.label).includes(e))},[E,j]),T=e.useMemo(()=>E.filter(e=>C.includes(e.value)),[E,C]),A=(e,n)=>{n.preventDefault(),n.stopPropagation(),a&&a(t?C.filter(t=>t!==e):"")},P=x?T.slice(0,x):T,_=x&&T.length>x?T.length-x:0;return fe.jsxs("div",{className:ge("space-y-2",h),children:[c&&fe.jsxs(je,{children:[c,f&&fe.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),fe.jsxs(It,{open:w,onOpenChange:e=>{N(e),e?v?.():(k(""),b?.())},modal:!1,children:[fe.jsx(Tt,{asChild:!0,children:fe.jsxs(ve,{variant:"outline",role:"combobox","aria-expanded":w,disabled:p,className:ge("w-full justify-between min-h-10 h-auto",0===T.length&&"text-muted-foreground"),children:[0===T.length?fe.jsxs("span",{className:"flex items-center gap-2",children:[u&&fe.jsx(u,{className:"h-4 w-4"}),l]}):t?fe.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[P.map(e=>fe.jsxs(lt,{variant:"secondary",className:"gap-1 pr-1",children:[e.label,fe.jsx("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:t=>{"Enter"===t.key&&A(e.value,t)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:t=>A(e.value,t),children:fe.jsx(o.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),_>0&&fe.jsxs(lt,{variant:"outline",className:"gap-1",children:["+",_]})]}):fe.jsxs("span",{className:"flex items-center gap-2",children:[u&&fe.jsx(u,{className:"h-4 w-4"}),T[0]?.label]}),fe.jsx(o.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),fe.jsx(At,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:S,collisionBoundary:S,children:fe.jsxs(Pt,{children:[fe.jsx(_t,{placeholder:m,value:j,onChange:e=>k(e.target.value)}),fe.jsx(Dt,{children:0===n.length?fe.jsx(Ft,{children:d}):0===I.length?fe.jsx(Ft,{children:"Nenhum item encontrado."}):fe.jsx(Rt,{children:I.map(e=>fe.jsxs(Mt,{value:e.value,onSelect:()=>(e=>{if(a)if(t){const t=C.includes(e)?C.filter(t=>t!==e):[...C,e];a(t)}else a(e),N(!1)})(e.value),className:"cursor-pointer",children:[fe.jsx(o.Check,{className:ge("mr-2 h-4 w-4",C.includes(e.value)?"opacity-100":"opacity-0")}),e.label]},e.value))})})]})})]})]})}function $t({multiple:e=!0,options:t=[],value:n,onChange:r,getOptionValue:a=e=>e.value,getOptionLabel:s=e=>e.label,placeholder:i="Selecione itens...",label:l,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:d="Buscar...",disabled:m=!1,required:p=!1,isLoading:f=!1,error:h,className:g,sortOptions:x=!0,maxDisplayedBadges:y,popoverContainer:v,onOpen:b,onClose:w}){if(f)return fe.jsxs("div",{className:ge("space-y-2",g),children:[l&&fe.jsxs(je,{children:[l,p&&fe.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),fe.jsx(zt,{className:"h-10 w-full"})]});const N="string"==typeof h?h:h?"Erro ao carregar dados":void 0;return N?fe.jsxs("div",{className:ge("space-y-2",g),children:[l&&fe.jsxs(je,{children:[l,p&&fe.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),fe.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[fe.jsx(o.AlertCircle,{className:"h-4 w-4"}),fe.jsx("span",{className:"text-sm",children:N})]})]}):fe.jsx(Bt,{multiple:e,options:t,value:n||(e?[]:""),onChange:r,getOptionValue:a,getOptionLabel:s,placeholder:i,label:l,icon:c,emptyMessage:u,searchPlaceholder:d,disabled:m,required:p,className:g,sortOptions:x,maxDisplayedBadges:y,popoverContainer:v,onOpen:b,onClose:w})}var qt=Object.defineProperty;class Vt{static normalizeBase64Url(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");const n=(4-t.length%4)%4;return t+="=".repeat(n),t}static parseJwtPayload(e){try{const a=e.split(".");if(3!==a.length)return null;const s=a[1];s.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(s),t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);const r=new TextDecoder("utf-8").decode(n);return JSON.parse(r)}catch(t){try{const e=this.normalizeBase64Url(s),t=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(t)}catch(n){try{const e=this.normalizeBase64Url(s),t=atob(e);return JSON.parse(t)}catch(r){throw r}}}}catch(a){return null}}static validateTokens(e,t){const n=[],r=[];try{t.split(".")[1],e.split(".")[1];const a=this.parseJwtPayload(t),s=this.parseJwtPayload(e);if(!a){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:n,errors:r}}let i=!0;if(!s){const e="Access token decode falhou - será tentado novamente nas chamadas de API";n.push(e),i=!1}const o=Math.floor(Date.now()/1e3);if(s?.exp&&s.exp<o){const e="Access token expirado - pode precisar de refresh";n.push(e),i=!1}if(a.exp&&a.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:i,warnings:n,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:n,errors:r}}catch(a){const e=`Erro na validação de tokens: ${a}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:n,errors:r}}}static isTokenExpired(e){const t=this.parseJwtPayload(e);return!t||!t.exp||1e3*t.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}((e,t,n)=>{t in e?qt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(Vt,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const Ht="qualiex_access_token",Wt="qualiex_id_token",Qt="supabase_token",Kt="oauth_state",Xt="oauth_nonce",Yt="selected_alias",Gt="manual_logout",Jt={setAccessToken:e=>localStorage.setItem(Ht,e),getAccessToken:()=>localStorage.getItem(Ht),setIdToken:e=>localStorage.setItem(Wt,e),getIdToken:()=>localStorage.getItem(Wt),getSupabaseToken:()=>localStorage.getItem(Qt),setOAuthState:e=>sessionStorage.setItem(Kt,e),getOAuthState:()=>sessionStorage.getItem(Kt),clearOAuthState:()=>sessionStorage.removeItem(Kt),setOAuthNonce:e=>sessionStorage.setItem(Xt,e),getOAuthNonce:()=>sessionStorage.getItem(Xt),clearOAuthNonce:()=>sessionStorage.removeItem(Xt),setSelectedAlias:e=>localStorage.setItem(Yt,e),getSelectedAlias:()=>localStorage.getItem(Yt),clearSelectedAlias:()=>localStorage.removeItem(Yt),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Jt.getAccessToken()||!Jt.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(Qt,e),Jt._clearValidationCache()},areAllTokensValid:()=>{const e=Jt.getAccessToken(),t=Jt.getIdToken();if(!e||!t)return!1;try{const n=Vt.validateTokens(e,t);return!!n.idTokenValid&&n.idTokenValid}catch(n){return!1}},clearExpiredTokens:()=>{let e=!1;const t=Jt.getAccessToken(),n=Jt.getIdToken(),r=Jt.getSupabaseToken();return t&&Jt.isTokenExpired(t)&&(localStorage.removeItem(Ht),e=!0),n&&Jt.isTokenExpired(n)&&(localStorage.removeItem(Wt),e=!0),r&&Jt.isTokenExpired(r)&&(localStorage.removeItem(Qt),e=!0),e},clearAll:()=>{localStorage.removeItem(Ht),localStorage.removeItem(Wt),localStorage.removeItem(Qt),localStorage.removeItem(Yt),localStorage.removeItem(Gt),sessionStorage.removeItem(Kt),sessionStorage.removeItem(Xt)},setManualLogout:()=>localStorage.setItem(Gt,"true"),isManualLogout:()=>"true"===localStorage.getItem(Gt),clearManualLogout:()=>localStorage.removeItem(Gt),isTokenExpired:e=>{try{return Vt.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Jt._validationCache.isValid=!1,Jt._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Jt.getSupabaseToken();if(!e)return!1;if(Jt.isTokenExpired(e))return Jt._clearValidationCache(),Jt._handleExpiredToken(),!1;const t=Date.now();return t-Jt._validationCache.timestamp<Jt._validationCache.cacheValidityMs?Jt._validationCache.isValid:(Jt._validationCache.isValid=!0,Jt._validationCache.timestamp=t,!0)},getValidSupabaseToken:()=>Jt.isSupabaseTokenValid()?Jt.getSupabaseToken():null,_handleExpiredToken:()=>{Jt.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Jt.isSupabaseTokenValid())return null;const e=Jt.getSupabaseToken();if(!e)return null;try{const t=Vt.parseJwtPayload(e);if(!t)return null;const n=t.alias||t.default||t.user_alias,r=t.place_id||null,a=t.place_name||null;let s=t.company_id;if(!s&&n)for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=t[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===n){s=e[7];break}}}return{alias:n,companyId:s,placeId:r,placeName:a,payload:t}}catch(t){return Jt._handleExpiredToken(),null}},getCompanyId:e=>{const t=Jt.getAccessToken();if(t)try{const n=Vt.parseJwtPayload(t);if(n)for(const t in n)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=n[t];if(r&&"string"==typeof r){const t=r.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(a){}const n=Jt.extractTokenData();if(n?.companyId)return n.companyId;const r=Jt.getIdToken();if(r)try{const t=Vt.parseJwtPayload(r);if(t)for(const n in t)if(n.startsWith("co")&&/^co\d+$/.test(n)){const r=t[n];if(r&&"string"==typeof r){const t=r.split(";");if(e&&t.length>7&&t[0]===e)return t[7];if(!e&&t.length>7)return t[7]}}}catch(a){}return null},getCurrentCompanyId:()=>{const e=Jt.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Jt.getIdToken();if(!e)return[];try{const t=Vt.parseJwtPayload(e);if(!t)return[];const n=[];for(const e in t)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=t[e];if(r&&"string"==typeof r){const e=r.split(";");e.length>=4&&n.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:t})}}return n}catch{return[]}}};var Zt=Object.defineProperty,en=(e,t,n)=>((e,t,n)=>t in e?Zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);const tn=new class{constructor(){en(this,"errors",[]),en(this,"toastCount",0),en(this,"lastToastTime",0)}handleError(e,t=!0){const n="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:n,timestamp:Date.now(),count:1}),t&&this.shouldShowToast()){yt({title:this.getErrorTitle(n),description:n,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){yt({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 nn=Object.defineProperty,rn=(e,t,n)=>((e,t,n)=>t in e?nn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);const an=(void 0).VITE_SUPABASE_URL,sn=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY,on=class e{constructor(){rn(this,"client"),rn(this,"currentToken",null),rn(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const t={apikey:sn};e&&this.isTokenValid(e)&&(t.Authorization=`Bearer ${e}`);return h.createClient(an,sn,{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=Jt.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])),n=Math.floor(Date.now()/1e3);return t.exp>n}catch(t){return tn.handleError(t instanceof Error?t:"❌ Supabase - Error validating token",!1),!1}}};rn(on,"instance");let ln=on;function cn(){return ln.getInstance().getClient()}class un{static async generateToken(e,t,n,r=!1){try{if(!r){const e=Jt.getSupabaseToken();if(e&&Jt.isSupabaseTokenValid())return e}const a=cn(),{data:s,error:i}=await a.functions.invoke("validate-token",{body:{access_token:e,alias:t}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(n?.(),null):s?.access_token&&s.access_token?(Jt.setSupabaseToken(s.access_token),s.access_token):null}catch(a){return a instanceof Error&&(a.message.includes("401")||a.message.includes("Unauthorized"))&&n?.(),null}}}var dn=Object.defineProperty,mn=(e,t,n)=>((e,t,n)=>t in e?dn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class pn{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=Jt.getAccessToken(),t=Jt.getSelectedAlias();if(!e||!t)return null;const n=await un.generateToken(e,t,this.onLogoutCallback||void 0,!1);return n?(Jt.setSupabaseToken(n),n):null}catch(e){return null}finally{this.isRegenerating=!1}}}mn(pn,"isRegenerating",!1),mn(pn,"onLogoutCallback",null);class fn{static handleError(e){if(!e)return!1;const t=e.message||e.toString();return!!this.isAuthenticationError(e,t)&&(Jt.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,t){if(401===e.status||401===e.statusCode)return!0;const n=t.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>n.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 hn=Object.defineProperty;class gn{static async handleApiError(e){if(!e||this.isRetrying)return!1;const t=e.status||e.statusCode,n=e.message||e.toString();if(401===t||n.includes("401")||n.includes("Unauthorized")){this.isRetrying=!0;try{return await pn.attemptRegeneration()?(this.isRetrying=!1,!0):(fn.handleError(e),this.isRetrying=!1,!1)}catch(r){return fn.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Jt.getAccessToken();return e?Jt.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,n)=>{((e,t,n)=>{t in e?hn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(e,t+"",n)})(gn,"isRetrying",!1);var xn=Object.defineProperty,yn=(e,t,n)=>((e,t,n)=>t in e?xn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);const vn=new class{constructor(){yn(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,t,n){const r=gn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const a=Jt.getAccessToken();if(!a)throw new Error("Token Qualiex não encontrado");if(!n||""===n.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const s=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{s.searchParams.append(e,t)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json","un-alias":n}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,t){try{const n=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let r=n;if(n.data)r=n.data;else{if(!Array.isArray(n))return tn.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];r=n}if(!Array.isArray(r))return tn.handleError("[QualiexApi] Resposta não é um array",!1),[];return r.map(this.mapToQualiexUser)}catch(n){if(await gn.handleApiError(n))try{const n=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:t,search:"",filterStatus:"active"},e);let r=n;if(n.data)r=n.data;else{if(!Array.isArray(n))return tn.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];r=n}return Array.isArray(r)?r.map(this.mapToQualiexUser):(tn.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(r){return tn.handleError(r instanceof Error?r:"Erro ao buscar usuários após renovação de token",!0),[]}const a=n instanceof Error?n.message:"Erro ao buscar usuários da API Qualiex";return tn.handleError(a,!0),[]}}async fetchUserById(e,t,n){try{return(await this.fetchUsers(t,n)).find(t=>t.userId===e)||null}catch(r){return tn.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,t){const n=await this.fetchUsers(e,t),r=new Map;return n.forEach(e=>{r.set(e.userId,e)}),r}async getUsers(e){const t=Jt.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId):[]}},bn={oauth:{authUrl:(void 0).VITE_OAUTH_AUTH_URL,clientId:(void 0).VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},wn={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Nn={debounceDelay:500},jn=()=>{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},kn={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Cn=()=>kn,Sn={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 En(e,t){const n=Cn(),r=t||n.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function In(e,t){const n=Cn(),r=t||n.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function Tn(e,t){const n=Cn(),r=t||n.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,r):`${e}${r}`}function An(e,t){return t&&t.length>0?t.map(e=>({idField:e.idField,nameField:e.nameField||En(e.idField),emailField:e.emailField||In(e.idField),usernameField:e.usernameField||Tn(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:En(e),emailField:In(e),usernameField:Tn(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Pn=new Map;class _n{static async fetchQualiexUsers(e,t){const n=`${t}_${e}`,r=Pn.get(n);if(r&&Date.now()-r.timestamp<3e5)return r.users;const a=await vn.fetchUsers(e,t);return Pn.set(n,{users:a,timestamp:Date.now()}),a}static extractUserIds(e,t){const n=new Set;for(const r of e)for(const e of t){const t=r[e.idField];t&&"string"==typeof t&&""!==t.trim()&&n.add(t)}return n}static indexUsers(e){const t=new Map;for(const n of e)n.id&&t.set(n.id,n),n.userId&&t.set(n.userId,n);return t}static enrichEntity(e,t,n){const r={...e};for(const a of t){const t=e[a.idField];if(!t)continue;const s=n.get(t);if(s){if(a.nameField){r[a.nameField]||(r[a.nameField]=s.userName||s.displayName||null)}if(a.emailField){r[a.emailField]||(r[a.emailField]=s.userEmail||null)}if(a.usernameField){r[a.usernameField]||(r[a.usernameField]=s.userName||null)}}}return r}static async enrichWithUserData(e,t){if(!Array.isArray(e)||0===e.length)return e;try{const n=Jt.extractTokenData();if(!n)return e;const{alias:r,companyId:a}=n;if(!r||!a)return e;const s=An(t.userIdFields,t.userFieldsMapping);if(0===this.extractUserIds(e,s).size)return e;const i=await this.fetchQualiexUsers(r,a),o=this.indexUsers(i);return e.map(e=>this.enrichEntity(e,s,o))}catch(n){return tn.handleError(n instanceof Error?n: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 Dn=["responsible_name"],Fn=e=>Dn.includes(e);function Rn(e,t,n){const r="string"==typeof e?{tableName:e,searchFields:t||[],schemaName:n||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:a,searchFields:s,selectFields:i,schemaName:o,entityName:l,enableQualiexEnrichment:c=!1}=r,u=()=>{if(!Jt.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return cn().schema(o).from(a)},d=(e,t,n,r)=>{let a=u().select(i||"*",{count:"exact"});a=a.eq("is_removed",!1),Object.entries(r).forEach(([e,t])=>{void 0!==t&&""!==t&&(Array.isArray(t)?a=a.in(e,t):"object"==typeof t&&t&&"operator"in t?"not_null"===t.operator?a=a.not(e,"is",null):"is_null"===t.operator&&(a=a.is(e,null)):null!==t&&(a=a.eq(e,t)))}),a=((e,t)=>{if(t&&s.length>0){const n=s.map(e=>`${e}.ilike.%${t}%`).join(",");return e.or(n)}return e})(a,e);const o=t.includes(".");return o||Fn(t)||(a=a.order(t,{ascending:"asc"===n})),{query:a,isForeignKey:o}},m=async(e,t,n,a,s)=>{const i=An(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===t||e.emailField===t||e.usernameField===t),o=t.includes(".");if(Fn(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 _n.enrichWithUserData(i.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let u;u=o?c.sort((e,r)=>{const a=t.split(".").reduce((e,t)=>e?.[t],e)||"",s=t.split(".").reduce((e,t)=>e?.[t],r)||"",i=String(a).localeCompare(String(s),"pt-BR");return"asc"===n?i:-i}):((e,t,n)=>[...e].sort((e,r)=>{const a=e[t]||"",s=r[t]||"",i=a.localeCompare(s,"pt-BR",{sensitivity:"base"});return"asc"===n?i:-i}))(c,t,n);const d=((e,t=1,n=25)=>{const r=(t-1)*n,a=r+n,s=e.slice(r,a);return{data:s,pagination:{currentPage:t,totalPages:Math.ceil(e.length/n),totalItems:s.length,totalCount:e.length,itemsPerPage:n,hasNextPage:a<e.length,hasPreviousPage:t>1}}})(u,a,s);return{data:d.data,currentPage:d.pagination.currentPage,totalPages:d.pagination.totalPages,totalItems:d.pagination.totalCount,itemsPerPage:d.pagination.itemsPerPage,hasNextPage:d.pagination.hasNextPage,hasPreviousPage:d.pagination.hasPreviousPage}}return await _n.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})};return{async getAll(e={}){const{search:t,sortField:n,sortDirection:s,page:i,limit:o,additionalFilters:u}=(e=>{const{search:t="",sortField:n="updated_at",sortDirection:r="desc",page:a=1,limit:s=25,...i}=e;return{search:t,sortField:n,sortDirection:r,page:a,limit:s,additionalFilters:i}})(e),{query:p}=d(t,n,s,u),f=((e,t,n)=>{const r=(t-1)*n,a=r+n-1;return e.range(r,a)})(p,i,o),{data:h,error:g,count:x}=await f;if(g)throw new Error(`Error fetching ${a}: ${g.message}`);let y=((e,t,n,r)=>{const a=Math.ceil((t||0)/r);return{data:e,currentPage:n,totalPages:a,totalItems:t||0,itemsPerPage:r,hasNextPage:n<a,hasPreviousPage:n>1}})(h||[],x,i,o);if((e=>{if(!c||!l||0===e.length)return!1;const t=An(r.userIdFields,r.userFieldsMapping);return e.some(e=>t.some(t=>e[t.idField]))})(y.data)){const e=await m(y.data,n,s,i,o);if(!Array.isArray(e))return e;y={...y,data:e}}return y},async getById(e){const{data:t,error:n}=await u().select(i||"*").eq("id",e).maybeSingle();if(n)throw new Error(`Error fetching ${a}: ${n.message}`);return t},async create(e){const t=xe(e),n=Object.entries(t).reduce((e,[t,n])=>(void 0!==n&&(e[t]=n),e),{}),{data:r,error:s}=await u().insert(n).select().single();if(s)throw new Error(`Error creating ${a}: ${s.message}`);if(!r)throw new Error(`No data returned from create ${a} operation`);return r},async update(e,t){const n={...xe(t),updated_at:(new Date).toISOString()},{data:r,error:s}=await u().update(n).eq("id",e).select().single();if(s)throw new Error(`Error updating ${a}: ${s.message}`);if(!r)throw new Error(`No data returned from update ${a} operation`);return r},async delete(e){const t={is_removed:!0,updated_at:(new Date).toISOString()},{error:n}=await u().update(t).eq("id",e);if(n)throw new Error(`Error soft deleting ${a}: ${n.message}`)}}}const Ln=()=>{Jt.clearManualLogout()},Mn=e=>e?.placeId||null,On=e=>e?.placeName||null,zn=e=>({placeId:Mn(e),placeName:On(e)}),Un=class{static async initialize(){try{if(!Jt.hasAllTokens()||!Jt.areAllTokensValid())return Jt.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=Jt.getAccessToken(),n=Jt.getIdToken();Ln();const r=this.extractUserFromIdToken(n),a=this.extractCompaniesFromIdToken(n),s=this.extractAliasFromAccessToken(t),i=Jt.extractTokenData(),o=i?.alias;let l=null;if(o&&a.some(e=>e.alias===o))l=o;else{const e=Jt.getSelectedAlias(),t=e&&a.some(t=>t.alias===e);l=t?e:s||a[0]?.alias||null}!Jt.isSupabaseTokenValid()&&l&&await pn.attemptRegeneration();let c=null;if(l){const e=Jt.getCompanyId(l),t=a.find(e=>e.alias===l);t&&(c={id:e||t.id,name:t.name,alias:t.alias})}let u=null,d=null;if(r?.id&&l){const t=Jt.getCompanyId(l);if(t)try{const e=(await vn.fetchActiveUsersMap(l,t)).get(r.id);if(e){const t=zn(e);u=t.placeId,d=t.placeName}}catch(e){}}return{isAuthenticated:!0,isLoading:!1,user:r,alias:l,companies:a,selectedUnit:c,userId:r?.id||null,userAlias:r?.id||null,placeId:u,placeName:d,activePlaceId:u,activePlaceName:d}}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=cn(),{data:t,error:n}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(n)return!1;if(!t?.access_token||!t?.id_token)return!1;const r=new URL("/callback",window.location.origin);return r.hash=`access_token=${t.access_token}&id_token=${t.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e=Jt.generateOAuthState();Jt.setOAuthState(e);const t=Jt.generateOAuthNonce();Jt.setOAuthNonce(t);const n=`${window.location.origin}/callback`,r=new URL(bn.oauth.authUrl);r.searchParams.set("client_id",bn.oauth.clientId),r.searchParams.set("response_type",bn.oauth.responseType),r.searchParams.set("scope",bn.oauth.scope),r.searchParams.set("redirect_uri",n),r.searchParams.set("state",e),r.searchParams.set("nonce",t),r.searchParams.set("response_mode","fragment"),jn(),window.location.href=r.toString()}static async processCallback(){try{if(Jt.hasAllTokens()){if(!Jt.getValidSupabaseToken()){Jt.getAccessToken();await pn.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),n=n=>e.get(n)||t.get(n),r=n("access_token"),a=n("id_token"),s=n("error");if(s)throw new Error(`Erro OAuth: ${s}`);if(!r||!a)throw new Error("Tokens não encontrados na URL de callback");Jt.setAccessToken(r),Jt.setIdToken(a),Ln();const i=this.extractAliasFromAccessToken(r);if(i)Jt.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(a);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Jt.setSelectedAlias(e[0].alias)}if(!await pn.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return Jt.clearOAuthState(),Jt.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Jt.setManualLogout(),Jt.clearAll(),window.location.href="/login"}static decodeToken(e){return Vt.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 n=[];return Object.keys(t).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof t[e]){const r=t[e].split(";");if(r.length>=4)n.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,a]=t[e].split("|");r&&a&&n.push({id:"",alias:r.trim(),name:a.trim()})}}}),n}static extractAliasFromAccessToken(e){const t=this.decodeToken(e);return t?.default||null}};pn.setLogoutCallback(()=>{Un.logout()});let Bn=Un;const $n=e.createContext(void 0),qn=()=>{const t=e.useContext($n);if(void 0===t)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return t};function Vn({queryKey:t,service:n,entityName:r,searchFields:a,additionalFilters:s={},onSuccess:o}){const[l,c]=x.useSearchParams(),u=g.useQueryClient(),{alias:d,userId:m}=qn(),p=e.useCallback(e=>{const n=`${t}_${e}`,r=l.get(n);return r||(l.get(e)||"")},[l,t]),f=p("search"),h=p("sortField")||wn.sorting.defaultField,y=p("sortDirection")||wn.sorting.defaultDirection,v=parseInt(p("page")||"1"),b=parseInt(p("limit")||String(wn.pagination.defaultPageSize)),w=f,N=e.useMemo(()=>({search:w,sortField:h,sortDirection:y,page:v,limit:b,...s}),[w,h,y,v,b,s]),j=e.useCallback(()=>n.getAll(N),[n,N]),k=g.useQuery({queryKey:[t,d,m,N],queryFn:j});if(!k)throw new Error(`useCrud: Query initialization failed for "${r}". Ensure QueryClientProvider is configured in your app root.`);const C=g.useMutation({mutationFn:n.create,onSuccess:()=>{u.invalidateQueries({queryKey:[t]}),i.toast.success(Sn.success.created(r)),o?.()},onError:e=>{i.toast.error(`${Sn.error.create(r)}: ${e.message}`)}}),S=g.useMutation({mutationFn:({id:e,data:t})=>n.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[t]}),i.toast.success(Sn.success.updated(r)),o?.()},onError:e=>{i.toast.error(`${Sn.error.update(r)}: ${e.message}`)}}),E=g.useMutation({mutationFn:n.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[t]}),i.toast.success(Sn.success.deleted(r))},onError:e=>{i.toast.error(`${Sn.error.delete(r)}: ${e.message}`)}}),I=e.useCallback(e=>{const n={...Object.fromEntries(l)};Object.entries(e).forEach(([e,r])=>{const a=`${t}_${e}`;""===r||0===r?delete n[a]:n[a]=String(r)}),delete n.sortField,delete n.sortDirection,c(n)},[l,c,t]),T=e.useCallback(e=>{I({search:e,page:1})},[I]),A=e.useCallback(e=>{I({sortField:e,sortDirection:h===e&&"asc"===y?"desc":"asc",page:1})},[h,y,I]),P=e.useCallback(e=>{I({page:e})},[I]),_=e.useCallback(e=>{I({limit:e,page:1})},[I]),D=e.useCallback(()=>{const e=Object.fromEntries(l),n=`${t}_`,r=Object.fromEntries(Object.entries(e).filter(([e])=>!e.startsWith(n)));c(r)},[c,l,t]),[F,R]=e.useState([]),L=e.useCallback(e=>{R(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[]),M=e.useCallback(()=>{const e=k?.data?.data.map(e=>e.id)||[];R(t=>t.length===e.length?[]:e)},[k?.data?.data]),O=e.useCallback(()=>{R([])},[]),z=e.useMemo(()=>{const e=k?.data?.data.map(e=>e.id)||[];return e.length>0&&F.length===e.length},[F,k?.data?.data]),U=g.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>n.delete(e)))},onSuccess:(e,n)=>{u.invalidateQueries({queryKey:[t]}),i.toast.success(`${n.length} ${r}(s) deletado(s) com sucesso`),O()},onError:e=>{i.toast.error(`Erro ao deletar itens: ${e.message}`)}}),B=e.useCallback((e,t)=>{const n=t?t(e):e;e.id?S.mutate({id:e.id,data:n}):C.mutate({...n,alias:d})},[d,C,S]);return{entities:k?.data?.data||[],pagination:{currentPage:k?.data?.currentPage||1,totalPages:k?.data?.totalPages||1,totalItems:k?.data?.totalItems||0,itemsPerPage:k?.data?.itemsPerPage||wn.pagination.defaultPageSize,hasNextPage:k?.data?.hasNextPage||!1,hasPreviousPage:k?.data?.hasPreviousPage||!1},isLoading:k?.isLoading??!0,isCreating:C?.isPending??!1,isUpdating:S?.isPending??!1,isDeleting:E?.isPending??!1,error:k?.error||null,searchTerm:f,sortField:h,sortDirection:y,currentPage:v,itemsPerPage:b,queryKey:t,createEntity:C.mutate,updateEntity:(e,t)=>S.mutate({id:e,data:t}),deleteEntity:E.mutate,save:B,handleSearch:T,handleSort:A,handlePageChange:P,handleItemsPerPageChange:_,clearFilters:D,refetch:k.refetch,selectedIds:F,selectItem:L,selectAll:M,clearSelection:O,isAllSelected:z,bulkDelete:U.mutate,isBulkDeleting:U.isPending}}const Hn=H.Root,Wn=H.Trigger,Qn=H.Portal,Kn=O.forwardRef(({className:e,...t},n)=>fe.jsx(H.Overlay,{className:ge("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",e),...t,ref:n}));Kn.displayName=H.Overlay.displayName;const Xn=O.forwardRef(({className:e,...t},n)=>fe.jsxs(Qn,{children:[fe.jsx(Kn,{}),fe.jsx(H.Content,{ref:n,className:ge("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",e),...t})]}));Xn.displayName=H.Content.displayName;const Yn=({className:e,...t})=>fe.jsx("div",{className:ge("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",e),...t});Yn.displayName="AlertDialogHeader";const Gn=({className:e,...t})=>fe.jsx("div",{className:ge("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Gn.displayName="AlertDialogFooter";const Jn=O.forwardRef(({className:e,...t},n)=>fe.jsx(H.Title,{ref:n,className:ge("text-lg font-semibold",e),...t}));Jn.displayName=H.Title.displayName;const Zn=O.forwardRef(({className:e,...t},n)=>fe.jsx(H.Description,{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));Zn.displayName=H.Description.displayName;const er=O.forwardRef(({className:e,...t},n)=>fe.jsx(H.Action,{ref:n,className:ge(ye(),e),...t}));er.displayName=H.Action.displayName;const tr=O.forwardRef(({className:e,...t},n)=>fe.jsx(H.Cancel,{ref:n,className:ge(ye({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));tr.displayName=H.Cancel.displayName;const nr=({open:t,onOpenChange:n,item:r,onConfirm:a,entityName:s="item",isDeleting:i=!1,isBulk:o=!1,bulkCount:l})=>{const[c,u]=e.useState("");e.useEffect(()=>{t||u("")},[t]);const d=()=>{u(""),n(!1)},m=o?c===l?.toString():c===r?.title;return r?fe.jsx(Hn,{open:t,onOpenChange:d,children:fe.jsxs(Xn,{className:"sm:max-w-[500px]",children:[fe.jsx(Yn,{children:fe.jsxs("div",{className:"flex items-center space-x-2",children:[fe.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-full bg-destructive/10 flex items-center justify-center",children:fe.jsx("span",{className:"text-destructive font-semibold text-sm",children:"!"})}),fe.jsx("div",{className:"flex-1",children:fe.jsx(Jn,{className:"text-lg font-semibold",children:"Confirmar Exclusão"})})]})}),fe.jsx(Zn,{asChild:!0,children:fe.jsxs("div",{className:"space-y-4",children:[fe.jsxs("div",{className:"text-sm text-muted-foreground",children:[fe.jsx("p",{className:"mb-2",children:o?fe.jsx(fe.Fragment,{children:"Você está prestes a excluir permanentemente:"}):fe.jsxs(fe.Fragment,{children:["Você está prestes a excluir permanentemente o ",s,":"]})}),fe.jsx("div",{className:"p-3 bg-muted rounded-md border-l-4 border-l-destructive",children:fe.jsx("p",{className:"font-medium text-foreground",children:o?`${r.title}`:r.title})})]}),fe.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-md p-3",children:fe.jsxs("div",{className:"flex items-start space-x-2",children:[fe.jsx("div",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-orange-500 flex items-center justify-center mt-0.5",children:fe.jsx("span",{className:"text-white font-bold text-xs",children:"!"})}),fe.jsxs("div",{className:"text-sm text-orange-800",children:[fe.jsx("p",{className:"font-medium mb-1",children:"Atenção!"}),fe.jsx("p",{children:o?fe.jsx(fe.Fragment,{children:"Esta ação não pode ser desfeita. Os itens serão removidos permanentemente do sistema."}):fe.jsxs(fe.Fragment,{children:["Esta ação não pode ser desfeita. O ",s," será removido permanentemente do sistema."]})})]})]})}),fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{htmlFor:"confirmation",className:"text-sm font-medium",children:o?fe.jsxs(fe.Fragment,{children:["Para confirmar, digite o número de itens que serão removidos: ",fe.jsx("strong",{children:l})]}):fe.jsxs(fe.Fragment,{children:["Para confirmar, digite ",fe.jsxs("strong",{children:['"',r.title,'"']})," abaixo:"]})}),fe.jsx(we,{id:"confirmation",type:o?"number":"text",value:c,onChange:e=>u(e.target.value),placeholder:o?`Digite: ${l}`:`Digite: ${r.title}`,className:"w-full"})]})]})}),fe.jsxs(Gn,{children:[fe.jsx(tr,{onClick:d,children:"Cancelar"}),fe.jsx(er,{onClick:()=>{if(!r)return;(o?c===l?.toString():c===r.title)&&(a(r),u(""),n(!1))},disabled:!m||i,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:i?"Removendo...":`Excluir ${s}`})]})]})}):null},rr=O.forwardRef(({className:e,...t},n)=>fe.jsx("table",{ref:n,className:ge("w-full caption-bottom text-sm",e),...t}));rr.displayName="Table";const ar=O.forwardRef(({className:e,...t},n)=>fe.jsx("thead",{ref:n,className:ge("[&_tr]:border-b sticky top-0 z-[1] bg-background",e),...t}));ar.displayName="TableHeader";const sr=O.forwardRef(({className:e,...t},n)=>fe.jsx("tbody",{ref:n,className:ge("[&_tr:last-child]:border-0",e),...t}));sr.displayName="TableBody";const ir=O.forwardRef(({className:e,...t},n)=>fe.jsx("tfoot",{ref:n,className:ge("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));ir.displayName="TableFooter";const or=O.forwardRef(({className:e,...t},n)=>fe.jsx("tr",{ref:n,className:ge("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",e),...t}));or.displayName="TableRow";const lr=O.forwardRef(({className:e,...t},n)=>fe.jsx("th",{ref:n,className:ge("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",e),...t}));lr.displayName="TableHead";const cr=O.forwardRef(({className:e,...t},n)=>fe.jsx("td",{ref:n,className:ge("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));cr.displayName="TableCell";const ur=O.forwardRef(({className:e,...t},n)=>fe.jsx("caption",{ref:n,className:ge("mt-4 text-sm text-muted-foreground",e),...t}));function dr({rows:e=5,columns:t=4}){return fe.jsx("div",{className:"w-full",children:fe.jsxs("div",{className:"rounded-md border",children:[fe.jsx("div",{className:"border-b bg-muted/50 px-4 py-3",children:fe.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((e,t)=>fe.jsx(zt,{className:"h-4 w-24"},t))})}),fe.jsx("div",{children:Array.from({length:e}).map((e,n)=>fe.jsx("div",{className:"border-b px-4 py-3 last:border-0",children:fe.jsx("div",{className:"flex space-x-4",children:Array.from({length:t}).map((e,t)=>fe.jsx(zt,{className:"h-4 w-20"},t))})},n))})]})})}function mr({count:e=3}){return fe.jsx("div",{className:"space-y-4",children:Array.from({length:e}).map((e,t)=>fe.jsxs(ke,{children:[fe.jsxs(Ce,{children:[fe.jsx(zt,{className:"h-4 w-3/4"}),fe.jsx(zt,{className:"h-3 w-1/2"})]}),fe.jsx(Ie,{children:fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(zt,{className:"h-3 w-full"}),fe.jsx(zt,{className:"h-3 w-2/3"})]})})]},t))})}ur.displayName="TableCaption";const pr={default:o.FileX,search:o.Search,error:o.AlertCircle};function fr({icon:e,title:t,description:n,action:r,className:a,variant:s="default"}){const i=e?()=>e:pr[s];return fe.jsxs("div",{className:ge("flex flex-col items-center justify-center py-12 px-4 text-center",a),children:[fe.jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:fe.jsx(i,{className:"h-8 w-8 text-muted-foreground"})}),fe.jsx("h3",{className:"text-lg font-semibold mb-2",children:t}),n&&fe.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),r&&fe.jsx(ve,{onClick:r.onClick,variant:"outline",children:r.label})]})}const hr=W.Root,gr=W.Trigger,xr=W.Group,yr=W.Portal,vr=W.Sub,br=W.RadioGroup,wr=O.forwardRef(({className:e,inset:t,children:n,...r},a)=>fe.jsxs(W.SubTrigger,{ref:a,className:ge("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",e),...r,children:[n,fe.jsx(o.ChevronRight,{className:"ml-auto h-4 w-4"})]}));wr.displayName=W.SubTrigger.displayName;const Nr=O.forwardRef(({className:e,...t},n)=>fe.jsx(W.SubContent,{ref:n,className:ge("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",e),...t}));Nr.displayName=W.SubContent.displayName;const jr=O.forwardRef(({className:e,sideOffset:t=4,...n},r)=>fe.jsx(W.Portal,{children:fe.jsx(W.Content,{ref:r,sideOffset:t,className:ge("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",e),...n})}));jr.displayName=W.Content.displayName;const kr=O.forwardRef(({className:e,inset:t,...n},r)=>fe.jsx(W.Item,{ref:r,className:ge("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",t&&"pl-8",e),...n}));kr.displayName=W.Item.displayName;const Cr=O.forwardRef(({className:e,children:t,checked:n,...r},a)=>fe.jsxs(W.CheckboxItem,{ref:a,className:ge("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",e),checked:n,...r,children:[fe.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:fe.jsx(W.ItemIndicator,{children:fe.jsx(o.Check,{className:"h-4 w-4"})})}),t]}));Cr.displayName=W.CheckboxItem.displayName;const Sr=O.forwardRef(({className:e,children:t,...n},r)=>fe.jsxs(W.RadioItem,{ref:r,className:ge("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",e),...n,children:[fe.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:fe.jsx(W.ItemIndicator,{children:fe.jsx(o.Circle,{className:"h-2 w-2 fill-current"})})}),t]}));Sr.displayName=W.RadioItem.displayName;const Er=O.forwardRef(({className:e,inset:t,...n},r)=>fe.jsx(W.Label,{ref:r,className:ge("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));Er.displayName=W.Label.displayName;const Ir=O.forwardRef(({className:e,...t},n)=>fe.jsx(W.Separator,{ref:n,className:ge("-mx-1 my-1 h-px bg-muted",e),...t}));Ir.displayName=W.Separator.displayName;const Tr=({className:e,...t})=>fe.jsx("span",{className:ge("ml-auto text-xs tracking-widest opacity-60",e),...t});Tr.displayName="DropdownMenuShortcut";const Ar=({onEdit:e,onDelete:t,onToggleStatus:n,isActive:r=!0,canDelete:a=!0,customActions:s=[],renderAs:i})=>{const l=[];if(e){const t={icon:o.Edit,label:"Editar",onClick:e};l.push(t)}if(s.forEach(e=>{l.push(e)}),n){const e={icon:r?o.PowerOff:o.Power,label:r?"Inativar":"Ativar",onClick:n};l.push(e)}if(a&&t){const e={icon:o.Trash2,label:"Remover",onClick:t,destructive:!0};l.push(e)}return"dropdown"===i?fe.jsx(fe.Fragment,{children:l.map((e,t)=>fe.jsxs(kr,{onClick:e.onClick,className:e.destructive?"text-destructive":"",children:[fe.jsx(e.icon,{className:"mr-2 h-4 w-4"}),e.label]},t))}):fe.jsx(fe.Fragment,{children:l.map((e,t)=>fe.jsxs(ve,{variant:"ghost",size:"sm",onClick:e.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(e.destructive?"text-destructive hover:text-destructive":""),children:[fe.jsx(e.icon,{className:"h-4 w-4 mr-2"}),e.label]},t))})},Pr=({onEdit:e,onDelete:t,canDelete:n=!0,onToggleStatus:r,isActive:a=!0,customActions:s=[]})=>fe.jsxs(hr,{children:[fe.jsx(gr,{asChild:!0,children:fe.jsx(ve,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:fe.jsx(o.EllipsisVertical,{size:12})})}),fe.jsx(jr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:fe.jsx(Ar,{onEdit:t=>{t?.stopPropagation(),e?.()},onDelete:e=>{e?.stopPropagation(),t?.()},onToggleStatus:e=>{e?.stopPropagation(),r?.()},isActive:a,canDelete:n,customActions:s,renderAs:"dropdown"})})]}),_r=({contextMenu:t,onClose:n,onEdit:r,onDelete:a,onToggleStatus:s,customActions:i})=>(e.useEffect(()=>{const e=()=>n();if(t)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[t,n]),t?fe.jsx("div",{className:"fixed bg-background border border-border rounded-md shadow-lg py-1 z-50 min-w-[120px]",style:{left:t.x,top:t.y},onClick:e=>e.stopPropagation(),children:fe.jsx(Ar,{onEdit:r?()=>{r(t.item),n()}:void 0,onDelete:a?()=>{a(t.item),n()}:void 0,onToggleStatus:s?()=>{s(t.item),n()}:void 0,isActive:t.item.is_actived,canDelete:!!a,customActions:i?i(t.item):[],renderAs:"context"})}):null),Dr=e.memo(({checked:e,onCheckedChange:t})=>fe.jsx(st,{checked:e,onCheckedChange:t}),(e,t)=>e.checked===t.checked),Fr=({manager:t,columns:n,onEdit:r,onView:a,onToggleStatus:s,onDelete:i,renderActions:l,customRowActions:c,enableBulkActions:u=!1})=>{const[d,m]=e.useState(!1),[p,f]=e.useState(null);e.useEffect(()=>{const e=()=>m(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e.useEffect(()=>{const e=()=>f(null);if(p)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[p]);const h=e.useMemo(()=>(()=>{n.length;let e=0;const t=n.map(t=>{if(t.width)return e+=t.width,{...t,calculatedWidth:t.width,isFixed:!0};{const n=t.minWidth||120,r=t.weight||1;return e+=n,{...t,calculatedWidth:n,weight:r,isFixed:!1}}});return e+=50,t.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[n]);return d?t.isLoading?fe.jsx(mr,{count:3}):0===t.entities.length?fe.jsx(fr,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):fe.jsxs("div",{className:"space-y-4",children:[t.entities.map(e=>fe.jsx(ke,{className:ge("overflow-hidden cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(e.id)&&"bg-muted"),onClick:n=>{n.stopPropagation(),u?t.selectItem(e.id):r?.(e)},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,item:e})},children:fe.jsx(Ie,{className:"p-4",children:fe.jsxs("div",{className:"flex items-start gap-3",children:[u&&fe.jsx("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:fe.jsx(Dr,{checked:t.selectedIds.includes(e.id),onCheckedChange:()=>t.selectItem(e.id)})}),fe.jsxs("div",{className:"flex-1",children:[n.map(t=>fe.jsxs("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[fe.jsxs("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[t.header,":"]}),fe.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(e):String(e[t.key]??"")})]},String(t.key))),(r||a||l)&&fe.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:l?l(e):fe.jsx(Pr,{onEdit:r?()=>{r(e)}:void 0,onDelete:i?()=>i(e):void 0,onToggleStatus:s?()=>s(e):void 0,isActive:e.is_actived,customActions:c?c(e):[]})})]})]})})},e.id)),fe.jsx(_r,{contextMenu:p,onClose:()=>f(null),onEdit:r,onDelete:i,onToggleStatus:s,customActions:c})]}):fe.jsxs("div",{className:"flex flex-col h-full",children:[t.isLoading?fe.jsx(dr,{rows:5,columns:n.length}):fe.jsx("div",{className:"flex flex-col h-full overflow-hidden",children:fe.jsx("div",{className:"flex-1 overflow-auto",children:fe.jsxs(rr,{className:"table-auto",children:[fe.jsxs("colgroup",{children:[u&&fe.jsx("col",{style:{width:"50px"}}),h.map((e,t)=>fe.jsx("col",{style:e.style},t)),fe.jsx("col",{style:{width:"50px"}})]}),fe.jsx(ar,{children:fe.jsxs(or,{children:[u&&fe.jsx(lr,{className:"w-[50px]",children:fe.jsx(Dr,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),n.map(e=>{return fe.jsx(lr,{className:`${e.className||""} ${e.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:e.sortable?()=>t.handleSort(String(e.key)):void 0,children:fe.jsxs("div",{className:"flex items-center "+(e.className?.includes("text-center")?"justify-center":""),children:[e.header,e.sortable&&(n=String(e.key),t.sortField!==n?fe.jsx(o.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?fe.jsx(o.ArrowUp,{size:14,className:"ml-1"}):fe.jsx(o.ArrowDown,{size:14,className:"ml-1"}))]})},String(e.key));var n}),fe.jsx(lr,{className:"w-[50px] text-center",children:"Ações"})]})}),fe.jsx(sr,{children:0===t.entities.length?fe.jsx(or,{children:fe.jsx(cr,{colSpan:u?n.length+2:n.length+1,className:"h-32",children:fe.jsx(fr,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(e=>fe.jsxs(or,{className:ge("cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(e.id)&&"bg-muted"),onClick:n=>{n.stopPropagation(),u?t.selectItem(e.id):r?.(e)},onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),f({x:t.clientX,y:t.clientY,item:e})},children:[u&&fe.jsx(cr,{onClick:e=>e.stopPropagation(),children:fe.jsx(Dr,{checked:t.selectedIds.includes(e.id),onCheckedChange:()=>t.selectItem(e.id)})}),n.map(t=>fe.jsx(cr,{className:t.className,children:t.render?t.render(e):String(e[t.key]??"")},String(t.key))),fe.jsx(cr,{className:"text-center",children:l?l(e):fe.jsx(Pr,{onEdit:r?()=>r(e):void 0,onDelete:i?()=>i(e):void 0,onToggleStatus:s?()=>s(e):void 0,isActive:e.is_actived,customActions:c?c(e):[]})})]},e.id))})]})})}),fe.jsx(_r,{contextMenu:p,onClose:()=>f(null),onEdit:r,onDelete:i,onToggleStatus:s,customActions:c})]})};function Rr(t,n,r,a){const[s,i]=e.useState({}),[o,l]=e.useState({}),c=e.useMemo(()=>t,[t]),u=e=>e instanceof Date&&!isNaN(e.getTime()),d=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(n){return d(e)}},p=(e,t,n)=>{if(e.required&&(""===t||null==t||Array.isArray(t)&&0===t.length))return`${e.label} é obrigatório`;if(e.validation){let a;if("function"==typeof e.validation?a=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(a=e.validation.custom),a)try{const e=a(t,n);if(e)return e}catch(r){}}};e.useEffect(()=>{if(!a)return;const e=t=>{const n=[];return t.forEach(t=>{n.push(t),t.fields&&n.push(...e(t.fields))}),n},t=e(c),s={};t.forEach(e=>{let t;if(n&&void 0!==n[e.name]){if(t=n[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);u(e)&&(t=e.toISOString().split("T")[0])}else u(t)&&(t=t.toISOString().split("T")[0])}else t=d(e);s[e.name]=t}),t.forEach(e=>{const t=m(e,s);void 0!==t&&(s[e.name]=t)}),n&&Object.keys(n).forEach(e=>{t.find(t=>t.name===e)||void 0===n[e]||(s[e]=n[e])}),i(s),l({}),r&&r(s)},[c,n,r,a]);const f=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...f(e.fields))}),t},h=()=>{const e=f(c),t={};return e.forEach(e=>{const n=p(e,s[e.name],s);n&&(t[e.name]=n)}),l(t),0===Object.keys(t).length};return{formData:s,errors:o,updateField:(e,t)=>{i(n=>{const a={...n,[e]:t},s=((e,t)=>{let n={...t};const r=e=>{const t=[];return e.forEach(e=>{t.push(e),e.fields&&t.push(...r(e.fields))}),t};return r(c).filter(t=>t.dependsOn===e).forEach(e=>{const t=m(e,n);void 0!==t&&(n={...n,[e.name]:t})}),n})(e,a);return r&&r(s),s}),o[e]&&l(t=>{const n={...t};return delete n[e],n});const n=f(c).find(t=>t.name===e);if(n){const r=p(n,t,s);r&&l(t=>({...t,[e]:r}))}},validateForm:h,handleSubmit:e=>t=>{t&&(t.preventDefault(),t.stopPropagation()),h()&&e(s)}}}const Lr=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Mr=({value:e="#3b82f6",onChange:t,label:n})=>fe.jsxs("div",{className:"space-y-2",children:[n&&fe.jsx(je,{children:n}),fe.jsxs(It,{children:[fe.jsx(Tt,{asChild:!0,children:fe.jsxs(ve,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[fe.jsx("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:e}}),e]})}),fe.jsx(At,{className:"w-64",children:fe.jsxs("div",{className:"space-y-3",children:[fe.jsxs("div",{children:[fe.jsx(je,{htmlFor:"color-input",children:"Cor personalizada"}),fe.jsx(we,{id:"color-input",type:"color",value:e,onChange:e=>t?.(e.target.value),className:"h-10 w-full"})]}),fe.jsxs("div",{children:[fe.jsx(je,{children:"Cores predefinidas"}),fe.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Lr.map(e=>fe.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:e},onClick:()=>t?.(e),"aria-label":`Selecionar cor ${e}`},e))})]})]})})]})]}),Or=O.forwardRef(({className:e,children:t,...n},r)=>fe.jsxs(Q.Root,{ref:r,className:ge("relative overflow-hidden",e),...n,children:[fe.jsx(Q.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),fe.jsx(zr,{}),fe.jsx(Q.Corner,{})]}));Or.displayName=Q.Root.displayName;const zr=O.forwardRef(({className:e,orientation:t="vertical",...n},r)=>fe.jsx(Q.ScrollAreaScrollbar,{ref:r,orientation:t,className:ge("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:fe.jsx(Q.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));zr.displayName=Q.ScrollAreaScrollbar.displayName;const Ur={Star:o.Star,Heart:o.Heart,Home:o.Home,User:o.User,Settings:o.Settings,Mail:o.Mail,Phone:o.Phone,Calendar:o.Calendar,MapPin:o.MapPin,Camera:o.Camera,Image:o.Image,Music:o.Music,Video:o.Video,Book:o.Book,Bookmark:o.Bookmark,Search:o.Search,Filter:o.Filter,Edit:o.Edit,Trash2:o.Trash2,Plus:o.Plus,Minus:o.Minus,Check:o.Check,X:o.X,ChevronDown:o.ChevronDown,ChevronUp:o.ChevronUp,ChevronLeft:o.ChevronLeft,ChevronRight:o.ChevronRight,ArrowUp:o.ArrowUp,ArrowDown:o.ArrowDown,ArrowLeft:o.ArrowLeft,ArrowRight:o.ArrowRight,Clock:o.Clock,Bell:o.Bell,AlertCircle:o.AlertCircle,Info:o.Info,HelpCircle:o.HelpCircle,Download:o.Download,Upload:o.Upload,Share:o.Share,Copy:o.Copy,Save:o.Save,FileText:o.FileText,Folder:o.Folder,FolderOpen:o.FolderOpen,Archive:o.Archive,Lock:o.Lock,Unlock:o.Unlock,Eye:o.Eye,EyeOff:o.EyeOff,Shield:o.Shield,Key:o.Key,Zap:o.Zap,Flame:o.Flame,Sparkles:o.Sparkles,Award:o.Award,Trophy:o.Trophy,Target:o.Target},Br=({value:t="Star",onChange:n,label:r})=>{const[a,s]=e.useState(""),i=Object.entries(Ur).filter(([e])=>e.toLowerCase().includes(a.toLowerCase())),l=Ur[t]||o.Star;return fe.jsxs("div",{className:"space-y-2",children:[r&&fe.jsx(je,{children:r}),fe.jsxs(It,{children:[fe.jsx(Tt,{asChild:!0,children:fe.jsxs(ve,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[fe.jsx(l,{className:"h-4 w-4 mr-2"}),t]})}),fe.jsx(At,{className:"w-80",children:fe.jsxs("div",{className:"space-y-3",children:[fe.jsxs("div",{children:[fe.jsx(je,{htmlFor:"icon-search",children:"Buscar ícone"}),fe.jsx(we,{id:"icon-search",placeholder:"Digite o nome do ícone...",value:a,onChange:e=>s(e.target.value)})]}),fe.jsx(Or,{className:"h-48",children:fe.jsx("div",{className:"grid grid-cols-6 gap-2",children:i.map(([e,r])=>fe.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===e?"border-primary bg-primary/10":"border-border"),onClick:()=>n?.(e),title:e,children:fe.jsx(r,{className:"h-4 w-4"})},e))})})]})})]})]})};function $r({items:e,getItemValue:t,getItemLabel:n,...r}){const a=r.error?"string"==typeof r.error?r.error:!(r.error instanceof Error)||r.error.message:void 0,s={...r,multiple:!1,options:e,getOptionValue:t,getOptionLabel:n,error:a};return fe.jsx($t,{...s})}const qr=(e={})=>{const{user:t,alias:n}=qn(),{enabled:r=!1}=e;return g.useQuery({queryKey:["qualiex-users",n],queryFn:()=>vn.getUsers(n),enabled:r&&!!n&&!!t,retry:2,retryDelay:1e3})},Vr=({value:e="",onChange:t,placeholder:n="Selecionar usuário",disabled:r,className:a,enabled:s})=>{const{data:i=[],isLoading:o,error:l}=qr({enabled:s});return fe.jsx($r,{value:e,onChange:t,items:i,isLoading:o,error:l,getItemValue:e=>e.userId,getItemLabel:e=>e.userName,placeholder:n,searchPlaceholder:"Buscar usuário...",emptyMessage:"Nenhum usuário disponível",disabled:r,className:a})};function Hr({title:t,sections:n,initialData:r,onSubmit:a,onCancel:s,open:i,submitButtonText:o="Salvar",isLoading:l=!1,usersData:c}){const[u,d]=e.useState(n?.[0]?.id||""),m=e.useRef(null),[p,f]=e.useState(null),h=e.useCallback(e=>{m.current=e,f(e)},[]),g=e.useMemo(()=>n&&Array.isArray(n)?n.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[n]),{formData:x,errors:y,updateField:v,handleSubmit:b}=Rr(g,r,void 0,i),w=e.useMemo(()=>n&&Array.isArray(n)?n.map(e=>({...e,disabled:e.condition?!e.condition(x):e.disabled||!1})):[],[n,x]),N=e.useMemo(()=>{const e=w.find(e=>e.id===u);if(e&&!e.disabled)return u;const t=w.find(e=>!e.disabled);return t?.id||u},[w,u]);e.useEffect(()=>{N!==u&&d(N)},[N,u]);const j=w.find(e=>e.id===N),k=e=>{const t=(e.computedValue,x[e.name]),n=void 0!==t?t:"",r=y[e.name];switch(e.type){case"group":return fe.jsxs("div",{className:"space-y-2",children:[e.label,fe.jsx("div",{className:e.className||("horizontal"===e.layout?"flex gap-3":"space-y-3"),children:e.fields?.map(e=>k(e))})]},e.name);case"user-select":return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[fe.jsx(je,{htmlFor:e.name,children:e.label}),fe.jsx(Vr,{value:n||"",onChange:t=>v(e.name,t),placeholder:e.placeholder,disabled:e.disabled,className:r?"border-red-500":""}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name);case"textarea":return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[fe.jsx(je,{htmlFor:e.name,children:e.label}),fe.jsx(it,{id:e.name,value:n||"",onChange:t=>{v(e.name,t.target.value)},placeholder:e.placeholder,disabled:e.disabled,className:`${r?"border-red-500":""} ${e.disabled?"bg-gray-100 cursor-not-allowed":""}`}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name);case"select":return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[fe.jsx(je,{htmlFor:e.name,children:e.label}),fe.jsxs(Xe,{value:String(n),onValueChange:t=>{v(e.name,t),e.onValueChange&&e.onValueChange(t)},disabled:e.disabled,children:[fe.jsx(Je,{className:`${r?"border-red-500":""} ${e.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:fe.jsx(Ge,{placeholder:e.placeholder})}),fe.jsx(tt,{children:e.options?.map(e=>fe.jsx(rt,{value:e.value,children:e.label},e.value))})]}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name);case"multiselect":return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[fe.jsxs(je,{htmlFor:e.name,children:[e.label,e.required&&fe.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),fe.jsx($t,{options:e.options||[],value:Array.isArray(n)?n:[],onChange:t=>v(e.name,t),placeholder:e.placeholder,disabled:e.disabled,error:r,popoverContainer:p,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name);case"date":return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[fe.jsx(je,{htmlFor:e.name,children:e.label}),fe.jsx(we,{id:e.name,type:"date",value:String(n),onChange:t=>v(e.name,t.target.value),placeholder:e.placeholder,disabled:e.disabled,className:ge("w-full",r?"border-red-500":"",e.disabled?"bg-gray-100 cursor-not-allowed":"")}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name);case"color":return fe.jsxs("div",{children:[fe.jsxs(je,{htmlFor:e.name,children:[e.label," ",e.required&&fe.jsx("span",{className:"text-destructive",children:"*"})]}),fe.jsx(we,{id:e.name,type:"color",value:n||e.defaultValue||"#000000",onChange:t=>v(e.name,t.target.value),className:"h-10"}),r&&fe.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},e.name);case"color-picker":return fe.jsxs("div",{children:[fe.jsx(Mr,{label:`${e.label} ${e.required?"*":""}`,value:n||e.defaultValue||"#3b82f6",onChange:t=>v(e.name,t)}),r&&fe.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},e.name);case"icon-picker":return fe.jsxs("div",{children:[fe.jsx(Br,{label:`${e.label} ${e.required?"*":""}`,value:n||e.defaultValue||"Star",onChange:t=>v(e.name,t)}),r&&fe.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},e.name);case"custom":if(!e.component)return null;const t=e.component;return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[e.label&&fe.jsx(je,{htmlFor:e.name,children:e.label}),fe.jsx(t,{value:n,onChange:t=>{v(e.name,t),e.onValueChange&&e.onValueChange(t)},disabled:e.disabled,error:r,popoverContainer:p,...e.componentProps||{}}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name);case"number":return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[fe.jsx(je,{htmlFor:e.name,children:e.label}),fe.jsx(we,{id:e.name,type:"number",value:null!=n?String(n):"",onChange:t=>{const n=t.target.value,r=""===n?null:Number(n);v(e.name,r)},placeholder:e.placeholder,disabled:e.disabled,className:`${r?"border-red-500":""} ${e.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:e.min,step:e.step||"1"}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name);default:return fe.jsxs("div",{className:`space-y-2 ${e.className||""}`,children:[fe.jsx(je,{htmlFor:e.name,children:e.label}),fe.jsx(we,{id:e.name,type:"text",value:n||"",onChange:t=>{v(e.name,t.target.value)},placeholder:e.placeholder,disabled:e.disabled,className:`${r?"border-red-500":""} ${e.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:e.disabled}),r&&fe.jsx("p",{className:"text-sm text-red-500",children:r})]},e.name)}},C=e.useCallback(()=>{if(!j)return null;if(j.disabled)return fe.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[fe.jsx("div",{className:"rounded-full bg-muted p-3 mb-4",children:fe.jsx("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:fe.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),fe.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),fe.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(j.component){const e=j.component;return fe.jsx(e,{formData:x,updateField:v,errors:y,users:c,disabled:j.disabled})}return fe.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:j.fields.map(k)})},[j,x,v,y,c,k]),S=fe.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[w.length>1&&fe.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:fe.jsx("div",{className:"flex space-x-2",children:w.map(e=>fe.jsx(ve,{variant:N===e.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const t=w.find(t=>t.id===e);t&&!t.disabled&&d(e)})(e.id),disabled:e.disabled,className:e.disabled?"opacity-50 cursor-not-allowed":"",children:e.title},e.id))})}),fe.jsx("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 pt-0 pb-2 md:pb-4",children:l?fe.jsx("div",{className:"flex items-center justify-center py-12",children:fe.jsx("div",{className:"text-muted-foreground",children:"Carregando dados..."})}):fe.jsxs("form",{onSubmit:b(a),className:"space-y-3 md:space-y-4",children:[C(),fe.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[fe.jsx(ve,{type:"button",variant:"outline",onClick:s,children:"Cancelar"}),fe.jsx(ve,{type:"submit",disabled:l,children:o})]})]})})]});return fe.jsx(Ae,{open:i,onOpenChange:e=>{!1===e&&!0===i&&s()},children:fe.jsxs(Re,{ref:h,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[fe.jsxs(Le,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[fe.jsx(Oe,{className:"text-white",children:t}),fe.jsx(ze,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),S]})})}function Wr({currentPage:e,totalPages:t,totalItems:n,itemsPerPage:r,onPageChange:a,onItemsPerPageChange:s,variant:i="full"}){const l=(e-1)*r+1,c=Math.min(e*r,n);return fe.jsxs("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[fe.jsx("div",{className:"flex items-center gap-2",children:"full"===i&&fe.jsxs(fe.Fragment,{children:[fe.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Itens por página"}),fe.jsxs(Xe,{value:String(r),onValueChange:e=>s(Number(e)),children:[fe.jsx(Je,{className:"h-8 w-[70px]",children:fe.jsx(Ge,{})}),fe.jsxs(tt,{children:[fe.jsx(rt,{value:"10",children:"10"}),fe.jsx(rt,{value:"25",children:"25"}),fe.jsx(rt,{value:"50",children:"50"}),fe.jsx(rt,{value:"100",children:"100"})]})]})]})}),fe.jsxs("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[l,"-",c," de ",n," itens"]}),fe.jsxs("div",{className:"flex items-center gap-1",children:[fe.jsx(ve,{variant:"outline",size:"sm",onClick:()=>a(1),disabled:1===e,className:"h-8 w-8 p-0",children:fe.jsx(o.ChevronsLeft,{size:16})}),fe.jsx(ve,{variant:"outline",size:"sm",onClick:()=>a(e-1),disabled:1===e,className:"h-8 w-8 p-0",children:fe.jsx(o.ChevronLeft,{size:16})}),fe.jsxs("div",{className:"flex items-center gap-1 px-2",children:[fe.jsx("span",{className:"text-sm font-medium",children:e}),fe.jsx("span",{className:"text-sm text-muted-foreground",children:"de"}),fe.jsx("span",{className:"text-sm font-medium",children:t})]}),fe.jsx(ve,{variant:"outline",size:"sm",onClick:()=>a(e+1),disabled:e===t,className:"h-8 w-8 p-0",children:fe.jsx(o.ChevronRight,{size:16})}),fe.jsx(ve,{variant:"outline",size:"sm",onClick:()=>a(t),disabled:e===t,className:"h-8 w-8 p-0",children:fe.jsx(o.ChevronsRight,{size:16})})]})]})}function Qr({manager:e}){return fe.jsx(Wr,{currentPage:e.pagination.currentPage,totalPages:e.pagination.totalPages,totalItems:e.pagination.totalItems,itemsPerPage:e.pagination.itemsPerPage,onPageChange:e.handlePageChange,onItemsPerPageChange:e.handleItemsPerPageChange,variant:"full"})}const Kr=({selectedCount:e,onClearSelection:t,onBulkDelete:n,customActions:r=[],isLoading:a=!1})=>fe.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-4 py-2 bg-primary/10 border-b border-primary/20",children:[fe.jsxs("div",{className:"flex items-center gap-3",children:[fe.jsxs("span",{className:"text-sm font-medium",children:[e," ",1===e?"item selecionado":"itens selecionados"]}),fe.jsxs(ve,{variant:"ghost",size:"sm",onClick:t,className:"h-7 px-2",children:[fe.jsx(o.X,{size:14,className:"mr-1"}),"Limpar"]})]}),fe.jsxs("div",{className:"flex items-center gap-2",children:[r.map((e,t)=>{const n=e.icon;return fe.jsxs(ve,{variant:e.variant||"outline",size:"sm",onClick:()=>e.action([]),disabled:a,className:"h-7",children:[n&&fe.jsx(n,{size:14,className:"mr-1"}),e.label]},t)}),n&&fe.jsxs(ve,{variant:"destructive",size:"sm",onClick:n,disabled:a,className:"h-7",children:[fe.jsx(o.Trash2,{size:14,className:"mr-1"}),"Remover"]})]})]}),Xr={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Yr={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Gr={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Jr({children:e,direction:t="column",gap:n="md",align:r="stretch",justify:a="start",wrap:s=!1,className:i}){return fe.jsx("div",{className:ge("flex","column"===t?"flex-col":"flex-row",Xr[n],Yr[r],Gr[a],s&&"flex-wrap",i),children:e})}function Zr({manager:e,filters:t,inline:n=!1}){const{isSearchVisible:r}=qn(),a=e.searchTerm,s=fe.jsxs(fe.Fragment,{children:[t.some(e=>"search"===e.type)&&!r&&fe.jsxs("div",{className:"relative flex-1",children:[fe.jsx(o.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),fe.jsx(we,{placeholder:"Buscar...",value:e.searchTerm,onChange:t=>e.handleSearch(t.target.value),className:"pl-10"})]}),t.filter(e=>"select"===e.type&&e.options).map((e,t)=>fe.jsxs("select",{value:e.value||"",onChange:t=>e.onChange?.(t.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:[e.placeholder&&fe.jsx("option",{value:"",children:e.placeholder}),e.options.map(e=>fe.jsx("option",{value:e.value,children:e.label},e.value))]},`select-${t}`)),t.filter(e=>"custom"===e.type&&e.component).map((e,t)=>{const r=e.component;return fe.jsx("div",{className:n?"":"w-full sm:w-auto",children:fe.jsx(r,{...e.props})},`custom-${t}`)}),a&&fe.jsxs(ve,{variant:"outline",onClick:e.clearFilters,className:"whitespace-nowrap",children:[fe.jsx(o.X,{className:"h-4 w-4 mr-2"}),"Limpar Filtros"]})]});return n?fe.jsx("div",{className:"flex items-center gap-2",children:s}):fe.jsx(Jr,{direction:"column",gap:"md",className:"mb-6",children:fe.jsx(Jr,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:s})})}function ea({manager:t,config:n,formSections:r,onSave:a,onToggleStatus:s,defaultSort:i}){t&&t.queryKey;const{setSearchVisible:l}=qn(),[c,u]=x.useSearchParams(),[d,m]=e.useState(!1),[p,f]=e.useState(null),[h,g]=e.useState({isOpen:!1,entityId:null,entityName:""}),[y,v]=e.useState({isOpen:!1,count:0});e.useEffect(()=>(l(!0),()=>{l(!1)}),[l]),e.useEffect(()=>{if(i&&t){const e=`${t.queryKey}_sortField`,n=`${t.queryKey}_sortDirection`;if(!c.has(e)&&!c.has(n)){const t=Object.fromEntries(c);t[e]=i.column,t[n]=i.direction,u(t)}}},[]);return fe.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[n.enableBulkActions&&t.selectedIds.length>0&&fe.jsx(Kr,{selectedCount:t.selectedIds.length,onClearSelection:t.clearSelection,onBulkDelete:n.bulkActions&&n.bulkActions.length>0?void 0:()=>{v({isOpen:!0,count:t.selectedIds.length})},customActions:n.bulkActions,isLoading:t.isBulkDeleting}),fe.jsxs("div",{className:"flex-shrink-0 flex justify-between items-center px-4 py-1.5 bg-muted/50 border-b gap-4",children:[fe.jsxs("div",{className:"flex items-center gap-2",children:[fe.jsxs(ve,{onClick:()=>{n.onNew?n.onNew():(f(null),m(!0))},children:[fe.jsx(o.Plus,{size:16,className:"mr-2"}),"Novo"]}),n.customActions?.map((e,t)=>fe.jsxs(ve,{onClick:e.action,variant:e.variant||"outline",children:[e.icon&&fe.jsx(e.icon,{size:16,className:"mr-2"}),e.label]},t))]}),n.filters&&n.filters.length>0&&fe.jsx("div",{className:"flex items-center gap-2 flex-1 justify-end",children:fe.jsx(Zr,{manager:t,filters:n.filters,inline:!0})})]}),fe.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:n.customListView?fe.jsx("div",{className:"flex-1 overflow-auto p-4",children:n.customListView(t.entities,t)}):fe.jsx(Fr,{manager:t,columns:n.columns,onEdit:e=>{n.onEdit?n.onEdit(e):(f(e),m(!0))},onDelete:e=>{g({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})},onToggleStatus:s,enableBulkActions:n.enableBulkActions,customRowActions:n.customRowActions})}),fe.jsx("div",{className:"flex-shrink-0 border-t bg-background",children:fe.jsx(Qr,{manager:t})}),!n.useCustomRouting&&fe.jsx(Hr,{open:d,title:p?`Editar ${n.entityName}`:`Novo ${n.entityName}`,sections:r,initialData:p||void 0,onSubmit:e=>{a(e),m(!1),f(null)},onCancel:()=>{m(!1),f(null)},isLoading:t.isLoading,submitButtonText:p?"Atualizar":"Criar"}),fe.jsx(nr,{open:h.isOpen,onOpenChange:()=>{g({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{h.entityId&&(t.deleteEntity(h.entityId),g({isOpen:!1,entityId:null,entityName:""}))},item:h.entityId?{id:h.entityId,title:h.entityName}:void 0,entityName:n.entityName,isDeleting:t.isDeleting}),fe.jsx(nr,{open:y.isOpen,onOpenChange:()=>v({isOpen:!1,count:0}),onConfirm:()=>(t.bulkDelete?.(t.selectedIds),void v({isOpen:!1,count:0})),item:{id:"bulk",title:`${y.count} ${1===y.count?n.entityName:n.entityNamePlural}`},entityName:n.entityNamePlural,isDeleting:t.isBulkDeleting,isBulk:!0,bulkCount:y.count})]})}function ta(e,t,n={}){const r=[];return Object.keys(t).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const n=t[e],a={key:e,header:ra(e),label:ra(e),...na(e,n),sortable:!0,searchable:"string"==typeof n};r.push(a)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...n}}function na(e,t){const n=e.toLowerCase();return n.includes("email")?{type:"email",required:!0}:n.includes("phone")||n.includes("tel")?{type:"tel"}:n.includes("description")||n.includes("content")||n.includes("notes")?{type:"textarea"}:n.includes("status")||n.includes("type")||n.includes("category")?{type:"select",options:[]}:"boolean"==typeof t?{type:"boolean"}:"number"==typeof t?{type:"number"}:t instanceof Date?{type:"date"}:{type:"text"}}function ra(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const aa={user:{title:"Usuários",searchPlaceholder:"Buscar usuários...",enableDelete:!1},product:{title:"Produtos",searchPlaceholder:"Buscar produtos...",enableFilters:!0},order:{title:"Pedidos",searchPlaceholder:"Buscar pedidos...",enableCreate:!1},category:{title:"Categorias",searchPlaceholder:"Buscar categorias...",itemsPerPage:20}};const sa=n.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"}}),ia=O.forwardRef(({className:e,variant:t,...n},r)=>fe.jsx("div",{ref:r,role:"alert",className:ge(sa({variant:t}),e),...n}));ia.displayName="Alert";const oa=O.forwardRef(({className:e,...t},n)=>fe.jsx("h5",{ref:n,className:ge("mb-1 font-medium leading-none tracking-tight",e),...t}));oa.displayName="AlertTitle";const la=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,className:ge("text-sm [&_p]:leading-relaxed",e),...t}));la.displayName="AlertDescription";const ca=e.createContext(void 0);function ua({children:t}){const[n,r]=e.useState({});return fe.jsx(ca.Provider,{value:{metadata:n,setMetadata:r,clearMetadata:()=>r({})},children:t})}function da(){const t=e.useContext(ca);if(!t)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return t}const ma=K.Root,pa=O.forwardRef(({className:e,...t},n)=>fe.jsx(K.Item,{ref:n,className:ge("border-b",e),...t}));pa.displayName="AccordionItem";const fa=O.forwardRef(({className:e,children:t,...n},r)=>fe.jsx(K.Header,{className:"flex",children:fe.jsxs(K.Trigger,{ref:r,className:ge("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,fe.jsx(o.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));fa.displayName=K.Trigger.displayName;const ha=O.forwardRef(({className:e,children:t,...n},r)=>fe.jsx(K.Content,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:fe.jsx("div",{className:ge("pb-4 pt-0",e),children:t})}));ha.displayName=K.Content.displayName;const ga=X.Root,xa=O.forwardRef(({className:e,...t},n)=>fe.jsx(Y.Root,{ref:n,className:ge("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));xa.displayName=Y.Root.displayName;const ya=O.forwardRef(({className:e,...t},n)=>fe.jsx(Y.Image,{ref:n,className:ge("aspect-square h-full w-full",e),...t}));ya.displayName=Y.Image.displayName;const va=O.forwardRef(({className:e,...t},n)=>fe.jsx(Y.Fallback,{ref:n,className:ge("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));va.displayName=Y.Fallback.displayName;const ba=O.forwardRef(({...e},t)=>fe.jsx("nav",{ref:t,"aria-label":"breadcrumb",...e}));ba.displayName="Breadcrumb";const wa=O.forwardRef(({className:e,...t},n)=>fe.jsx("ol",{ref:n,className:ge("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",e),...t}));wa.displayName="BreadcrumbList";const Na=O.forwardRef(({className:e,...t},n)=>fe.jsx("li",{ref:n,className:ge("inline-flex items-center gap-1.5",e),...t}));Na.displayName="BreadcrumbItem";const ja=O.forwardRef(({asChild:e,className:t,...n},r)=>{const a=e?O.Fragment:"a";return fe.jsx(a,{ref:r,className:ge("transition-colors hover:text-foreground",t),...n})});ja.displayName="BreadcrumbLink";const ka=O.forwardRef(({className:e,...t},n)=>fe.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:ge("font-normal text-foreground",e),...t}));ka.displayName="BreadcrumbPage";const Ca=({children:e,className:t,...n})=>fe.jsx("li",{role:"presentation","aria-hidden":"true",className:ge("[&>svg]:size-3.5",t),...n,children:e??fe.jsx(o.ChevronRight,{})});Ca.displayName="BreadcrumbSeparator";const Sa=({className:e,...t})=>fe.jsxs("span",{role:"presentation","aria-hidden":"true",className:ge("flex h-9 w-9 items-center justify-center",e),...t,children:[fe.jsx(o.MoreHorizontal,{className:"h-4 w-4"}),fe.jsx("span",{className:"sr-only",children:"More"})]});function Ea(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}function Ia(e){return(t,n)=>{let r;if("formatting"===(n?.context?String(n.context):"standalone")&&e.formattingValues){const t=e.defaultFormattingWidth||e.defaultWidth,a=n?.width?String(n.width):t;r=e.formattingValues[a]||e.formattingValues[t]}else{const t=e.defaultWidth,a=n?.width?String(n.width):e.defaultWidth;r=e.values[a]||e.values[t]}return r[e.argumentCallback?e.argumentCallback(t):t]}}function Ta(e){return(t,n={})=>{const r=n.width,a=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],s=t.match(a);if(!s)return null;const i=s[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n;return}(o,e=>e.test(i)):function(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n;return}(o,e=>e.test(i));let c;c=e.valueCallback?e.valueCallback(l):l,c=n.valueCallback?n.valueCallback(c):c;return{value:c,rest:t.slice(i.length)}}}Sa.displayName="BreadcrumbEllipsis";const Aa={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"}},Pa={date:Ea({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:Ea({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Ea({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},_a={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"},Da={ordinalNumber:(e,t)=>{const n=Number(e);return"week"===t?.unit?n+"ª":n+"º"},era:Ia({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Ia({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:Ia({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:Ia({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:Ia({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"})},Fa={ordinalNumber:(Ra={matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)},(e,t={})=>{const n=e.match(Ra.matchPattern);if(!n)return null;const r=n[0],a=e.match(Ra.parsePattern);if(!a)return null;let s=Ra.valueCallback?Ra.valueCallback(a[0]):a[0];return s=t.valueCallback?t.valueCallback(s):s,{value:s,rest:e.slice(r.length)}}),era:Ta({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:Ta({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:Ta({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:Ta({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:Ta({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"})};var Ra;const La={code:"pt-BR",formatDistance:(e,t,n)=>{let r;const a=Aa[e];return r="string"==typeof a?a:1===t?a.one:a.other.replace("{{count}}",String(t)),n?.addSuffix?n.comparison&&n.comparison>0?"em "+r:"há "+r:r},formatLong:Pa,formatRelative:(e,t,n,r)=>{const a=_a[e];return"function"==typeof a?a(t):a},localize:Da,match:Fa,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Ma({className:e,classNames:t,showOutsideDays:n=!0,...r}){return fe.jsx(k.DayPicker,{showOutsideDays:n,className:ge("p-3",e),locale:La,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:ge(ye({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:ge(ye({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",...t},components:{IconLeft:({...e})=>fe.jsx(o.ChevronLeft,{className:"h-4 w-4"}),IconRight:({...e})=>fe.jsx(o.ChevronRight,{className:"h-4 w-4"})},...r})}Ma.displayName="Calendar";const Oa=G.Root,za=G.CollapsibleTrigger,Ua=G.CollapsibleContent;const Ba={Root:function({children:e,className:t}){return fe.jsx("div",{className:ge("space-y-4",t),children:e})},Item:function({children:e,onClick:t,className:n}){return fe.jsx(ke,{className:ge("transition-colors",t&&"cursor-pointer hover:bg-muted/50",n),onClick:t,children:fe.jsx(Ie,{className:"p-4",children:e})})},Field:function({label:e,value:t,className:n}){return fe.jsxs("div",{className:ge("flex justify-between items-center text-sm",n),children:[fe.jsxs("span",{className:"text-muted-foreground font-medium",children:[e,":"]}),fe.jsx("span",{className:"text-foreground",children:t})]})}};const $a={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))]"},qa={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Va({children:e,cols:t="auto-fit",gap:n="md",className:r}){return fe.jsx("div",{className:ge("grid",$a[t],qa[n],r),children:e})}const Ha=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Wa({multiple:t,options:n,value:r,onChange:a,getOptionValue:s,getOptionLabel:i,placeholder:l,label:c,icon:u,emptyMessage:d,searchPlaceholder:m,disabled:p,required:f,className:h,sortOptions:g,maxDisplayedBadges:x,popoverContainer:y,onOpen:v,onClose:b}){const[w,N]=e.useState(!1),[j,k]=e.useState(""),C=e.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),S=e.useMemo(()=>{if(!y)return;let e=y,t=0;try{for(;e&&t<3;){const n=window.getComputedStyle(e),r=n.overflowY||n.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,t++}}catch{}return e??void 0},[y]),E=e.useMemo(()=>{const e=n.map(e=>({original:e,value:s(e),label:i(e)}));return g?e.sort((e,t)=>e.label.localeCompare(t.label,"pt-BR",{sensitivity:"base"})):e},[n,s,i,g]),I=e.useMemo(()=>{if(!j)return E;const e=Ha(j);return E.filter(t=>Ha(t.label).includes(e))},[E,j]),T=e.useMemo(()=>E.filter(e=>C.includes(e.value)),[E,C]),A=(e,n)=>{n.preventDefault(),n.stopPropagation(),a&&a(t?C.filter(t=>t!==e):"")},P=x?T.slice(0,x):T,_=x&&T.length>x?T.length-x:0;return fe.jsxs("div",{className:ge("space-y-2",h),children:[c&&fe.jsxs(je,{children:[c,f&&fe.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),fe.jsxs(It,{open:w,onOpenChange:e=>{N(e),e?v?.():(k(""),b?.())},modal:!1,children:[fe.jsx(Tt,{asChild:!0,children:fe.jsxs(ve,{variant:"outline",role:"combobox","aria-expanded":w,disabled:p,className:ge("w-full justify-between min-h-10 h-auto",0===T.length&&"text-muted-foreground"),children:[0===T.length?fe.jsxs("span",{className:"flex items-center gap-2",children:[u&&fe.jsx(u,{className:"h-4 w-4"}),l]}):t?fe.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[P.map(e=>fe.jsxs(lt,{variant:"secondary",className:"gap-1 pr-1",children:[e.label,fe.jsx("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:t=>{"Enter"===t.key&&A(e.value,t)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:t=>A(e.value,t),children:fe.jsx(o.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),_>0&&fe.jsxs(lt,{variant:"outline",className:"gap-1",children:["+",_]})]}):fe.jsxs("span",{className:"flex items-center gap-2",children:[u&&fe.jsx(u,{className:"h-4 w-4"}),T[0]?.label]}),fe.jsx(o.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),fe.jsx(At,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:S,collisionBoundary:S,children:fe.jsxs(Pt,{children:[fe.jsx(_t,{placeholder:m,value:j,onChange:e=>k(e.target.value)}),fe.jsx(Dt,{children:0===n.length?fe.jsx(Ft,{children:d}):0===I.length?fe.jsx(Ft,{children:"Nenhum item encontrado."}):fe.jsx(Rt,{children:I.map(e=>fe.jsxs(Mt,{value:e.value,onSelect:()=>(e=>{if(a)if(t){const t=C.includes(e)?C.filter(t=>t!==e):[...C,e];a(t)}else a(e),N(!1)})(e.value),className:"cursor-pointer",children:[fe.jsx(o.Check,{className:ge("mr-2 h-4 w-4",C.includes(e.value)?"opacity-100":"opacity-0")}),e.label]},e.value))})})]})})]})]})}const Qa=({className:e,...t})=>fe.jsx("nav",{role:"navigation","aria-label":"pagination",className:ge("mx-auto flex w-full justify-center",e),...t});Qa.displayName="Pagination";const Ka=O.forwardRef(({className:e,...t},n)=>fe.jsx("ul",{ref:n,className:ge("flex flex-row items-center gap-1",e),...t}));Ka.displayName="PaginationContent";const Xa=O.forwardRef(({className:e,...t},n)=>fe.jsx("li",{ref:n,className:ge("",e),...t}));Xa.displayName="PaginationItem";const Ya=({className:e,isActive:t,size:n="icon",...r})=>fe.jsx("a",{"aria-current":t?"page":void 0,className:ge(ye({variant:t?"outline":"ghost",size:n}),e),...r});Ya.displayName="PaginationLink";const Ga=({className:e,...t})=>fe.jsxs(Ya,{"aria-label":"Go to previous page",size:"default",className:ge("gap-1 pl-2.5",e),...t,children:[fe.jsx(o.ChevronLeft,{className:"h-4 w-4"}),fe.jsx("span",{children:"Previous"})]});Ga.displayName="PaginationPrevious";const Ja=({className:e,...t})=>fe.jsxs(Ya,{"aria-label":"Go to next page",size:"default",className:ge("gap-1 pr-2.5",e),...t,children:[fe.jsx("span",{children:"Next"}),fe.jsx(o.ChevronRight,{className:"h-4 w-4"})]});Ja.displayName="PaginationNext";const Za=({className:e,...t})=>fe.jsxs("span",{"aria-hidden":!0,className:ge("flex h-9 w-9 items-center justify-center",e),...t,children:[fe.jsx(o.MoreHorizontal,{className:"h-4 w-4"}),fe.jsx("span",{className:"sr-only",children:"More pages"})]});Za.displayName="PaginationEllipsis";const es=O.forwardRef(({className:e,value:t,...n},r)=>fe.jsx(J.Root,{ref:r,className:ge("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:fe.jsx(J.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));es.displayName=J.Root.displayName;const ts=O.forwardRef(({className:e,...t},n)=>fe.jsx(Z.Root,{className:ge("grid gap-2",e),...t,ref:n}));ts.displayName=Z.Root.displayName;const ns=O.forwardRef(({className:e,...t},n)=>fe.jsx(Z.Item,{ref:n,className:ge("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",e),...t,children:fe.jsx(Z.Indicator,{className:"flex items-center justify-center",children:fe.jsx(o.Circle,{className:"h-2.5 w-2.5 fill-current text-current"})})}));ns.displayName=Z.Item.displayName;const rs=O.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},a)=>fe.jsx(ee.Root,{ref:a,decorative:n,orientation:t,className:ge("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...r}));rs.displayName=ee.Root.displayName;const as=U.Root,ss=U.Trigger,is=U.Close,os=U.Portal,ls=O.forwardRef(({className:e,...t},n)=>fe.jsx(U.Overlay,{className:ge("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",e),...t,ref:n}));ls.displayName=U.Overlay.displayName;const cs=n.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"}}),us=O.forwardRef(({side:e="right",className:t,children:n,...r},a)=>fe.jsxs(os,{children:[fe.jsx(ls,{}),fe.jsxs(U.Content,{ref:a,className:ge(cs({side:e}),t),...r,children:[n,fe.jsxs(U.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:[fe.jsx(o.X,{className:"h-4 w-4"}),fe.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));us.displayName=U.Content.displayName;const ds=({className:e,...t})=>fe.jsx("div",{className:ge("flex flex-col space-y-2 text-center sm:text-left",e),...t});ds.displayName="SheetHeader";const ms=({className:e,...t})=>fe.jsx("div",{className:ge("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});ms.displayName="SheetFooter";const ps=O.forwardRef(({className:e,...t},n)=>fe.jsx(U.Title,{ref:n,className:ge("text-lg font-semibold text-foreground",e),...t}));ps.displayName=U.Title.displayName;const fs=O.forwardRef(({className:e,...t},n)=>fe.jsx(U.Description,{ref:n,className:ge("text-sm text-muted-foreground",e),...t}));fs.displayName=U.Description.displayName;const hs=te.Provider,gs=te.Root,xs=te.Trigger,ys=O.forwardRef(({className:e,sideOffset:t=4,...n},r)=>fe.jsx(te.Content,{ref:r,sideOffset:t,className:ge("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",e),...n}));ys.displayName=te.Content.displayName;const vs="sidebar:state",bs=O.createContext(null);function ws(){const e=O.useContext(bs);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Ns=O.forwardRef(({defaultOpen:e=!0,open:t,onOpenChange:n,className:r,style:a,children:s,...i},o)=>{const[l,c]=O.useState(!1);O.useEffect(()=>{const e=()=>c(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,d]=O.useState(!1),[m,p]=O.useState(()=>{if("undefined"!=typeof window){const t=localStorage.getItem(vs);return null!==t?"true"===t:e}return e}),f=t??m,h=O.useCallback(e=>{const t="function"==typeof e?e(f):e;n?n(t):p(t),"undefined"!=typeof window&&localStorage.setItem(vs,String(t))},[n,f]),g=O.useCallback(()=>l?d(e=>!e):h(e=>!e),[l,h,d]);O.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 x=f?"expanded":"collapsed",y=O.useMemo(()=>({state:x,open:f,setOpen:h,isMobile:l,openMobile:u,setOpenMobile:d,toggleSidebar:g}),[x,f,h,l,u,d,g]);return fe.jsx(bs.Provider,{value:y,children:fe.jsx(hs,{delayDuration:0,children:fe.jsx("div",{className:ge("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",...a},ref:o,...i,children:s})})})});Ns.displayName="SidebarProvider";const js=O.forwardRef(({side:e="left",variant:t="sidebar",collapsible:n="offcanvas",className:r,children:a,...s},i)=>{const{isMobile:o,state:l,openMobile:c,setOpenMobile:u}=ws();return"none"===n?fe.jsx("div",{className:ge("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:i,...s,children:a}):o?fe.jsx(as,{open:c,onOpenChange:u,...s,children:fe.jsxs(us,{"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:e,children:[fe.jsx(ps,{className:"sr-only",children:"Menu de Navegação"}),fe.jsx("div",{className:"flex h-full w-full flex-col",children:a})]})}):fe.jsxs("div",{ref:i,className:"group peer hidden md:block text-sidebar-foreground","data-state":l,"data-collapsible":"collapsed"===l?n:"","data-variant":t,"data-side":e,children:[fe.jsx("div",{className:ge("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"===t||"inset"===t?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),fe.jsx("div",{className:ge("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===e?"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"===t||"inset"===t?"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),...s,children:fe.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:a})})]})});js.displayName="Sidebar";const ks=O.forwardRef(({className:e,onClick:t,...n},r)=>{const{toggleSidebar:a}=ws();return fe.jsxs(ve,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:ge("h-7 w-7",e),onClick:e=>{t?.(e),a()},...n,children:[fe.jsx(o.PanelLeft,{}),fe.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});ks.displayName="SidebarTrigger";const Cs=O.forwardRef(({className:e,...t},n)=>{const{toggleSidebar:r}=ws();return fe.jsx("button",{ref:n,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:ge("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",e),...t})});Cs.displayName="SidebarRail";const Ss=O.forwardRef(({className:e,...t},n)=>fe.jsx("main",{ref:n,className:ge("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",e),...t}));Ss.displayName="SidebarInset";const Es=O.forwardRef(({className:e,...t},n)=>fe.jsx(we,{ref:n,"data-sidebar":"input",className:ge("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",e),...t}));Es.displayName="SidebarInput";const Is=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,"data-sidebar":"header",className:ge("flex flex-col gap-2 p-2",e),...t}));Is.displayName="SidebarHeader";const Ts=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,"data-sidebar":"footer",className:ge("flex flex-col gap-2 p-2",e),...t}));Ts.displayName="SidebarFooter";const As=O.forwardRef(({className:e,...t},n)=>fe.jsx(rs,{ref:n,"data-sidebar":"separator",className:ge("mx-2 w-auto bg-sidebar-border",e),...t}));As.displayName="SidebarSeparator";const Ps=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,"data-sidebar":"content",className:ge("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t}));Ps.displayName="SidebarContent";const _s=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,"data-sidebar":"group",className:ge("relative flex w-full min-w-0 flex-col p-2",e),...t}));_s.displayName="SidebarGroup";const Ds=O.forwardRef(({className:e,asChild:n=!1,...r},a)=>{const s=n?t.Slot:"div";return fe.jsx(s,{ref:a,"data-sidebar":"group-label",className:ge("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",e),...r})});Ds.displayName="SidebarGroupLabel";const Fs=O.forwardRef(({className:e,asChild:n=!1,...r},a)=>{const s=n?t.Slot:"button";return fe.jsx(s,{ref:a,"data-sidebar":"group-action",className:ge("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",e),...r})});Fs.displayName="SidebarGroupAction";const Rs=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,"data-sidebar":"group-content",className:ge("w-full text-sm",e),...t}));Rs.displayName="SidebarGroupContent";const Ls=O.forwardRef(({className:e,...t},n)=>fe.jsx("ul",{ref:n,"data-sidebar":"menu",className:ge("flex w-full min-w-0 flex-col gap-1",e),...t}));Ls.displayName="SidebarMenu";const Ms=O.forwardRef(({className:e,...t},n)=>fe.jsx("li",{ref:n,"data-sidebar":"menu-item",className:ge("group/menu-item relative",e),...t}));Ms.displayName="SidebarMenuItem";const Os=n.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"}}),zs=O.forwardRef(({asChild:e=!1,isActive:n=!1,variant:r="default",size:a="default",tooltip:s,className:i,...o},l)=>{const c=e?t.Slot:"button",{isMobile:u,state:d}=ws(),m=fe.jsx(c,{ref:l,"data-sidebar":"menu-button","data-size":a,"data-active":n,className:ge(Os({variant:r,size:a}),i),...o});return s?("string"==typeof s&&(s={children:s}),fe.jsxs(gs,{children:[fe.jsx(xs,{asChild:!0,children:m}),fe.jsx(ys,{side:"right",align:"center",hidden:"collapsed"!==d||u,...s})]})):m});zs.displayName="SidebarMenuButton";const Us=O.forwardRef(({className:e,asChild:n=!1,showOnHover:r=!1,...a},s)=>{const i=n?t.Slot:"button";return fe.jsx(i,{ref:s,"data-sidebar":"menu-action",className:ge("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",e),...a})});Us.displayName="SidebarMenuAction";const Bs=O.forwardRef(({className:e,...t},n)=>fe.jsx("div",{ref:n,"data-sidebar":"menu-badge",className:ge("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",e),...t}));Bs.displayName="SidebarMenuBadge";const $s=O.forwardRef(({className:e,showIcon:t=!1,...n},r)=>{const a=O.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return fe.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:ge("rounded-md h-8 flex gap-2 px-2 items-center",e),...n,children:[t&&fe.jsx("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),fe.jsx("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":a}})]})});$s.displayName="SidebarMenuSkeleton";const qs=O.forwardRef(({className:e,...t},n)=>fe.jsx("ul",{ref:n,"data-sidebar":"menu-sub",className:ge("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",e),...t}));qs.displayName="SidebarMenuSub";const Vs=O.forwardRef(({...e},t)=>fe.jsx("li",{ref:t,...e}));Vs.displayName="SidebarMenuSubItem";const Hs=O.forwardRef(({asChild:e=!1,size:n="md",isActive:r,className:a,...s},i)=>{const o=e?t.Slot:"a";return fe.jsx(o,{ref:i,"data-sidebar":"menu-sub-button","data-size":n,"data-active":r,className:ge("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"===n&&"text-xs","md"===n&&"text-sm","group-data-[collapsible=icon]:hidden",a),...s})});Hs.displayName="SidebarMenuSubButton";const Ws=O.forwardRef(({className:e,...t},n)=>fe.jsxs(ne.Root,{ref:n,className:ge("relative flex w-full touch-none select-none items-center",e),...t,children:[fe.jsx(ne.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:fe.jsx(ne.Range,{className:"absolute h-full bg-primary"})}),fe.jsx(ne.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"})]}));Ws.displayName=ne.Root.displayName;function Qs(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),!1===n||!r.defaultPrevented)return t?.(r)}}function Ks(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}function Xs(...e){return O.useCallback(function(...e){return t=>{let n=!1;const r=e.map(e=>{const r=Ks(e,t);return n||"function"!=typeof r||(n=!0),r});if(n)return()=>{for(let t=0;t<r.length;t++){const n=r[t];"function"==typeof n?n():Ks(e[t],null)}}}}(...e),e)}function Ys(...e){const t=e[0];if(1===e.length)return t;const n=()=>{const n=e.map(e=>({useScope:e(),scopeName:e.scopeName}));return function(e){const r=n.reduce((t,{useScope:n,scopeName:r})=>({...t,...n(e)[`__scope${r}`]}),{});return O.useMemo(()=>({[`__scope${t.scopeName}`]:r}),[r])}};return n.scopeName=t.scopeName,n}var Gs=globalThis?.document?O.useLayoutEffect:()=>{},Js=O[" useInsertionEffect ".trim().toString()]||Gs;function Zs({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,s,i]=function({defaultProp:e,onChange:t}){const[n,r]=O.useState(e),a=O.useRef(n),s=O.useRef(t);return Js(()=>{s.current=t},[t]),O.useEffect(()=>{a.current!==n&&(s.current?.(n),a.current=n)},[n,a]),[n,r,s]}({defaultProp:t,onChange:n}),o=void 0!==e,l=o?e:a;{const t=O.useRef(void 0!==e);O.useEffect(()=>{const e=t.current;if(e!==o){}t.current=o},[o,r])}const c=O.useCallback(t=>{if(o){const n=function(e){return"function"==typeof e}(t)?t(e):t;n!==e&&i.current?.(n)}else s(t)},[o,e,s,i]);return[l,c]}var ei=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"].reduce((e,n)=>{const r=t.createSlot(`Primitive.${n}`),a=O.forwardRef((e,t)=>{const{asChild:a,...s}=e,i=a?r:n;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),fe.jsx(i,{...s,ref:t})});return a.displayName=`Primitive.${n}`,{...e,[n]:a}},{}),ti="Switch",[ni]=function(e,t=[]){let n=[];const r=()=>{const t=n.map(e=>O.createContext(e));return function(n){const r=n?.[e]||t;return O.useMemo(()=>({[`__scope${e}`]:{...n,[e]:r}}),[n,r])}};return r.scopeName=e,[function(t,r){const a=O.createContext(r),s=n.length;n=[...n,r];const i=t=>{const{scope:n,children:r,...i}=t,o=n?.[e]?.[s]||a,l=O.useMemo(()=>i,Object.values(i));return fe.jsx(o.Provider,{value:l,children:r})};return i.displayName=t+"Provider",[i,function(n,i){const o=i?.[e]?.[s]||a,l=O.useContext(o);if(l)return l;if(void 0!==r)return r;throw new Error(`\`${n}\` must be used within \`${t}\``)}]},Ys(r,...t)]}(ti),[ri,ai]=ni(ti),si=O.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:s,required:i,disabled:o,value:l="on",onCheckedChange:c,form:u,...d}=e,[m,p]=O.useState(null),f=Xs(t,e=>p(e)),h=O.useRef(!1),g=!m||(u||!!m.closest("form")),[x,y]=Zs({prop:a,defaultProp:s??!1,onChange:c,caller:ti});return fe.jsxs(ri,{scope:n,checked:x,disabled:o,children:[fe.jsx(ei.button,{type:"button",role:"switch","aria-checked":x,"aria-required":i,"data-state":ci(x),"data-disabled":o?"":void 0,disabled:o,value:l,...d,ref:f,onClick:Qs(e.onClick,e=>{y(e=>!e),g&&(h.current=e.isPropagationStopped(),h.current||e.stopPropagation())})}),g&&fe.jsx(li,{control:m,bubbles:!h.current,name:r,value:l,checked:x,required:i,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});si.displayName=ti;var ii="SwitchThumb",oi=O.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,a=ai(ii,n);return fe.jsx(ei.span,{"data-state":ci(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});oi.displayName=ii;var li=O.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...a},s)=>{const i=O.useRef(null),o=Xs(i,s),l=function(e){const t=O.useRef({value:e,previous:e});return O.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}(n),c=function(e){const[t,n]=O.useState(void 0);return Gs(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const t=new ResizeObserver(t=>{if(!Array.isArray(t))return;if(!t.length)return;const r=t[0];let a,s;if("borderBoxSize"in r){const e=r.borderBoxSize,t=Array.isArray(e)?e[0]:e;a=t.inlineSize,s=t.blockSize}else a=e.offsetWidth,s=e.offsetHeight;n({width:a,height:s})});return t.observe(e,{box:"border-box"}),()=>t.unobserve(e)}n(void 0)},[e]),t}(t);return O.useEffect(()=>{const e=i.current;if(!e)return;const t=window.HTMLInputElement.prototype,a=Object.getOwnPropertyDescriptor(t,"checked").set;if(l!==n&&a){const t=new Event("click",{bubbles:r});a.call(e,n),e.dispatchEvent(t)}},[l,n,r]),fe.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});function ci(e){return e?"checked":"unchecked"}li.displayName="SwitchBubbleInput";var ui=si,di=oi;const mi=O.forwardRef(({className:e,...t},n)=>fe.jsx(ui,{className:ge("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",e),...t,ref:n,children:fe.jsx(di,{className:ge("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")})}));mi.displayName=ui.displayName;const pi=re.Root,fi=O.forwardRef(({className:e,...t},n)=>fe.jsx(re.List,{ref:n,className:ge("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),...t}));fi.displayName=re.List.displayName;const hi=O.forwardRef(({className:e,...t},n)=>fe.jsx(re.Trigger,{ref:n,className:ge("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",e),...t}));hi.displayName=re.Trigger.displayName;const gi=O.forwardRef(({className:e,...t},n)=>fe.jsx(re.Content,{ref:n,className:ge("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));gi.displayName=re.Content.displayName;const xi=n.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"}}),yi=O.forwardRef(({className:e,variant:t,size:n,...r},a)=>fe.jsx(ae.Root,{ref:a,className:ge(xi({variant:t,size:n,className:e})),...r}));yi.displayName=ae.Root.displayName;const vi=O.createContext({size:"default",variant:"default"}),bi=O.forwardRef(({className:e,variant:t,size:n,children:r,...a},s)=>fe.jsx(se.Root,{ref:s,className:ge("flex items-center justify-center gap-1",e),...a,children:fe.jsx(vi.Provider,{value:{variant:t,size:n},children:r})}));bi.displayName=se.Root.displayName;const wi=O.forwardRef(({className:e,children:t,variant:n,size:r,...a},s)=>{const i=O.useContext(vi);return fe.jsx(se.Item,{ref:s,className:ge(xi({variant:i.variant||n,size:i.size||r}),e),...a,children:t})});function Ni({onEdit:e,onDelete:t,onToggleStatus:n,isActive:r=!0,canEdit:a=!0,canDelete:s=!0,customActions:i=[],renderAs:l="dropdown",variant:c="default"}){const u=[];return e&&a&&u.push({icon:o.Edit,label:"Editar",onClick:e,variant:"default"}),n&&u.push({icon:r?o.PowerOff:o.Power,label:r?"Inativar":"Ativar",onClick:n,variant:"default"}),i.forEach(e=>{!1!==e.show&&u.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),t&&s&&u.push({icon:o.Trash2,label:"Remover",onClick:t,variant:"destructive"}),0===u.length?null:"dropdown"===l?fe.jsxs(hr,{children:[fe.jsx(gr,{asChild:!0,children:fe.jsx(ve,{variant:"ghost",size:"compact"===c?"sm":"default",className:"compact"===c?"h-7 px-2":"",children:fe.jsx(o.EllipsisVertical,{size:"compact"===c?14:16})})}),fe.jsx(jr,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:u.map((e,t)=>fe.jsxs(kr,{onClick:e.onClick,className:"destructive"===e.variant?"text-destructive":"",children:[e.icon&&fe.jsx(e.icon,{className:"mr-2 h-4 w-4"}),e.label]},t))})]}):fe.jsx("div",{className:"flex items-center gap-1",children:u.map((e,t)=>fe.jsxs(ve,{variant:"destructive"===e.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:e.onClick,className:"compact"===c?"h-7 px-2":"",children:[e.icon&&fe.jsx(e.icon,{size:"compact"===c?14:16}),"compact"!==c&&fe.jsx("span",{className:"ml-1",children:e.label})]},t))})}function ji(e){const t=x.useNavigate();return{onNew:()=>{const n=e.newPath||`${e.basePath}/new`;t(n)},onEdit:n=>{const r=e.editPath?e.editPath.replace(":id",n.id):`${e.basePath}/${n.id}/edit`;t(r)}}}wi.displayName=se.Item.displayName;const ki=e.memo(({variant:t="card",className:n="",selectedUnit:r,onUnitChange:a})=>{const{user:s,companies:i,alias:l,isAuthenticated:c,logout:u,switchUnit:d}=qn(),m=i?.[0]||null,p=l?i?.find(e=>e.alias===l):m,f=i||[],h=r||p||m||m,g=e.useCallback(e=>{a?a(e):d(e)},[a,d]),x=e.useMemo(()=>{if(!f?.length)return[];const e=new Map;f.forEach(t=>{e.set(t.alias,t)});const t=Array.from(e.values()),n=t.find(e=>e.alias===h?.alias),r=t.filter(e=>e.alias!==h?.alias);return r.sort((e,t)=>(e.name||"").localeCompare(t.name||"","pt-BR",{sensitivity:"base"})),n?[n,...r]:r},[f,h?.alias]);if(!c||!s)return null;const y=()=>fe.jsxs(fe.Fragment,{children:[fe.jsxs("div",{className:"flex items-center space-x-3",children:[fe.jsx("div",{className:"flex-shrink-0",children:fe.jsx("div",{className:"w-10 h-10 bg-primary rounded-full flex items-center justify-center",children:fe.jsx(o.User,{className:"h-5 w-5 text-primary-foreground"})})}),fe.jsxs("div",{className:"flex-1 min-w-0",children:[fe.jsx("p",{className:"text-sm font-medium truncate",children:s.name}),fe.jsxs("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",h?.name||"N/A"]})]})]}),h&&fe.jsx("div",{className:"mt-3",children:fe.jsxs("div",{className:"flex items-center space-x-2",children:[fe.jsx(o.Building2,{className:"h-4 w-4 text-muted-foreground"}),fe.jsx("span",{className:"text-sm font-medium",children:h.name})]})}),x.length>1&&fe.jsxs("div",{className:"mt-2",children:[fe.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",x.length]}),fe.jsxs("div",{className:"flex flex-wrap gap-1",children:[x.slice(0,3).map(e=>fe.jsx(lt,{variant:e.alias===h?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>g(e),children:e.name},e.alias)),x.length>3&&fe.jsxs(lt,{variant:"outline",className:"text-xs",children:["+",x.length-3]})]})]})]});return"dropdown"===t?fe.jsxs(hr,{children:[fe.jsx(gr,{asChild:!0,children:fe.jsx(ve,{variant:"ghost",className:`h-auto p-2 ${n}`,children:fe.jsxs("div",{className:"flex items-center space-x-2",children:[fe.jsxs("div",{className:"hidden md:block text-left",children:[fe.jsx("p",{className:"text-sm font-medium",children:s.name}),fe.jsx("p",{className:"text-xs text-muted-foreground",children:h?.name||"N/A"})]}),fe.jsx("div",{className:"w-8 h-8 bg-primary rounded-full flex items-center justify-center",children:fe.jsx(o.User,{className:"h-4 w-4 text-primary-foreground"})}),fe.jsx(o.ChevronDown,{className:"h-4 w-4"})]})})}),fe.jsxs(jr,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[fe.jsxs(vr,{children:[fe.jsxs(wr,{children:[fe.jsx(o.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),fe.jsx(Nr,{children:x.map(e=>fe.jsxs(kr,{onClick:()=>g(e),className:e.alias===h?.alias?"bg-muted":"",children:[fe.jsx(o.Building2,{className:"mr-2 h-4 w-4"}),e.name,e.alias===h?.alias&&fe.jsx(lt,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},e.alias))})]}),fe.jsx(Ir,{}),fe.jsxs(kr,{onClick:u,children:[fe.jsx(o.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):fe.jsxs(ke,{className:n,children:[fe.jsx(Ce,{children:fe.jsx(Se,{className:"text-lg",children:"Informações do Usuário"})}),fe.jsxs(Ie,{className:"space-y-4",children:[fe.jsx(y,{}),fe.jsx(rs,{}),fe.jsxs(ve,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[fe.jsx(o.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Ci=e.createContext({});function Si({children:t,config:n}){const r=e.useMemo(()=>({navigation:n?.navigation,appName:n?.appName}),[n?.navigation,n?.appName]);return fe.jsx(Ci.Provider,{value:r,children:t})}function Ei(){return e.useContext(Ci)}function Ii(){const e=x.useLocation(),{navigation:t}=Ei();if(!t)return"Página";const n=t.find(t=>t.path===e.pathname);if(n)return n.label;const r=t.find(t=>e.pathname.startsWith(t.path+"/"));return r?.label||"Página"}function Ti(t,n){const[r,a]=e.useState(t),s=e.useRef(),i=e.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=void 0)},[]);return e.useEffect(()=>(i(),s.current=setTimeout(()=>{a(t)},n),i),[t,n,i]),[r,i]}const Ai=e.memo(function({actions:t}){const n=x.useLocation(),r=Ii(),{navigation:a,appName:s}=Ei(),{metadata:i}=da(),{companies:l,alias:c,isSearchVisible:u,clearSearch:d,refreshData:m,switchUnit:p}=qn(),f=c?l?.find(e=>e.alias===c)||l?.[0]||null:l?.[0]||null,[h,g]=x.useSearchParams(),[y,v]=e.useState(()=>h.get("search")||""),[b,w]=Ti(y,Nn.debounceDelay);e.useEffect(()=>{if(!u)return;const e=new URLSearchParams(h);b?(e.set("search",b),e.set("page","1")):e.delete("search"),g(e)},[b,g,u]);const N=a?.find(e=>e.path===n.pathname)||a?.find(e=>n.pathname.startsWith(e.path+"/")),j=i.title||r,k=i.subtitle||N?.complementaryText||"Detalhes do item";return fe.jsx("header",{className:"bg-white border-b border-gray-200 px-2 md:px-4 py-2",children:fe.jsxs("div",{className:"flex items-center gap-4",children:[fe.jsxs("div",{className:"flex-shrink-0",children:[fe.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[fe.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:j}),fe.jsx(lt,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:s||"Módulo"})]}),fe.jsx("p",{className:"text-sm text-muted-foreground truncate",children:k})]}),u&&fe.jsxs("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[fe.jsxs("div",{className:"relative flex-1",children:[fe.jsx(o.Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),fe.jsx(we,{placeholder:"/wiki"===n.pathname?"Buscar artigos...":"Buscar...",value:y,onChange:e=>(e=>{v(e)})(e.target.value),className:"w-full pl-10 pr-8"}),y&&fe.jsx(ve,{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:()=>{w(),v("");const e=new URLSearchParams(h);e.delete("search"),e.delete("page"),g(e)},title:"Limpar busca",children:fe.jsx(o.X,{size:14})})]}),fe.jsx(ve,{variant:"outline",size:"sm",onClick:m,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:fe.jsx(o.RefreshCw,{size:14})})]}),fe.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[t&&fe.jsx("div",{className:"flex items-center gap-2",children:t}),(void 0).VITE_WIKI_URL&&fe.jsx(ve,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>he((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),fe.jsx("div",{className:"text-sm",children:fe.jsx(ki,{variant:"dropdown",selectedUnit:f,onUnitChange:p})})]})]})})}),Pi=({key:e,enabled:t,checkFn:n,staleTime:r=3e5,gcTime:a=6e5})=>g.useQuery({queryKey:["permission",e],queryFn:n,enabled:t,staleTime:r,gcTime:a,retry:0,refetchOnWindowFocus:!1}),_i=(e={})=>{const{enabled:t=!0}=e,{alias:n}=qn();return g.useQuery({queryKey:["active-modules",n],queryFn:async()=>{if(!n)return[];const e=cn(),{data:t,error:r}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",n).eq("status","active").order("name");if(r){if(!fn.handleError(r))throw r;return[]}return t||[]},enabled:t&&!!n})},Di="forlogic-sidebar-pinned",Fi=()=>{try{const e=localStorage.getItem(Di);return!!e&&JSON.parse(e)}catch{return!1}},Ri=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]},Li=(void 0).VITE_SUPABASE_PROJECT_ID,Mi={logo:`https://${Li}.supabase.co/storage/v1/object/public/library-assets/logo.svg`,smallLogo:`https://${Li}.supabase.co/storage/v1/object/public/library-assets/small.svg`},Oi=Mi.logo,zi=Mi.smallLogo;function Ui({appName:e,isPinned:t,onPinToggle:n,open:r,dropdownOpen:a,onDropdownChange:s}){const{data:i,isLoading:l,error:c}=_i({enabled:a}),u=e=>{((e,t)=>{const n=e?.find(e=>e.url===t);n?.url&&window.open(n.url,"_blank")})(i,e)};return fe.jsxs(Is,{className:"p-0 gap-0",children:[fe.jsx("div",{className:"flex items-center justify-between h-[34px]",children:r?fe.jsxs(fe.Fragment,{children:[fe.jsx("div",{className:"flex items-center pl-[12px]",children:fe.jsx("img",{src:Mi.logo,alt:"Logo",className:"h-6 max-w-full object-contain"})}),fe.jsx("button",{onClick:n,className:"h-8 w-8 flex items-center justify-center rounded-md transition-colors duration-200 "+(t?"bg-primary text-primary-foreground":"hover:bg-muted text-muted-foreground"),children:fe.jsx(o.PanelLeft,{className:"h-4 w-4"})})]}):fe.jsx("div",{className:"flex items-center justify-center w-full h-[34px]",children:fe.jsx("img",{src:Mi.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),fe.jsx("div",{className:"mt-2 pt-0",children:fe.jsxs(hr,{onOpenChange:s,children:[fe.jsx(gr,{asChild:!0,children:r?fe.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:[fe.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[fe.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"}),fe.jsx("span",{className:"truncate group-data-[collapsible=icon]:hidden",children:e})]}),fe.jsx(o.ChevronDown,{className:"h-6 w-6 flex-shrink-0 text-muted-foreground"})]}):fe.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:fe.jsx(o.ChevronDown,{className:"h-6 w-6 text-muted-foreground"})})}),fe.jsx(jr,{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:l?fe.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-muted-foreground",children:[fe.jsx(o.Loader2,{className:"h-4 w-4 animate-spin"}),fe.jsx("span",{className:"text-sm",children:"Carregando módulos..."})]}):c?fe.jsxs("div",{className:"flex items-center space-x-2 py-3 px-3 text-destructive",children:[fe.jsx(o.AlertCircle,{className:"h-4 w-4"}),fe.jsx("span",{className:"text-sm",children:"Erro ao carregar módulos"})]}):i&&0!==i.length?fe.jsx("div",{className:"space-y-2",children:i.map((e,t)=>fe.jsx("div",{onClick:()=>u(e.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${Ri(t)} transition-colors duration-200\n `,children:fe.jsxs("div",{className:"flex items-center justify-between",children:[fe.jsx("span",{className:"font-medium text-foreground text-sm",children:e.name}),e.url&&fe.jsx(o.ExternalLink,{className:"h-4 w-4 text-muted-foreground"})]})},e.id))}):fe.jsx("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:"Nenhum módulo disponível"})})]})})]})}function Bi({direction:t="right",minWidth:n=224,maxWidth:r=384,defaultWidth:a=240,storageKey:s="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,c]=e.useState(()=>{if("undefined"==typeof window)return a;const e=localStorage.getItem(s);return e?parseInt(e):a}),[u,d]=e.useState(!1),m=e.useRef(null);e.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=e.useCallback(e=>{e.preventDefault(),d(!0)},[]);return e.useEffect(()=>{if(!u)return;const e=e=>{let a;a="left"===t?window.innerWidth-e.clientX:e.clientX,a=Math.max(n,Math.min(r,a)),c(a),i?.(a)},a=()=>{d(!1),localStorage.setItem(s,l.toString())};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[u,t,n,r,l,s,i]),e.useEffect(()=>{u?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect="")},[u,t]),{width:l,isDragging:u,dragRef:m,handleMouseDown:p}}const $i=e.forwardRef(({className:e,onMouseDown:t,isDragging:n,...r},a)=>fe.jsx("div",{ref:a,onMouseDown:t,className:ge("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-['']",n&&"bg-primary/40",e),...r}));function qi({config:t,customContent:n,resizable:r=!1,minWidth:a=224,maxWidth:s=384}={}){const{open:i,setOpen:l}=ws(),c=x.useLocation(),{alias:u,user:d}=qn(),[m,p]=e.useState(!1),[f,h]=e.useState(Fi),[g,y]=e.useState(!1),v=r?Bi({minWidth:a,maxWidth:s,storageKey:"app-sidebar-width",isOpen:i}):null;e.useEffect(()=>{l(!!f||!(!g&&!m))},[f,g,m,l]);const b=e=>c.pathname===e||c.pathname.startsWith(e+"/");return fe.jsxs(js,{collapsible:"icon",onMouseEnter:()=>{f||y(!0)},onMouseLeave:()=>{f||y(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:v&&i?{width:`${v.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[fe.jsx(Ui,{appName:t?.appName||"Título do módulo",isPinned:f,onPinToggle:()=>{const e=!f;h(e),(e=>{try{localStorage.setItem(Di,JSON.stringify(e))}catch{}})(e)},open:i,dropdownOpen:m,onDropdownChange:p}),fe.jsx(Ps,{children:n||fe.jsx(_s,{className:"p-0 mt-6",children:fe.jsx(Rs,{children:fe.jsx(Ls,{className:"space-y-2",children:fe.jsx(hs,{children:t?.navigation?.map((e,t)=>{const n=({item:e,index:t})=>{const r=`${e.path}-${t}-${u??"noalias"}-${d?.id??"nouser"}`,{data:a=!0,isLoading:s}=Pi({key:r,enabled:Boolean(e.permissionCheck&&u&&d?.id),checkFn:e.permissionCheck||(()=>Promise.resolve(!0))}),i=e.permissionCheck&&!a,l=s?o.Loader2:i?o.Lock:e.icon;i||e.complementaryText;return e.children&&e.children.length>0?fe.jsx(Oa,{defaultOpen:!0,className:"group/collapsible",children:fe.jsxs(Ms,{children:[fe.jsx(za,{asChild:!0,children:fe.jsx(zs,{size:"lg",className:"h-10",children:fe.jsxs("div",{className:"flex w-full items-center gap-3",children:[fe.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:fe.jsx(l,{className:"h-5 w-4"})}),fe.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:e.label}),fe.jsx(o.ChevronRight,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90 group-data-[collapsible=icon]:hidden"})]})})}),fe.jsx(Ua,{children:fe.jsx(qs,{children:e.children.map((e,t)=>fe.jsx(n,{item:e,index:t},e.path))})})]})},e.path):fe.jsx(Ms,{children:i||s?fe.jsxs(gs,{children:[fe.jsx(xs,{asChild:!0,children:fe.jsx(zs,{size:"lg",className:"h-10 opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:fe.jsxs("div",{className:"flex w-full items-center gap-3",children:[fe.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:fe.jsx(l,{className:"h-4 w-4 "+(s?"animate-spin":"")})}),fe.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:e.label})]})})}),fe.jsx(ys,{children:fe.jsx("p",{children:s?"Verificando acesso...":"Acesso restrito"})})]}):fe.jsx(zs,{asChild:!0,isActive:b(e.path),size:"lg",className:"h-10",children:fe.jsxs(x.Link,{to:e.path,className:"flex w-full items-center gap-3",children:[fe.jsx("span",{className:"grid place-items-center h-[34px] w-[34px] p-[5px]",children:fe.jsx(l,{className:"h-5 w-4"})}),fe.jsx("span",{className:"font-medium sidebar-text group-data-[collapsible=icon]:hidden",children:e.label})]})})},e.path)};return fe.jsx(n,{item:e,index:t},e.path)})})})})})}),r&&v&&i&&fe.jsx($i,{ref:v.dragRef,onMouseDown:v.handleMouseDown,isDragging:v.isDragging})]})}$i.displayName="ResizableRail";const Vi=e.memo(function({children:t,sidebar:n,sidebarConfig:r,showHeader:a=!0}){const s=e.useMemo(()=>n||fe.jsx(qi,{config:r}),[n,r]),i=e.useMemo(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return fe.jsx(Si,{config:r,children:fe.jsx(ua,{children:fe.jsx(Ns,{defaultOpen:!1,style:i,children:fe.jsxs("div",{className:"sidebar-container min-h-screen flex w-full",children:[s,fe.jsxs("main",{className:"flex-1 flex flex-col h-screen overflow-hidden",children:[a&&fe.jsx("div",{className:"flex-shrink-0 sticky top-0 z-10 bg-background",children:fe.jsx(Ai,{})}),fe.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:t})]})]})})})})});var Hi=Object.defineProperty,Wi=(e,t,n)=>((e,t,n)=>t in e?Hi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);class Qi extends e.Component{constructor(e){super(e),Wi(this,"copyErrorDetails",()=>{const e=tn.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),yt({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;tn.handleError(e,!1),this.setState({errorInfo:t})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const e=tn.getErrors().slice(0,2);return fe.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:fe.jsxs(ke,{className:"w-full max-w-2xl",children:[fe.jsxs(Ce,{className:"text-center",children:[fe.jsx("div",{className:"flex justify-center mb-4",children:fe.jsx(o.AlertTriangle,{className:"h-12 w-12 text-destructive"})}),fe.jsx(Se,{children:"Algo deu errado"})]}),fe.jsxs(Ie,{className:"space-y-4",children:[fe.jsx("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),fe.jsxs(Oa,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[fe.jsx(za,{asChild:!0,children:fe.jsxs(ve,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[fe.jsx(o.ChevronDown,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),fe.jsxs(Ua,{className:"mt-4 space-y-4",children:[fe.jsxs("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[fe.jsxs("div",{children:[fe.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),fe.jsxs("div",{className:"text-sm space-y-2",children:[fe.jsx("p",{className:"font-medium text-destructive",children:this.state.error?.message||"Erro desconhecido"}),this.state.error?.stack&&fe.jsx(Or,{className:"h-32 w-full rounded border bg-muted p-2",children:fe.jsx("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),e.length>0&&fe.jsxs("div",{className:"pt-3 border-t",children:[fe.jsx("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),fe.jsx("div",{className:"space-y-2",children:e.map((e,t)=>fe.jsx("div",{className:"text-sm p-2 rounded bg-muted/50",children:fe.jsxs("div",{className:"flex items-start gap-2",children:[fe.jsxs("span",{className:"font-medium text-muted-foreground shrink-0",children:[t+1,"."]}),fe.jsxs("div",{className:"flex-1 min-w-0",children:[fe.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:fe.jsxs("span",{className:"text-xs text-muted-foreground",children:["[",new Date(e.timestamp).toLocaleTimeString(),"]"]})}),fe.jsx("p",{className:"text-sm break-words",children:e.message})]})]})},e.id))})]})]}),fe.jsxs(ve,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[fe.jsx(o.Copy,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),fe.jsx(ve,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}class Ki{static async sendEmail(e){const t=cn(),{data:n,error:r}=await t.functions.invoke("send-email",{body:{template_code:e.templateCode,to:e.to,variables:e.variables,cc:e.cc,bcc:e.bcc,replyTo:e.replyTo}});if(r)throw r;return n}}const Xi=Ki;function Yi(){const[t,n]=e.useState([]),[r,a]=e.useState(!1),[s,o]=e.useState(null),[l,c]=e.useState(null);e.useEffect(()=>{u()},[]);const u=async()=>{try{const e=cn(),{data:t,error:r}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(r)throw r;o(t.threadId),n([{id:"initial",role:"assistant",content:"Olá! Como posso ajudá-lo hoje?",timestamp:new Date}])}catch(e){c("Erro ao inicializar conversa"),i.toast.error("Erro ao inicializar conversa")}},d=e.useCallback(async e=>{if(!s||!e.trim())return;const t={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};n(e=>[...e,t]),a(!0),c(null);try{const t=cn(),{data:r,error:a}=await t.functions.invoke("openai-chat",{body:{action:"sendMessage",threadId:s,message:e}});if(a)throw a;const{runId:i}=r,o=await(async e=>{if(!s)return!1;for(let n=0;n<60;n++)try{const t=cn(),{data:n,error:r}=await t.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:s,runId:e}});if(r)throw r;const{status:a}=n;if("completed"===a)return!0;if("failed"===a||"cancelled"===a)throw new Error("O assistente encontrou um erro");await new Promise(e=>setTimeout(e,1e3))}catch(t){throw t}throw new Error("Tempo limite excedido")})(i);o&&await(async()=>{if(s)try{const e=cn(),{data:t,error:r}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:s}});if(r)throw r;const a=t.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));n(a)}catch(e){throw e}})()}catch(r){const e=r instanceof Error?r.message:"Erro ao enviar mensagem";c(e),i.toast.error(e),n(e=>e.filter(e=>e.id!==t.id))}finally{a(!1)}},[s]);return{messages:t,isLoading:r,error:l,sendMessage:d,threadId:s}}function Gi(){}function Ji(){}const Zi=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,eo=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,to={};function no(e,t){return(to.jsx?eo:Zi).test(e)}const ro=/[ \t\n\f\r]/g;function ao(e){return""===e.replace(ro,"")}class so{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}}function io(e,t){const n={},r={};for(const a of e)Object.assign(n,a.property),Object.assign(r,a.normal);return new so(n,r,t)}function oo(e){return e.toLowerCase()}so.prototype.normal={},so.prototype.property={},so.prototype.space=void 0;class lo{constructor(e,t){this.attribute=t,this.property=e}}lo.prototype.attribute="",lo.prototype.booleanish=!1,lo.prototype.boolean=!1,lo.prototype.commaOrSpaceSeparated=!1,lo.prototype.commaSeparated=!1,lo.prototype.defined=!1,lo.prototype.mustUseProperty=!1,lo.prototype.number=!1,lo.prototype.overloadedBoolean=!1,lo.prototype.property="",lo.prototype.spaceSeparated=!1,lo.prototype.space=void 0;let co=0;const uo=yo(),mo=yo(),po=yo(),fo=yo(),ho=yo(),go=yo(),xo=yo();function yo(){return 2**++co}var vo=Object.freeze({__proto__:null,boolean:uo,booleanish:mo,commaOrSpaceSeparated:xo,commaSeparated:go,number:fo,overloadedBoolean:po,spaceSeparated:ho});const bo=Object.keys(vo);class wo extends lo{constructor(e,t,n,r){let a=-1;if(super(e,t),No(this,"space",r),"number"==typeof n)for(;++a<bo.length;){const e=bo[a];No(this,bo[a],(n&vo[e])===vo[e])}}}function No(e,t,n){n&&(e[t]=n)}function jo(e){const t={},n={};for(const[r,a]of Object.entries(e.properties)){const s=new wo(r,e.transform(e.attributes||{},r),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(s.mustUseProperty=!0),t[r]=s,n[oo(r)]=r,n[oo(s.attribute)]=r}return new so(t,n,e.space)}wo.prototype.defined=!0;const ko=jo({properties:{ariaActiveDescendant:null,ariaAtomic:mo,ariaAutoComplete:null,ariaBusy:mo,ariaChecked:mo,ariaColCount:fo,ariaColIndex:fo,ariaColSpan:fo,ariaControls:ho,ariaCurrent:null,ariaDescribedBy:ho,ariaDetails:null,ariaDisabled:mo,ariaDropEffect:ho,ariaErrorMessage:null,ariaExpanded:mo,ariaFlowTo:ho,ariaGrabbed:mo,ariaHasPopup:null,ariaHidden:mo,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ho,ariaLevel:fo,ariaLive:null,ariaModal:mo,ariaMultiLine:mo,ariaMultiSelectable:mo,ariaOrientation:null,ariaOwns:ho,ariaPlaceholder:null,ariaPosInSet:fo,ariaPressed:mo,ariaReadOnly:mo,ariaRelevant:null,ariaRequired:mo,ariaRoleDescription:ho,ariaRowCount:fo,ariaRowIndex:fo,ariaRowSpan:fo,ariaSelected:mo,ariaSetSize:fo,ariaSort:null,ariaValueMax:fo,ariaValueMin:fo,ariaValueNow:fo,ariaValueText:null,role:null},transform:(e,t)=>"role"===t?t:"aria-"+t.slice(4).toLowerCase()});function Co(e,t){return t in e?e[t]:t}function So(e,t){return Co(e,t.toLowerCase())}const Eo=jo({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:go,acceptCharset:ho,accessKey:ho,action:null,allow:null,allowFullScreen:uo,allowPaymentRequest:uo,allowUserMedia:uo,alt:null,as:null,async:uo,autoCapitalize:null,autoComplete:ho,autoFocus:uo,autoPlay:uo,blocking:ho,capture:null,charSet:null,checked:uo,cite:null,className:ho,cols:fo,colSpan:null,content:null,contentEditable:mo,controls:uo,controlsList:ho,coords:fo|go,crossOrigin:null,data:null,dateTime:null,decoding:null,default:uo,defer:uo,dir:null,dirName:null,disabled:uo,download:po,draggable:mo,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:uo,formTarget:null,headers:ho,height:fo,hidden:po,high:fo,href:null,hrefLang:null,htmlFor:ho,httpEquiv:ho,id:null,imageSizes:null,imageSrcSet:null,inert:uo,inputMode:null,integrity:null,is:null,isMap:uo,itemId:null,itemProp:ho,itemRef:ho,itemScope:uo,itemType:ho,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:uo,low:fo,manifest:null,max:null,maxLength:fo,media:null,method:null,min:null,minLength:fo,multiple:uo,muted:uo,name:null,nonce:null,noModule:uo,noValidate:uo,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:uo,optimum:fo,pattern:null,ping:ho,placeholder:null,playsInline:uo,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:uo,referrerPolicy:null,rel:ho,required:uo,reversed:uo,rows:fo,rowSpan:fo,sandbox:ho,scope:null,scoped:uo,seamless:uo,selected:uo,shadowRootClonable:uo,shadowRootDelegatesFocus:uo,shadowRootMode:null,shape:null,size:fo,sizes:null,slot:null,span:fo,spellCheck:mo,src:null,srcDoc:null,srcLang:null,srcSet:null,start:fo,step:null,style:null,tabIndex:fo,target:null,title:null,translate:null,type:null,typeMustMatch:uo,useMap:null,value:mo,width:fo,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ho,axis:null,background:null,bgColor:null,border:fo,borderColor:null,bottomMargin:fo,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:uo,declare:uo,event:null,face:null,frame:null,frameBorder:null,hSpace:fo,leftMargin:fo,link:null,longDesc:null,lowSrc:null,marginHeight:fo,marginWidth:fo,noResize:uo,noHref:uo,noShade:uo,noWrap:uo,object:null,profile:null,prompt:null,rev:null,rightMargin:fo,rules:null,scheme:null,scrolling:mo,standby:null,summary:null,text:null,topMargin:fo,valueType:null,version:null,vAlign:null,vLink:null,vSpace:fo,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:uo,disableRemotePlayback:uo,prefix:null,property:null,results:fo,security:null,unselectable:null},space:"html",transform:So}),Io=jo({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:xo,accentHeight:fo,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:fo,amplitude:fo,arabicForm:null,ascent:fo,attributeName:null,attributeType:null,azimuth:fo,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:fo,by:null,calcMode:null,capHeight:fo,className:ho,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:fo,diffuseConstant:fo,direction:null,display:null,dur:null,divisor:fo,dominantBaseline:null,download:uo,dx:null,dy:null,edgeMode:null,editable:null,elevation:fo,enableBackground:null,end:null,event:null,exponent:fo,externalResourcesRequired:null,fill:null,fillOpacity:fo,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:go,g2:go,glyphName:go,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:fo,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:fo,horizOriginX:fo,horizOriginY:fo,id:null,ideographic:fo,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:fo,k:fo,k1:fo,k2:fo,k3:fo,k4:fo,kernelMatrix:xo,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:fo,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:fo,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:fo,overlineThickness:fo,paintOrder:null,panose1:null,path:null,pathLength:fo,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ho,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:fo,pointsAtY:fo,pointsAtZ:fo,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:xo,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:xo,rev:xo,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:xo,requiredFeatures:xo,requiredFonts:xo,requiredFormats:xo,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:fo,specularExponent:fo,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:fo,strikethroughThickness:fo,string:null,stroke:null,strokeDashArray:xo,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:fo,strokeOpacity:fo,strokeWidth:null,style:null,surfaceScale:fo,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:xo,tabIndex:fo,tableValues:null,target:null,targetX:fo,targetY:fo,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:xo,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:fo,underlineThickness:fo,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:fo,values:null,vAlphabetic:fo,vMathematical:fo,vectorEffect:null,vHanging:fo,vIdeographic:fo,version:null,vertAdvY:fo,vertOriginX:fo,vertOriginY:fo,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:fo,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Co}),To=jo({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform:(e,t)=>"xlink:"+t.slice(5).toLowerCase()}),Ao=jo({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:So}),Po=jo({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform:(e,t)=>"xml:"+t.slice(3).toLowerCase()}),_o={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Do=/[A-Z]/g,Fo=/-[a-z]/g,Ro=/^data[-\w.:]+$/i;function Lo(e){return"-"+e.toLowerCase()}function Mo(e){return e.charAt(1).toUpperCase()}const Oo=io([ko,Eo,To,Ao,Po],"html"),zo=io([ko,Io,To,Ao,Po],"svg");var Uo,Bo,$o,qo={};function Vo(){if($o)return qo;$o=1;var e=qo&&qo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(qo,"__esModule",{value:!0}),qo.default=function(e,n){let r=null;if(!e||"string"!=typeof e)return r;const a=(0,t.default)(e),s="function"==typeof n;return a.forEach(e=>{if("declaration"!==e.type)return;const{property:t,value:a}=e;s?n(t,a,e):a&&(r=r||{},r[t]=a)}),r};const t=e(function(){if(Bo)return Uo;Bo=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,i=/^[;\s]*/,o=/^\s+|\s+$/g,l="";function c(e){return e?e.replace(o,l):l}return Uo=function(o,u){if("string"!=typeof o)throw new TypeError("First argument must be a string");if(!o)return[];u=u||{};var d=1,m=1;function p(e){var n=e.match(t);n&&(d+=n.length);var r=e.lastIndexOf("\n");m=~r?e.length-r:m+e.length}function f(){var e={line:d,column:m};return function(t){return t.position=new h(e),y(),t}}function h(e){this.start=e,this.end={line:d,column:m},this.source=u.source}function g(e){var t=new Error(u.source+":"+d+":"+m+": "+e);if(t.reason=e,t.filename=u.source,t.line=d,t.column=m,t.source=o,!u.silent)throw t}function x(e){var t=e.exec(o);if(t){var n=t[0];return p(n),o=o.slice(n.length),t}}function y(){x(n)}function v(e){var t;for(e=e||[];t=b();)!1!==t&&e.push(t);return e}function b(){var e=f();if("/"==o.charAt(0)&&"*"==o.charAt(1)){for(var t=2;l!=o.charAt(t)&&("*"!=o.charAt(t)||"/"!=o.charAt(t+1));)++t;if(t+=2,l===o.charAt(t-1))return g("End of comment missing");var n=o.slice(2,t-2);return m+=2,p(n),o=o.slice(t),m+=2,e({type:"comment",comment:n})}}function w(){var t=f(),n=x(r);if(n){if(b(),!x(a))return g("property missing ':'");var o=x(s),u=t({type:"declaration",property:c(n[0].replace(e,l)),value:o?c(o[0].replace(e,l)):l});return x(i),u}}return h.prototype.content=o,y(),function(){var e,t=[];for(v(t);e=w();)!1!==e&&(t.push(e),v(t));return t}()},Uo}());return qo}var Ho,Wo,Qo,Ko={};function Xo(){if(Ho)return Ko;Ho=1,Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,s=function(e,t){return t.toUpperCase()},i=function(e,t){return"".concat(t,"-")};return Ko.camelCase=function(o,l){return void 0===l&&(l={}),function(t){return!t||n.test(t)||e.test(t)}(o)?o:(o=o.toLowerCase(),(o=l.reactCompat?o.replace(a,i):o.replace(r,i)).replace(t,s))},Ko}var Yo=function(){if(Qo)return Wo;Qo=1;var e=(Wo&&Wo.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(Vo()),t=Xo();function n(n,r){var a={};return n&&"string"==typeof n?((0,e.default)(n,function(e,n){e&&n&&(a[(0,t.camelCase)(e,r)]=n)}),a):a}return n.default=n,Wo=n}(),Go=ie(Yo);const Jo=el("end"),Zo=el("start");function el(e){return function(t){const n=t&&t.position&&t.position[e]||{};if("number"==typeof n.line&&n.line>0&&"number"==typeof n.column&&n.column>0)return{line:n.line,column:n.column,offset:"number"==typeof n.offset&&n.offset>-1?n.offset:void 0}}}function tl(e){return e&&"object"==typeof e?"position"in e||"type"in e?rl(e.position):"start"in e||"end"in e?rl(e):"line"in e||"column"in e?nl(e):"":""}function nl(e){return al(e&&e.line)+":"+al(e&&e.column)}function rl(e){return nl(e&&e.start)+"-"+nl(e&&e.end)}function al(e){return e&&"number"==typeof e?e:1}class sl extends Error{constructor(e,t,n){super(),"string"==typeof t&&(n=t,t=void 0);let r="",a={},s=!1;if(t&&(a="line"in t&&"column"in t||"start"in t&&"end"in t?{place:t}:"type"in t?{ancestors:[t],place:t.position}:{...t}),"string"==typeof e?r=e:!a.cause&&e&&(s=!0,r=e.message,a.cause=e),!a.ruleId&&!a.source&&"string"==typeof n){const e=n.indexOf(":");-1===e?a.ruleId=n:(a.source=n.slice(0,e),a.ruleId=n.slice(e+1))}if(!a.place&&a.ancestors&&a.ancestors){const e=a.ancestors[a.ancestors.length-1];e&&(a.place=e.position)}const i=a.place&&"start"in a.place?a.place.start:a.place;this.ancestors=a.ancestors||void 0,this.cause=a.cause||void 0,this.column=i?i.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=i?i.line:void 0,this.name=tl(a.place)||"1:1",this.place=a.place||void 0,this.reason=this.message,this.ruleId=a.ruleId||void 0,this.source=a.source||void 0,this.stack=s&&a.cause&&"string"==typeof a.cause.stack?a.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}sl.prototype.file="",sl.prototype.name="",sl.prototype.reason="",sl.prototype.message="",sl.prototype.stack="",sl.prototype.column=void 0,sl.prototype.line=void 0,sl.prototype.ancestors=void 0,sl.prototype.cause=void 0,sl.prototype.fatal=void 0,sl.prototype.place=void 0,sl.prototype.ruleId=void 0,sl.prototype.source=void 0;const il={}.hasOwnProperty,ol=new Map,ll=/[A-Z]/g,cl=new Set(["table","tbody","thead","tfoot","tr"]),ul=new Set(["td","th"]),dl="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function ml(e,t){if(!t||void 0===t.Fragment)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if("function"!=typeof t.jsxDEV)throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=function(e,t){return n;function n(n,r,a,s){const i=Array.isArray(a.children),o=Zo(n);return t(r,a,s,i,{columnNumber:o?o.column-1:void 0,fileName:e,lineNumber:o?o.line:void 0},void 0)}}(n,t.jsxDEV)}else{if("function"!=typeof t.jsx)throw new TypeError("Expected `jsx` in production options");if("function"!=typeof t.jsxs)throw new TypeError("Expected `jsxs` in production options");r=function(e,t,n){return r;function r(e,r,a,s){const i=Array.isArray(a.children)?n:t;return s?i(r,a,s):i(r,a)}}(0,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:!1!==t.passKeys,passNode:t.passNode||!1,schema:"svg"===t.space?zo:Oo,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:!1!==t.tableCellAlignToStyle},s=pl(a,e,void 0);return s&&"string"!=typeof s?s:a.create(e,a.Fragment,{children:s||void 0},void 0)}function pl(e,t,n){return"element"===t.type?function(e,t,n){const r=e.schema;let a=r;"svg"===t.tagName.toLowerCase()&&"html"===r.space&&(a=zo,e.schema=a);e.ancestors.push(t);const s=yl(e,t.tagName,!1),i=function(e,t){const n={};let r,a;for(a in t.properties)if("children"!==a&&il.call(t.properties,a)){const s=xl(e,a,t.properties[a]);if(s){const[a,i]=s;e.tableCellAlignToStyle&&"align"===a&&"string"==typeof i&&ul.has(t.tagName)?r=i:n[a]=i}}if(r){(n.style||(n.style={}))["css"===e.stylePropertyNameCase?"text-align":"textAlign"]=r}return n}(e,t);let o=gl(e,t);cl.has(t.tagName)&&(o=o.filter(function(e){return"string"!=typeof e||!("object"==typeof(t=e)?"text"===t.type&&ao(t.value):ao(t));var t}));return fl(e,i,s,t),hl(i,o),e.ancestors.pop(),e.schema=r,e.create(t,s,i,n)}(e,t,n):"mdxFlowExpression"===t.type||"mdxTextExpression"===t.type?function(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}vl(e,t.position)}(e,t):"mdxJsxFlowElement"===t.type||"mdxJsxTextElement"===t.type?function(e,t,n){const r=e.schema;let a=r;"svg"===t.name&&"html"===r.space&&(a=zo,e.schema=a);e.ancestors.push(t);const s=null===t.name?e.Fragment:yl(e,t.name,!0),i=function(e,t){const n={};for(const r of t.attributes)if("mdxJsxExpressionAttribute"===r.type)if(r.data&&r.data.estree&&e.evaluater){const t=r.data.estree.body[0];Gi(t.type);const a=t.expression;Gi(a.type);const s=a.properties[0];Gi(s.type),Object.assign(n,e.evaluater.evaluateExpression(s.argument))}else vl(e,t.position);else{const a=r.name;let s;if(r.value&&"object"==typeof r.value)if(r.value.data&&r.value.data.estree&&e.evaluater){const t=r.value.data.estree.body[0];Gi(t.type),s=e.evaluater.evaluateExpression(t.expression)}else vl(e,t.position);else s=null===r.value||r.value;n[a]=s}return n}(e,t),o=gl(e,t);return fl(e,i,s,t),hl(i,o),e.ancestors.pop(),e.schema=r,e.create(t,s,i,n)}(e,t,n):"mdxjsEsm"===t.type?function(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);vl(e,t.position)}(e,t):"root"===t.type?function(e,t,n){const r={};return hl(r,gl(e,t)),e.create(t,e.Fragment,r,n)}(e,t,n):"text"===t.type?function(e,t){return t.value}(0,t):void 0}function fl(e,t,n,r){"string"!=typeof n&&n!==e.Fragment&&e.passNode&&(t.node=r)}function hl(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function gl(e,t){const n=[];let r=-1;const a=e.passKeys?new Map:ol;for(;++r<t.children.length;){const s=t.children[r];let i;if(e.passKeys){const e="element"===s.type?s.tagName:"mdxJsxFlowElement"===s.type||"mdxJsxTextElement"===s.type?s.name:void 0;if(e){const t=a.get(e)||0;i=e+"-"+t,a.set(e,t+1)}}const o=pl(e,s,i);void 0!==o&&n.push(o)}return n}function xl(e,t,n){const r=function(e,t){const n=oo(t);let r=t,a=lo;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&"data"===n.slice(0,4)&&Ro.test(t)){if("-"===t.charAt(4)){const e=t.slice(5).replace(Fo,Mo);r="data"+e.charAt(0).toUpperCase()+e.slice(1)}else{const e=t.slice(4);if(!Fo.test(e)){let n=e.replace(Do,Lo);"-"!==n.charAt(0)&&(n="-"+n),t="data"+n}}a=wo}return new a(r,t)}(e.schema,t);if(!(null==n||"number"==typeof n&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?function(e){const t={};return(""===e[e.length-1]?[...e,""]:e).join((t.padRight?" ":"")+","+(!1===t.padLeft?"":" ")).trim()}(n):n.join(" ").trim()),"style"===r.property){let t="object"==typeof n?n:function(e,t){try{return Go(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const t=n,r=new sl("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:t,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=dl+"#cannot-parse-style-attribute",r}}(e,String(n));return"css"===e.stylePropertyNameCase&&(t=function(e){const t={};let n;for(n in e)il.call(e,n)&&(t[bl(n)]=e[n]);return t}(t)),["style",t]}return["react"===e.elementAttributeNameCase&&r.space?_o[r.property]||r.property:r.attribute,n]}}function yl(e,t,n){let r;if(n)if(t.includes(".")){const e=t.split(".");let n,a=-1;for(;++a<e.length;){const t=no(e[a])?{type:"Identifier",name:e[a]}:{type:"Literal",value:e[a]};n=n?{type:"MemberExpression",object:n,property:t,computed:Boolean(a&&"Literal"===t.type),optional:!1}:t}r=n}else r=no(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};else r={type:"Literal",value:t};if("Literal"===r.type){const t=r.value;return il.call(e.components,t)?e.components[t]:t}if(e.evaluater)return e.evaluater.evaluateExpression(r);vl(e)}function vl(e,t){const n=new sl("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=dl+"#cannot-handle-mdx-estrees-without-createevaluater",n}function bl(e){let t=e.replace(ll,wl);return"ms-"===t.slice(0,3)&&(t="-"+t),t}function wl(e){return"-"+e.toLowerCase()}const Nl={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},jl={};function kl(e,t){return Cl(e,"boolean"!=typeof jl.includeImageAlt||jl.includeImageAlt,"boolean"!=typeof jl.includeHtml||jl.includeHtml)}function Cl(e,t,n){if(function(e){return Boolean(e&&"object"==typeof e)}(e)){if("value"in e)return"html"!==e.type||n?e.value:"";if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Sl(e.children,t,n)}return Array.isArray(e)?Sl(e,t,n):""}function Sl(e,t,n){const r=[];let a=-1;for(;++a<e.length;)r[a]=Cl(e[a],t,n);return r.join("")}const El=document.createElement("i");function Il(e){const t="&"+e+";";El.innerHTML=t;const n=El.textContent;return(59!==n.charCodeAt(n.length-1)||"semi"===e)&&(n!==t&&n)}function Tl(e,t,n,r){const a=e.length;let s,i=0;if(t=t<0?-t>a?0:a+t:t>a?a:t,n=n>0?n:0,r.length<1e4)s=Array.from(r),s.unshift(t,n),e.splice(...s);else for(n&&e.splice(t,n);i<r.length;)s=r.slice(i,i+1e4),s.unshift(t,0),e.splice(...s),i+=1e4,t+=1e4}function Al(e,t){return e.length>0?(Tl(e,e.length,0,t),e):t}const Pl={}.hasOwnProperty;function _l(e){const t={};let n=-1;for(;++n<e.length;)Dl(t,e[n]);return t}function Dl(e,t){let n;for(n in t){const r=(Pl.call(e,n)?e[n]:void 0)||(e[n]={}),a=t[n];let s;if(a)for(s in a){Pl.call(r,s)||(r[s]=[]);const e=a[s];Fl(r[s],Array.isArray(e)?e:e?[e]:[])}}}function Fl(e,t){let n=-1;const r=[];for(;++n<t.length;)("after"===t[n].add?e:r).push(t[n]);Tl(e,0,0,r)}function Rl(e,t){const n=Number.parseInt(e,t);return n<9||11===n||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||!(65535&~n)||65534==(65535&n)||n>1114111?"�":String.fromCodePoint(n)}function Ll(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Ml=Xl(/[A-Za-z]/),Ol=Xl(/[\dA-Za-z]/),zl=Xl(/[#-'*+\--9=?A-Z^-~]/);function Ul(e){return null!==e&&(e<32||127===e)}const Bl=Xl(/\d/),$l=Xl(/[\dA-Fa-f]/),ql=Xl(/[!-/:-@[-`{-~]/);function Vl(e){return null!==e&&e<-2}function Hl(e){return null!==e&&(e<0||32===e)}function Wl(e){return-2===e||-1===e||32===e}const Ql=Xl(/\p{P}|\p{S}/u),Kl=Xl(/\s/);function Xl(e){return function(t){return null!==t&&t>-1&&e.test(String.fromCharCode(t))}}function Yl(e){const t=[];let n=-1,r=0,a=0;for(;++n<e.length;){const s=e.charCodeAt(n);let i="";if(37===s&&Ol(e.charCodeAt(n+1))&&Ol(e.charCodeAt(n+2)))a=2;else if(s<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(s))||(i=String.fromCharCode(s));else if(s>55295&&s<57344){const t=e.charCodeAt(n+1);s<56320&&t>56319&&t<57344?(i=String.fromCharCode(s,t),a=1):i="�"}else i=String.fromCharCode(s);i&&(t.push(e.slice(r,n),encodeURIComponent(i)),r=n+a+1,i=""),a&&(n+=a,a=0)}return t.join("")+e.slice(r)}function Gl(e,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let s=0;return function(r){if(Wl(r))return e.enter(n),i(r);return t(r)};function i(r){return Wl(r)&&s++<a?(e.consume(r),i):(e.exit(n),t(r))}}const Jl={tokenize:function(e){const t=e.attempt(this.parser.constructs.contentInitial,function(n){if(null===n)return void e.consume(n);return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Gl(e,t,"linePrefix")},function(t){return e.enter("paragraph"),r(t)});let n;return t;function r(t){const r=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=r),n=r,a(t)}function a(t){return null===t?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(t)):Vl(t)?(e.consume(t),e.exit("chunkText"),r):(e.consume(t),a)}}};const Zl={tokenize:function(e){const t=this,n=[];let r,a,s,i=0;return o;function o(r){if(i<n.length){const a=n[i];return t.containerState=a[1],e.attempt(a[0].continuation,l,c)(r)}return c(r)}function l(e){if(i++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,r&&y();const n=t.events.length;let a,s=n;for(;s--;)if("exit"===t.events[s][0]&&"chunkFlow"===t.events[s][1].type){a=t.events[s][1].end;break}x(i);let o=n;for(;o<t.events.length;)t.events[o][1].end={...a},o++;return Tl(t.events,s+1,0,t.events.slice(n)),t.events.length=o,c(e)}return o(e)}function c(a){if(i===n.length){if(!r)return m(a);if(r.currentConstruct&&r.currentConstruct.concrete)return f(a);t.interrupt=Boolean(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(ec,u,d)(a)}function u(e){return r&&y(),x(i),m(e)}function d(e){return t.parser.lazy[t.now().line]=i!==n.length,s=t.now().offset,f(e)}function m(n){return t.containerState={},e.attempt(ec,p,f)(n)}function p(e){return i++,n.push([t.currentConstruct,t.containerState]),m(e)}function f(n){return null===n?(r&&y(),x(0),void e.consume(n)):(r=r||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:a}),h(n))}function h(n){return null===n?(g(e.exit("chunkFlow"),!0),x(0),void e.consume(n)):Vl(n)?(e.consume(n),g(e.exit("chunkFlow")),i=0,t.interrupt=void 0,o):(e.consume(n),h)}function g(e,n){const o=t.sliceStream(e);if(n&&o.push(null),e.previous=a,a&&(a.next=e),a=e,r.defineSkip(e.start),r.write(o),t.parser.lazy[e.start.line]){let e=r.events.length;for(;e--;)if(r.events[e][1].start.offset<s&&(!r.events[e][1].end||r.events[e][1].end.offset>s))return;const n=t.events.length;let a,o,l=n;for(;l--;)if("exit"===t.events[l][0]&&"chunkFlow"===t.events[l][1].type){if(a){o=t.events[l][1].end;break}a=!0}for(x(i),e=n;e<t.events.length;)t.events[e][1].end={...o},e++;Tl(t.events,l+1,0,t.events.slice(n)),t.events.length=e}}function x(r){let a=n.length;for(;a-- >r;){const r=n[a];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function y(){r.write([null]),a=void 0,r=void 0,t.containerState._closeFlow=void 0}}},ec={tokenize:function(e,t,n){return Gl(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}};function tc(e){return null===e||Hl(e)||Kl(e)?1:Ql(e)?2:void 0}function nc(e,t,n){const r=[];let a=-1;for(;++a<e.length;){const s=e[a].resolveAll;s&&!r.includes(s)&&(t=s(t,n),r.push(s))}return t}const rc={name:"attention",resolveAll:function(e,t){let n,r,a,s,i,o,l,c,u=-1;for(;++u<e.length;)if("enter"===e[u][0]&&"attentionSequence"===e[u][1].type&&e[u][1]._close)for(n=u;n--;)if("exit"===e[n][0]&&"attentionSequence"===e[n][1].type&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[u][1]).charCodeAt(0)){if((e[n][1]._close||e[u][1]._open)&&(e[u][1].end.offset-e[u][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[u][1].end.offset-e[u][1].start.offset)%3))continue;o=e[n][1].end.offset-e[n][1].start.offset>1&&e[u][1].end.offset-e[u][1].start.offset>1?2:1;const d={...e[n][1].end},m={...e[u][1].start};ac(d,-o),ac(m,o),s={type:o>1?"strongSequence":"emphasisSequence",start:d,end:{...e[n][1].end}},i={type:o>1?"strongSequence":"emphasisSequence",start:{...e[u][1].start},end:m},a={type:o>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[u][1].start}},r={type:o>1?"strong":"emphasis",start:{...s.start},end:{...i.end}},e[n][1].end={...s.start},e[u][1].start={...i.end},l=[],e[n][1].end.offset-e[n][1].start.offset&&(l=Al(l,[["enter",e[n][1],t],["exit",e[n][1],t]])),l=Al(l,[["enter",r,t],["enter",s,t],["exit",s,t],["enter",a,t]]),l=Al(l,nc(t.parser.constructs.insideSpan.null,e.slice(n+1,u),t)),l=Al(l,[["exit",a,t],["enter",i,t],["exit",i,t],["exit",r,t]]),e[u][1].end.offset-e[u][1].start.offset?(c=2,l=Al(l,[["enter",e[u][1],t],["exit",e[u][1],t]])):c=0,Tl(e,n-1,u-n+3,l),u=n+l.length-c-2;break}u=-1;for(;++u<e.length;)"attentionSequence"===e[u][1].type&&(e[u][1].type="data");return e},tokenize:function(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,a=tc(r);let s;return function(t){return s=t,e.enter("attentionSequence"),i(t)};function i(o){if(o===s)return e.consume(o),i;const l=e.exit("attentionSequence"),c=tc(o),u=!c||2===c&&a||n.includes(o),d=!a||2===a&&c||n.includes(r);return l._open=Boolean(42===s?u:u&&(a||!d)),l._close=Boolean(42===s?d:d&&(c||!u)),t(o)}}};function ac(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const sc={name:"autolink",tokenize:function(e,t,n){let r=0;return function(t){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(t),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),a};function a(t){return Ml(t)?(e.consume(t),s):64===t?n(t):l(t)}function s(e){return 43===e||45===e||46===e||Ol(e)?(r=1,i(e)):l(e)}function i(t){return 58===t?(e.consume(t),r=0,o):(43===t||45===t||46===t||Ol(t))&&r++<32?(e.consume(t),i):(r=0,l(t))}function o(r){return 62===r?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(r),e.exit("autolinkMarker"),e.exit("autolink"),t):null===r||32===r||60===r||Ul(r)?n(r):(e.consume(r),o)}function l(t){return 64===t?(e.consume(t),c):zl(t)?(e.consume(t),l):n(t)}function c(e){return Ol(e)?u(e):n(e)}function u(n){return 46===n?(e.consume(n),r=0,c):62===n?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(n),e.exit("autolinkMarker"),e.exit("autolink"),t):d(n)}function d(t){if((45===t||Ol(t))&&r++<63){const n=45===t?d:u;return e.consume(t),n}return n(t)}}};const ic={partial:!0,tokenize:function(e,t,n){return function(t){return Wl(t)?Gl(e,r,"linePrefix")(t):r(t)};function r(e){return null===e||Vl(e)?t(e):n(e)}}};const oc={continuation:{tokenize:function(e,t,n){const r=this;return function(t){if(Wl(t))return Gl(e,a,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t);return a(t)};function a(r){return e.attempt(oc,t,n)(r)}}},exit:function(e){e.exit("blockQuote")},name:"blockQuote",tokenize:function(e,t,n){const r=this;return function(t){if(62===t){const n=r.containerState;return n.open||(e.enter("blockQuote",{_container:!0}),n.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(t),e.exit("blockQuoteMarker"),a}return n(t)};function a(n){return Wl(n)?(e.enter("blockQuotePrefixWhitespace"),e.consume(n),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(n))}}};const lc={name:"characterEscape",tokenize:function(e,t,n){return function(t){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(t),e.exit("escapeMarker"),r};function r(r){return ql(r)?(e.enter("characterEscapeValue"),e.consume(r),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(r)}}};const cc={name:"characterReference",tokenize:function(e,t,n){const r=this;let a,s,i=0;return function(t){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(t),e.exit("characterReferenceMarker"),o};function o(t){return 35===t?(e.enter("characterReferenceMarkerNumeric"),e.consume(t),e.exit("characterReferenceMarkerNumeric"),l):(e.enter("characterReferenceValue"),a=31,s=Ol,c(t))}function l(t){return 88===t||120===t?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(t),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),a=6,s=$l,c):(e.enter("characterReferenceValue"),a=7,s=Bl,c(t))}function c(o){if(59===o&&i){const a=e.exit("characterReferenceValue");return s!==Ol||Il(r.sliceSerialize(a))?(e.enter("characterReferenceMarker"),e.consume(o),e.exit("characterReferenceMarker"),e.exit("characterReference"),t):n(o)}return s(o)&&i++<a?(e.consume(o),c):n(o)}}};const uc={partial:!0,tokenize:function(e,t,n){const r=this;return function(t){if(null===t)return n(t);return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),a};function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}},dc={concrete:!0,name:"codeFenced",tokenize:function(e,t,n){const r=this,a={partial:!0,tokenize:function(e,t,n){let a=0;return i;function i(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),l}function l(t){return e.enter("codeFencedFence"),Wl(t)?Gl(e,c,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):c(t)}function c(t){return t===s?(e.enter("codeFencedFenceSequence"),u(t)):n(t)}function u(t){return t===s?(a++,e.consume(t),u):a>=o?(e.exit("codeFencedFenceSequence"),Wl(t)?Gl(e,d,"whitespace")(t):d(t)):n(t)}function d(r){return null===r||Vl(r)?(e.exit("codeFencedFence"),t(r)):n(r)}}};let s,i=0,o=0;return function(t){return function(t){const n=r.events[r.events.length-1];return i=n&&"linePrefix"===n[1].type?n[2].sliceSerialize(n[1],!0).length:0,s=t,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),l(t)}(t)};function l(t){return t===s?(o++,e.consume(t),l):o<3?n(t):(e.exit("codeFencedFenceSequence"),Wl(t)?Gl(e,c,"whitespace")(t):c(t))}function c(n){return null===n||Vl(n)?(e.exit("codeFencedFence"),r.interrupt?t(n):e.check(uc,p,y)(n)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),u(n))}function u(t){return null===t||Vl(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(t)):Wl(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Gl(e,d,"whitespace")(t)):96===t&&t===s?n(t):(e.consume(t),u)}function d(t){return null===t||Vl(t)?c(t):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),m(t))}function m(t){return null===t||Vl(t)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(t)):96===t&&t===s?n(t):(e.consume(t),m)}function p(t){return e.attempt(a,y,f)(t)}function f(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),h}function h(t){return i>0&&Wl(t)?Gl(e,g,"linePrefix",i+1)(t):g(t)}function g(t){return null===t||Vl(t)?e.check(uc,p,y)(t):(e.enter("codeFlowValue"),x(t))}function x(t){return null===t||Vl(t)?(e.exit("codeFlowValue"),g(t)):(e.consume(t),x)}function y(n){return e.exit("codeFenced"),t(n)}}};const mc={name:"codeIndented",tokenize:function(e,t,n){const r=this;return function(t){return e.enter("codeIndented"),Gl(e,a,"linePrefix",5)(t)};function a(e){const t=r.events[r.events.length-1];return t&&"linePrefix"===t[1].type&&t[2].sliceSerialize(t[1],!0).length>=4?s(e):n(e)}function s(t){return null===t?o(t):Vl(t)?e.attempt(pc,s,o)(t):(e.enter("codeFlowValue"),i(t))}function i(t){return null===t||Vl(t)?(e.exit("codeFlowValue"),s(t)):(e.consume(t),i)}function o(n){return e.exit("codeIndented"),t(n)}}},pc={partial:!0,tokenize:function(e,t,n){const r=this;return a;function a(t){return r.parser.lazy[r.now().line]?n(t):Vl(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),a):Gl(e,s,"linePrefix",5)(t)}function s(e){const s=r.events[r.events.length-1];return s&&"linePrefix"===s[1].type&&s[2].sliceSerialize(s[1],!0).length>=4?t(e):Vl(e)?a(e):n(e)}}};const fc={name:"codeText",previous:function(e){return 96!==e||"characterEscape"===this.events[this.events.length-1][1].type},resolve:function(e){let t,n,r=e.length-4,a=3;if(!("lineEnding"!==e[a][1].type&&"space"!==e[a][1].type||"lineEnding"!==e[r][1].type&&"space"!==e[r][1].type))for(t=a;++t<r;)if("codeTextData"===e[t][1].type){e[a][1].type="codeTextPadding",e[r][1].type="codeTextPadding",a+=2,r-=2;break}t=a-1,r++;for(;++t<=r;)void 0===n?t!==r&&"lineEnding"!==e[t][1].type&&(n=t):t!==r&&"lineEnding"!==e[t][1].type||(e[n][1].type="codeTextData",t!==n+2&&(e[n][1].end=e[t-1][1].end,e.splice(n+2,t-n-2),r-=t-n-2,t=n+2),n=void 0);return e},tokenize:function(e,t,n){let r,a,s=0;return function(t){return e.enter("codeText"),e.enter("codeTextSequence"),i(t)};function i(t){return 96===t?(e.consume(t),s++,i):(e.exit("codeTextSequence"),o(t))}function o(t){return null===t?n(t):32===t?(e.enter("space"),e.consume(t),e.exit("space"),o):96===t?(a=e.enter("codeTextSequence"),r=0,c(t)):Vl(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o):(e.enter("codeTextData"),l(t))}function l(t){return null===t||32===t||96===t||Vl(t)?(e.exit("codeTextData"),o(t)):(e.consume(t),l)}function c(n){return 96===n?(e.consume(n),r++,c):r===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(n)):(a.type="codeTextData",l(n))}}};class hc{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){const n=null==t?Number.POSITIVE_INFINITY:t;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){const r=t||0;this.setCursor(Math.trunc(e));const a=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return n&&gc(this.left,n),a.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),gc(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),gc(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&0===this.right.length||e<0&&0===this.left.length))if(e<this.left.length){const t=this.left.splice(e,Number.POSITIVE_INFINITY);gc(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);gc(this.left,t.reverse())}}}function gc(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function xc(e){const t={};let n,r,a,s,i,o,l,c=-1;const u=new hc(e);for(;++c<u.length;){for(;c in t;)c=t[c];if(n=u.get(c),c&&"chunkFlow"===n[1].type&&"listItemPrefix"===u.get(c-1)[1].type&&(o=n[1]._tokenizer.events,a=0,a<o.length&&"lineEndingBlank"===o[a][1].type&&(a+=2),a<o.length&&"content"===o[a][1].type))for(;++a<o.length&&"content"!==o[a][1].type;)"chunkText"===o[a][1].type&&(o[a][1]._isInFirstContentOfListItem=!0,a++);if("enter"===n[0])n[1].contentType&&(Object.assign(t,yc(u,c)),c=t[c],l=!0);else if(n[1]._container){for(a=c,r=void 0;a--;)if(s=u.get(a),"lineEnding"===s[1].type||"lineEndingBlank"===s[1].type)"enter"===s[0]&&(r&&(u.get(r)[1].type="lineEndingBlank"),s[1].type="lineEnding",r=a);else if("linePrefix"!==s[1].type&&"listItemIndent"!==s[1].type)break;r&&(n[1].end={...u.get(r)[1].start},i=u.slice(r,c),i.unshift(n),u.splice(r,c-r+1,i))}}return Tl(e,0,Number.POSITIVE_INFINITY,u.slice(0)),!l}function yc(e,t){const n=e.get(t)[1],r=e.get(t)[2];let a=t-1;const s=[];let i=n._tokenizer;i||(i=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(i._contentTypeTextTrailing=!0));const o=i.events,l=[],c={};let u,d,m=-1,p=n,f=0,h=0;const g=[h];for(;p;){for(;e.get(++a)[1]!==p;);s.push(a),p._tokenizer||(u=r.sliceStream(p),p.next||u.push(null),d&&i.defineSkip(p.start),p._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=!0),i.write(u),p._isInFirstContentOfListItem&&(i._gfmTasklistFirstContentOfListItem=void 0)),d=p,p=p.next}for(p=n;++m<o.length;)"exit"===o[m][0]&&"enter"===o[m-1][0]&&o[m][1].type===o[m-1][1].type&&o[m][1].start.line!==o[m][1].end.line&&(h=m+1,g.push(h),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(i.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),m=g.length;m--;){const t=o.slice(g[m],g[m+1]),n=s.pop();l.push([n,n+t.length-1]),e.splice(n,2,t)}for(l.reverse(),m=-1;++m<l.length;)c[f+l[m][0]]=f+l[m][1],f+=l[m][1]-l[m][0]-1;return c}const vc={resolve:function(e){return xc(e),e},tokenize:function(e,t){let n;return function(t){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),r(t)};function r(t){return null===t?a(t):Vl(t)?e.check(bc,s,a)(t):(e.consume(t),r)}function a(n){return e.exit("chunkContent"),e.exit("content"),t(n)}function s(t){return e.consume(t),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,r}}},bc={partial:!0,tokenize:function(e,t,n){const r=this;return function(t){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Gl(e,a,"linePrefix")};function a(a){if(null===a||Vl(a))return n(a);const s=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&s&&"linePrefix"===s[1].type&&s[2].sliceSerialize(s[1],!0).length>=4?t(a):e.interrupt(r.parser.constructs.flow,n,t)(a)}}};function wc(e,t,n,r,a,s,i,o,l){const c=l||Number.POSITIVE_INFINITY;let u=0;return function(t){if(60===t)return e.enter(r),e.enter(a),e.enter(s),e.consume(t),e.exit(s),d;if(null===t||32===t||41===t||Ul(t))return n(t);return e.enter(r),e.enter(i),e.enter(o),e.enter("chunkString",{contentType:"string"}),f(t)};function d(n){return 62===n?(e.enter(s),e.consume(n),e.exit(s),e.exit(a),e.exit(r),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),m(n))}function m(t){return 62===t?(e.exit("chunkString"),e.exit(o),d(t)):null===t||60===t||Vl(t)?n(t):(e.consume(t),92===t?p:m)}function p(t){return 60===t||62===t||92===t?(e.consume(t),m):m(t)}function f(a){return u||null!==a&&41!==a&&!Hl(a)?u<c&&40===a?(e.consume(a),u++,f):41===a?(e.consume(a),u--,f):null===a||32===a||40===a||Ul(a)?n(a):(e.consume(a),92===a?h:f):(e.exit("chunkString"),e.exit(o),e.exit(i),e.exit(r),t(a))}function h(t){return 40===t||41===t||92===t?(e.consume(t),f):f(t)}}function Nc(e,t,n,r,a,s){const i=this;let o,l=0;return function(t){return e.enter(r),e.enter(a),e.consume(t),e.exit(a),e.enter(s),c};function c(d){return l>999||null===d||91===d||93===d&&!o||94===d&&!l&&"_hiddenFootnoteSupport"in i.parser.constructs?n(d):93===d?(e.exit(s),e.enter(a),e.consume(d),e.exit(a),e.exit(r),t):Vl(d)?(e.enter("lineEnding"),e.consume(d),e.exit("lineEnding"),c):(e.enter("chunkString",{contentType:"string"}),u(d))}function u(t){return null===t||91===t||93===t||Vl(t)||l++>999?(e.exit("chunkString"),c(t)):(e.consume(t),o||(o=!Wl(t)),92===t?d:u)}function d(t){return 91===t||92===t||93===t?(e.consume(t),l++,u):u(t)}}function jc(e,t,n,r,a,s){let i;return function(t){if(34===t||39===t||40===t)return e.enter(r),e.enter(a),e.consume(t),e.exit(a),i=40===t?41:t,o;return n(t)};function o(n){return n===i?(e.enter(a),e.consume(n),e.exit(a),e.exit(r),t):(e.enter(s),l(n))}function l(t){return t===i?(e.exit(s),o(i)):null===t?n(t):Vl(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Gl(e,l,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),c(t))}function c(t){return t===i||null===t||Vl(t)?(e.exit("chunkString"),l(t)):(e.consume(t),92===t?u:c)}function u(t){return t===i||92===t?(e.consume(t),c):c(t)}}function kc(e,t){let n;return function r(a){if(Vl(a))return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),n=!0,r;if(Wl(a))return Gl(e,r,n?"linePrefix":"lineSuffix")(a);return t(a)}}const Cc={name:"definition",tokenize:function(e,t,n){const r=this;let a;return function(t){return e.enter("definition"),function(t){return Nc.call(r,e,s,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(t)}(t)};function s(t){return a=Ll(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),i):n(t)}function i(t){return Hl(t)?kc(e,o)(t):o(t)}function o(t){return wc(e,l,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(t)}function l(t){return e.attempt(Sc,c,c)(t)}function c(t){return Wl(t)?Gl(e,u,"whitespace")(t):u(t)}function u(s){return null===s||Vl(s)?(e.exit("definition"),r.parser.defined.push(a),t(s)):n(s)}}},Sc={partial:!0,tokenize:function(e,t,n){return function(t){return Hl(t)?kc(e,r)(t):n(t)};function r(t){return jc(e,a,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(t)}function a(t){return Wl(t)?Gl(e,s,"whitespace")(t):s(t)}function s(e){return null===e||Vl(e)?t(e):n(e)}}};const Ec={name:"hardBreakEscape",tokenize:function(e,t,n){return function(t){return e.enter("hardBreakEscape"),e.consume(t),r};function r(r){return Vl(r)?(e.exit("hardBreakEscape"),t(r)):n(r)}}};const Ic={name:"headingAtx",resolve:function(e,t){let n,r,a=e.length-2,s=3;"whitespace"===e[s][1].type&&(s+=2);a-2>s&&"whitespace"===e[a][1].type&&(a-=2);"atxHeadingSequence"===e[a][1].type&&(s===a-1||a-4>s&&"whitespace"===e[a-2][1].type)&&(a-=s+1===a?2:4);a>s&&(n={type:"atxHeadingText",start:e[s][1].start,end:e[a][1].end},r={type:"chunkText",start:e[s][1].start,end:e[a][1].end,contentType:"text"},Tl(e,s,a-s+1,[["enter",n,t],["enter",r,t],["exit",r,t],["exit",n,t]]));return e},tokenize:function(e,t,n){let r=0;return function(t){return e.enter("atxHeading"),function(t){return e.enter("atxHeadingSequence"),a(t)}(t)};function a(t){return 35===t&&r++<6?(e.consume(t),a):null===t||Hl(t)?(e.exit("atxHeadingSequence"),s(t)):n(t)}function s(n){return 35===n?(e.enter("atxHeadingSequence"),i(n)):null===n||Vl(n)?(e.exit("atxHeading"),t(n)):Wl(n)?Gl(e,s,"whitespace")(n):(e.enter("atxHeadingText"),o(n))}function i(t){return 35===t?(e.consume(t),i):(e.exit("atxHeadingSequence"),s(t))}function o(t){return null===t||35===t||Hl(t)?(e.exit("atxHeadingText"),s(t)):(e.consume(t),o)}}};const Tc=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Ac=["pre","script","style","textarea"],Pc={concrete:!0,name:"htmlFlow",resolveTo:function(e){let t=e.length;for(;t--&&("enter"!==e[t][0]||"htmlFlow"!==e[t][1].type););t>1&&"linePrefix"===e[t-2][1].type&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2));return e},tokenize:function(e,t,n){const r=this;let a,s,i,o,l;return function(t){return function(t){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(t),c}(t)};function c(o){return 33===o?(e.consume(o),u):47===o?(e.consume(o),s=!0,p):63===o?(e.consume(o),a=3,r.interrupt?t:F):Ml(o)?(e.consume(o),i=String.fromCharCode(o),f):n(o)}function u(s){return 45===s?(e.consume(s),a=2,d):91===s?(e.consume(s),a=5,o=0,m):Ml(s)?(e.consume(s),a=4,r.interrupt?t:F):n(s)}function d(a){return 45===a?(e.consume(a),r.interrupt?t:F):n(a)}function m(a){const s="CDATA[";return a===s.charCodeAt(o++)?(e.consume(a),6===o?r.interrupt?t:S:m):n(a)}function p(t){return Ml(t)?(e.consume(t),i=String.fromCharCode(t),f):n(t)}function f(o){if(null===o||47===o||62===o||Hl(o)){const l=47===o,c=i.toLowerCase();return l||s||!Ac.includes(c)?Tc.includes(i.toLowerCase())?(a=6,l?(e.consume(o),h):r.interrupt?t(o):S(o)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(o):s?g(o):x(o)):(a=1,r.interrupt?t(o):S(o))}return 45===o||Ol(o)?(e.consume(o),i+=String.fromCharCode(o),f):n(o)}function h(a){return 62===a?(e.consume(a),r.interrupt?t:S):n(a)}function g(t){return Wl(t)?(e.consume(t),g):k(t)}function x(t){return 47===t?(e.consume(t),k):58===t||95===t||Ml(t)?(e.consume(t),y):Wl(t)?(e.consume(t),x):k(t)}function y(t){return 45===t||46===t||58===t||95===t||Ol(t)?(e.consume(t),y):v(t)}function v(t){return 61===t?(e.consume(t),b):Wl(t)?(e.consume(t),v):x(t)}function b(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),l=t,w):Wl(t)?(e.consume(t),b):N(t)}function w(t){return t===l?(e.consume(t),l=null,j):null===t||Vl(t)?n(t):(e.consume(t),w)}function N(t){return null===t||34===t||39===t||47===t||60===t||61===t||62===t||96===t||Hl(t)?v(t):(e.consume(t),N)}function j(e){return 47===e||62===e||Wl(e)?x(e):n(e)}function k(t){return 62===t?(e.consume(t),C):n(t)}function C(t){return null===t||Vl(t)?S(t):Wl(t)?(e.consume(t),C):n(t)}function S(t){return 45===t&&2===a?(e.consume(t),A):60===t&&1===a?(e.consume(t),P):62===t&&4===a?(e.consume(t),R):63===t&&3===a?(e.consume(t),F):93===t&&5===a?(e.consume(t),D):!Vl(t)||6!==a&&7!==a?null===t||Vl(t)?(e.exit("htmlFlowData"),E(t)):(e.consume(t),S):(e.exit("htmlFlowData"),e.check(_c,L,E)(t))}function E(t){return e.check(Dc,I,L)(t)}function I(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),T}function T(t){return null===t||Vl(t)?E(t):(e.enter("htmlFlowData"),S(t))}function A(t){return 45===t?(e.consume(t),F):S(t)}function P(t){return 47===t?(e.consume(t),i="",_):S(t)}function _(t){if(62===t){const n=i.toLowerCase();return Ac.includes(n)?(e.consume(t),R):S(t)}return Ml(t)&&i.length<8?(e.consume(t),i+=String.fromCharCode(t),_):S(t)}function D(t){return 93===t?(e.consume(t),F):S(t)}function F(t){return 62===t?(e.consume(t),R):45===t&&2===a?(e.consume(t),F):S(t)}function R(t){return null===t||Vl(t)?(e.exit("htmlFlowData"),L(t)):(e.consume(t),R)}function L(n){return e.exit("htmlFlow"),t(n)}}},_c={partial:!0,tokenize:function(e,t,n){return function(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(ic,t,n)}}},Dc={partial:!0,tokenize:function(e,t,n){const r=this;return function(t){if(Vl(t))return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),a;return n(t)};function a(e){return r.parser.lazy[r.now().line]?n(e):t(e)}}};const Fc={name:"htmlText",tokenize:function(e,t,n){const r=this;let a,s,i;return function(t){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(t),o};function o(t){return 33===t?(e.consume(t),l):47===t?(e.consume(t),b):63===t?(e.consume(t),y):Ml(t)?(e.consume(t),j):n(t)}function l(t){return 45===t?(e.consume(t),c):91===t?(e.consume(t),s=0,p):Ml(t)?(e.consume(t),x):n(t)}function c(t){return 45===t?(e.consume(t),m):n(t)}function u(t){return null===t?n(t):45===t?(e.consume(t),d):Vl(t)?(i=u,_(t)):(e.consume(t),u)}function d(t){return 45===t?(e.consume(t),m):u(t)}function m(e){return 62===e?P(e):45===e?d(e):u(e)}function p(t){const r="CDATA[";return t===r.charCodeAt(s++)?(e.consume(t),6===s?f:p):n(t)}function f(t){return null===t?n(t):93===t?(e.consume(t),h):Vl(t)?(i=f,_(t)):(e.consume(t),f)}function h(t){return 93===t?(e.consume(t),g):f(t)}function g(t){return 62===t?P(t):93===t?(e.consume(t),g):f(t)}function x(t){return null===t||62===t?P(t):Vl(t)?(i=x,_(t)):(e.consume(t),x)}function y(t){return null===t?n(t):63===t?(e.consume(t),v):Vl(t)?(i=y,_(t)):(e.consume(t),y)}function v(e){return 62===e?P(e):y(e)}function b(t){return Ml(t)?(e.consume(t),w):n(t)}function w(t){return 45===t||Ol(t)?(e.consume(t),w):N(t)}function N(t){return Vl(t)?(i=N,_(t)):Wl(t)?(e.consume(t),N):P(t)}function j(t){return 45===t||Ol(t)?(e.consume(t),j):47===t||62===t||Hl(t)?k(t):n(t)}function k(t){return 47===t?(e.consume(t),P):58===t||95===t||Ml(t)?(e.consume(t),C):Vl(t)?(i=k,_(t)):Wl(t)?(e.consume(t),k):P(t)}function C(t){return 45===t||46===t||58===t||95===t||Ol(t)?(e.consume(t),C):S(t)}function S(t){return 61===t?(e.consume(t),E):Vl(t)?(i=S,_(t)):Wl(t)?(e.consume(t),S):k(t)}function E(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),a=t,I):Vl(t)?(i=E,_(t)):Wl(t)?(e.consume(t),E):(e.consume(t),T)}function I(t){return t===a?(e.consume(t),a=void 0,A):null===t?n(t):Vl(t)?(i=I,_(t)):(e.consume(t),I)}function T(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):47===t||62===t||Hl(t)?k(t):(e.consume(t),T)}function A(e){return 47===e||62===e||Hl(e)?k(e):n(e)}function P(r){return 62===r?(e.consume(r),e.exit("htmlTextData"),e.exit("htmlText"),t):n(r)}function _(t){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),D}function D(t){return Wl(t)?Gl(e,F,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):F(t)}function F(t){return e.enter("htmlTextData"),i(t)}}};const Rc={name:"labelEnd",resolveAll:function(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),"labelImage"===r.type||"labelLink"===r.type||"labelEnd"===r.type){const e="labelImage"===r.type?4:2;r.type="data",t+=e}}e.length!==n.length&&Tl(e,0,e.length,n);return e},resolveTo:function(e,t){let n,r,a,s,i=e.length,o=0;for(;i--;)if(n=e[i][1],r){if("link"===n.type||"labelLink"===n.type&&n._inactive)break;"enter"===e[i][0]&&"labelLink"===n.type&&(n._inactive=!0)}else if(a){if("enter"===e[i][0]&&("labelImage"===n.type||"labelLink"===n.type)&&!n._balanced&&(r=i,"labelLink"!==n.type)){o=2;break}}else"labelEnd"===n.type&&(a=i);const l={type:"labelLink"===e[r][1].type?"link":"image",start:{...e[r][1].start},end:{...e[e.length-1][1].end}},c={type:"label",start:{...e[r][1].start},end:{...e[a][1].end}},u={type:"labelText",start:{...e[r+o+2][1].end},end:{...e[a-2][1].start}};return s=[["enter",l,t],["enter",c,t]],s=Al(s,e.slice(r+1,r+o+3)),s=Al(s,[["enter",u,t]]),s=Al(s,nc(t.parser.constructs.insideSpan.null,e.slice(r+o+4,a-3),t)),s=Al(s,[["exit",u,t],e[a-2],e[a-1],["exit",c,t]]),s=Al(s,e.slice(a+1)),s=Al(s,[["exit",l,t]]),Tl(e,r,e.length,s),e},tokenize:function(e,t,n){const r=this;let a,s,i=r.events.length;for(;i--;)if(("labelImage"===r.events[i][1].type||"labelLink"===r.events[i][1].type)&&!r.events[i][1]._balanced){a=r.events[i][1];break}return function(t){if(!a)return n(t);if(a._inactive)return u(t);return s=r.parser.defined.includes(Ll(r.sliceSerialize({start:a.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelEnd"),o};function o(t){return 40===t?e.attempt(Lc,c,s?c:u)(t):91===t?e.attempt(Mc,c,s?l:u)(t):s?c(t):u(t)}function l(t){return e.attempt(Oc,c,u)(t)}function c(e){return t(e)}function u(e){return a._balanced=!0,n(e)}}},Lc={tokenize:function(e,t,n){return function(t){return e.enter("resource"),e.enter("resourceMarker"),e.consume(t),e.exit("resourceMarker"),r};function r(t){return Hl(t)?kc(e,a)(t):a(t)}function a(t){return 41===t?c(t):wc(e,s,i,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(t)}function s(t){return Hl(t)?kc(e,o)(t):c(t)}function i(e){return n(e)}function o(t){return 34===t||39===t||40===t?jc(e,l,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(t):c(t)}function l(t){return Hl(t)?kc(e,c)(t):c(t)}function c(r){return 41===r?(e.enter("resourceMarker"),e.consume(r),e.exit("resourceMarker"),e.exit("resource"),t):n(r)}}},Mc={tokenize:function(e,t,n){const r=this;return function(t){return Nc.call(r,e,a,s,"reference","referenceMarker","referenceString")(t)};function a(e){return r.parser.defined.includes(Ll(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function s(e){return n(e)}}},Oc={tokenize:function(e,t,n){return function(t){return e.enter("reference"),e.enter("referenceMarker"),e.consume(t),e.exit("referenceMarker"),r};function r(r){return 93===r?(e.enter("referenceMarker"),e.consume(r),e.exit("referenceMarker"),e.exit("reference"),t):n(r)}}};const zc={name:"labelStartImage",resolveAll:Rc.resolveAll,tokenize:function(e,t,n){const r=this;return function(t){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(t),e.exit("labelImageMarker"),a};function a(t){return 91===t?(e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelImage"),s):n(t)}function s(e){return 94===e&&"_hiddenFootnoteSupport"in r.parser.constructs?n(e):t(e)}}};const Uc={name:"labelStartLink",resolveAll:Rc.resolveAll,tokenize:function(e,t,n){const r=this;return function(t){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelLink"),a};function a(e){return 94===e&&"_hiddenFootnoteSupport"in r.parser.constructs?n(e):t(e)}}};const Bc={name:"lineEnding",tokenize:function(e,t){return function(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Gl(e,t,"linePrefix")}}};const $c={name:"thematicBreak",tokenize:function(e,t,n){let r,a=0;return function(t){return e.enter("thematicBreak"),function(e){return r=e,s(e)}(t)};function s(s){return s===r?(e.enter("thematicBreakSequence"),i(s)):a>=3&&(null===s||Vl(s))?(e.exit("thematicBreak"),t(s)):n(s)}function i(t){return t===r?(e.consume(t),a++,i):(e.exit("thematicBreakSequence"),Wl(t)?Gl(e,s,"whitespace")(t):s(t))}}};const qc={continuation:{tokenize:function(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(ic,a,s);function a(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Gl(e,t,"listItemIndent",r.containerState.size+1)(n)}function s(n){return r.containerState.furtherBlankLines||!Wl(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,i(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(Hc,t,i)(n))}function i(a){return r.containerState._closeFlow=!0,r.interrupt=void 0,Gl(e,e.attempt(qc,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(a)}}},exit:function(e){e.exit(this.containerState.type)},name:"list",tokenize:function(e,t,n){const r=this,a=r.events[r.events.length-1];let s=a&&"linePrefix"===a[1].type?a[2].sliceSerialize(a[1],!0).length:0,i=0;return function(t){const a=r.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===a?!r.containerState.marker||t===r.containerState.marker:Bl(t)){if(r.containerState.type||(r.containerState.type=a,e.enter(a,{_container:!0})),"listUnordered"===a)return e.enter("listItemPrefix"),42===t||45===t?e.check($c,n,l)(t):l(t);if(!r.interrupt||49===t)return e.enter("listItemPrefix"),e.enter("listItemValue"),o(t)}return n(t)};function o(t){return Bl(t)&&++i<10?(e.consume(t),o):(!r.interrupt||i<2)&&(r.containerState.marker?t===r.containerState.marker:41===t||46===t)?(e.exit("listItemValue"),l(t)):n(t)}function l(t){return e.enter("listItemMarker"),e.consume(t),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||t,e.check(ic,r.interrupt?n:c,e.attempt(Vc,d,u))}function c(e){return r.containerState.initialBlankLine=!0,s++,d(e)}function u(t){return Wl(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),d):n(t)}function d(n){return r.containerState.size=s+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(n)}}},Vc={partial:!0,tokenize:function(e,t,n){const r=this;return Gl(e,function(e){const a=r.events[r.events.length-1];return!Wl(e)&&a&&"listItemPrefixWhitespace"===a[1].type?t(e):n(e)},"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5)}},Hc={partial:!0,tokenize:function(e,t,n){const r=this;return Gl(e,function(e){const a=r.events[r.events.length-1];return a&&"listItemIndent"===a[1].type&&a[2].sliceSerialize(a[1],!0).length===r.containerState.size?t(e):n(e)},"listItemIndent",r.containerState.size+1)}};const Wc={name:"setextUnderline",resolveTo:function(e,t){let n,r,a,s=e.length;for(;s--;)if("enter"===e[s][0]){if("content"===e[s][1].type){n=s;break}"paragraph"===e[s][1].type&&(r=s)}else"content"===e[s][1].type&&e.splice(s,1),a||"definition"!==e[s][1].type||(a=s);const i={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};e[r][1].type="setextHeadingText",a?(e.splice(r,0,["enter",i,t]),e.splice(a+1,0,["exit",e[n][1],t]),e[n][1].end={...e[a][1].end}):e[n][1]=i;return e.push(["exit",i,t]),e},tokenize:function(e,t,n){const r=this;let a;return function(t){let i,o=r.events.length;for(;o--;)if("lineEnding"!==r.events[o][1].type&&"linePrefix"!==r.events[o][1].type&&"content"!==r.events[o][1].type){i="paragraph"===r.events[o][1].type;break}if(!r.parser.lazy[r.now().line]&&(r.interrupt||i))return e.enter("setextHeadingLine"),a=t,function(t){return e.enter("setextHeadingLineSequence"),s(t)}(t);return n(t)};function s(t){return t===a?(e.consume(t),s):(e.exit("setextHeadingLineSequence"),Wl(t)?Gl(e,i,"lineSuffix")(t):i(t))}function i(r){return null===r||Vl(r)?(e.exit("setextHeadingLine"),t(r)):n(r)}}};const Qc={tokenize:function(e){const t=this,n=e.attempt(ic,function(r){if(null===r)return void e.consume(r);return e.enter("lineEndingBlank"),e.consume(r),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n},e.attempt(this.parser.constructs.flowInitial,r,Gl(e,e.attempt(this.parser.constructs.flow,r,e.attempt(vc,r)),"linePrefix")));return n;function r(r){if(null!==r)return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),t.currentConstruct=void 0,n;e.consume(r)}}};const Kc={resolveAll:Jc()},Xc=Gc("string"),Yc=Gc("text");function Gc(e){return{resolveAll:Jc("text"===e?Zc:void 0),tokenize:function(t){const n=this,r=this.parser.constructs[e],a=t.attempt(r,s,i);return s;function s(e){return l(e)?a(e):i(e)}function i(e){if(null!==e)return t.enter("data"),t.consume(e),o;t.consume(e)}function o(e){return l(e)?(t.exit("data"),a(e)):(t.consume(e),o)}function l(e){if(null===e)return!0;const t=r[e];let a=-1;if(t)for(;++a<t.length;){const e=t[a];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}}function Jc(e){return function(t,n){let r,a=-1;for(;++a<=t.length;)void 0===r?t[a]&&"data"===t[a][1].type&&(r=a,a++):t[a]&&"data"===t[a][1].type||(a!==r+2&&(t[r][1].end=t[a-1][1].end,t.splice(r+2,a-r-2),a=r+2),r=void 0);return e?e(t,n):t}}function Zc(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||"lineEnding"===e[n][1].type)&&"data"===e[n-1][1].type){const r=e[n-1][1],a=t.sliceStream(r);let s,i=a.length,o=-1,l=0;for(;i--;){const e=a[i];if("string"==typeof e){for(o=e.length;32===e.charCodeAt(o-1);)l++,o--;if(o)break;o=-1}else if(-2===e)s=!0,l++;else if(-1!==e){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(l=0),l){const a={type:n===e.length||s||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:r.start._bufferIndex+o,_index:r.start._index+i,line:r.end.line,column:r.end.column-l,offset:r.end.offset-l},end:{...r.end}};r.end={...a.start},r.start.offset===r.end.offset?Object.assign(r,a):(e.splice(n,0,["enter",a,t],["exit",a,t]),n+=2)}n++}return e}const eu={42:qc,43:qc,45:qc,48:qc,49:qc,50:qc,51:qc,52:qc,53:qc,54:qc,55:qc,56:qc,57:qc,62:oc},tu={91:Cc},nu={[-2]:mc,[-1]:mc,32:mc},ru={35:Ic,42:$c,45:[Wc,$c],60:Pc,61:Wc,95:$c,96:dc,126:dc},au={38:cc,92:lc},su={[-5]:Bc,[-4]:Bc,[-3]:Bc,33:zc,38:cc,42:rc,60:[sc,Fc],91:Uc,92:[Ec,lc],93:Rc,95:rc,96:fc},iu={null:[rc,Kc]};var ou=Object.freeze({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:tu,disable:{null:[]},document:eu,flow:ru,flowInitial:nu,insideSpan:iu,string:au,text:su});function lu(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const a={},s=[];let i=[],o=[];const l={attempt:g(function(e,t){x(e,t.from)}),check:g(h),consume:function(e){Vl(e)?(r.line++,r.column=1,r.offset+=-3===e?2:1,y()):-1!==e&&(r.column++,r.offset++);r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===i[r._index].length&&(r._bufferIndex=-1,r._index++));c.previous=e},enter:function(e,t){const n=t||{};return n.type=e,n.start=m(),c.events.push(["enter",n,c]),o.push(n),n},exit:function(e){const t=o.pop();return t.end=m(),c.events.push(["exit",t,c]),t},interrupt:g(h,{interrupt:!0})},c={code:null,containerState:{},defineSkip:function(e){a[e.line]=e.column,y()},events:[],now:m,parser:e,previous:null,sliceSerialize:function(e,t){return function(e,t){let n=-1;const r=[];let a;for(;++n<e.length;){const s=e[n];let i;if("string"==typeof s)i=s;else switch(s){case-5:i="\r";break;case-4:i="\n";break;case-3:i="\r\n";break;case-2:i=t?" ":"\t";break;case-1:if(!t&&a)continue;i=" ";break;default:i=String.fromCharCode(s)}a=-2===s,r.push(i)}return r.join("")}(d(e),t)},sliceStream:d,write:function(e){if(i=Al(i,e),p(),null!==i[i.length-1])return[];return x(t,0),c.events=nc(s,c.events,c),c.events}};let u=t.tokenize.call(c,l);return t.resolveAll&&s.push(t),c;function d(e){return function(e,t){const n=t.start._index,r=t.start._bufferIndex,a=t.end._index,s=t.end._bufferIndex;let i;if(n===a)i=[e[n].slice(r,s)];else{if(i=e.slice(n,a),r>-1){const e=i[0];"string"==typeof e?i[0]=e.slice(r):i.shift()}s>0&&i.push(e[a].slice(0,s))}return i}(i,e)}function m(){const{_bufferIndex:e,_index:t,line:n,column:a,offset:s}=r;return{_bufferIndex:e,_index:t,line:n,column:a,offset:s}}function p(){let e;for(;r._index<i.length;){const t=i[r._index];if("string"==typeof t)for(e=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===e&&r._bufferIndex<t.length;)f(t.charCodeAt(r._bufferIndex));else f(t)}}function f(e){u=u(e)}function h(e,t){t.restore()}function g(e,t){return function(n,a,s){let i,u,d,p;return Array.isArray(n)?f(n):"tokenize"in n?f([n]):function(e){return t;function t(t){const n=null!==t&&e[t],r=null!==t&&e.null;return f([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(r)?r:r?[r]:[]])(t)}}(n);function f(e){return i=e,u=0,0===e.length?s:h(e[u])}function h(e){return function(n){p=function(){const e=m(),t=c.previous,n=c.currentConstruct,a=c.events.length,s=Array.from(o);return{from:a,restore:i};function i(){r=e,c.previous=t,c.currentConstruct=n,c.events.length=a,o=s,y()}}(),d=e,e.partial||(c.currentConstruct=e);if(e.name&&c.parser.constructs.disable.null.includes(e.name))return x();return e.tokenize.call(t?Object.assign(Object.create(c),t):c,l,g,x)(n)}}function g(t){return e(d,p),a}function x(e){return p.restore(),++u<i.length?h(i[u]):s}}}function x(e,t){e.resolveAll&&!s.includes(e)&&s.push(e),e.resolve&&Tl(c.events,t,c.events.length-t,e.resolve(c.events.slice(t),c)),e.resolveTo&&(c.events=e.resolveTo(c.events,c))}function y(){r.line in a&&r.column<2&&(r.column=a[r.line],r.offset+=a[r.line]-1)}}const cu=/[\0\t\n\r]/g;const uu=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function du(e,t,n){if(t)return t;if(35===n.charCodeAt(0)){const e=n.charCodeAt(1),t=120===e||88===e;return Rl(n.slice(t?2:1),t?16:10)}return Il(n)||e}const mu={}.hasOwnProperty;function pu(e,t,n){return"string"!=typeof t&&(n=t,t=void 0),function(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:s(te),autolinkProtocol:C,autolinkEmail:C,atxHeading:s(G),blockQuote:s(W),characterEscape:C,characterReference:C,codeFenced:s(Q),codeFencedFenceInfo:i,codeFencedFenceMeta:i,codeIndented:s(Q,i),codeText:s(K,i),codeTextData:C,data:C,codeFlowValue:C,definition:s(X),definitionDestinationString:i,definitionLabelString:i,definitionTitleString:i,emphasis:s(Y),hardBreakEscape:s(J),hardBreakTrailing:s(J),htmlFlow:s(Z,i),htmlFlowData:C,htmlText:s(Z,i),htmlTextData:C,image:s(ee),label:i,link:s(te),listItem:s(re),listItemValue:m,listOrdered:s(ne,d),listUnordered:s(ne),paragraph:s(ae),reference:z,referenceString:i,resourceDestinationString:i,resourceTitleString:i,setextHeading:s(G),strong:s(se),thematicBreak:s(oe)},exit:{atxHeading:l(),atxHeadingSequence:w,autolink:l(),autolinkEmail:H,autolinkProtocol:V,blockQuote:l(),characterEscapeValue:S,characterReferenceMarkerHexadecimal:B,characterReferenceMarkerNumeric:B,characterReferenceValue:$,characterReference:q,codeFenced:l(g),codeFencedFence:h,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:S,codeIndented:l(x),codeText:l(P),codeTextData:S,data:S,definition:l(),definitionDestinationString:b,definitionLabelString:y,definitionTitleString:v,emphasis:l(),hardBreakEscape:l(I),hardBreakTrailing:l(I),htmlFlow:l(T),htmlFlowData:S,htmlText:l(A),htmlTextData:S,image:l(D),label:R,labelText:F,lineEnding:E,link:l(_),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:U,resourceDestinationString:L,resourceTitleString:M,resource:O,setextHeading:l(k),setextHeadingLineSequence:j,setextHeadingText:N,strong:l(),thematicBreak:l()}};hu(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(e){let r={type:"root",children:[]};const s={stack:[r],tokenStack:[],config:t,enter:o,exit:c,buffer:i,resume:u,data:n},l=[];let d=-1;for(;++d<e.length;)if("listOrdered"===e[d][1].type||"listUnordered"===e[d][1].type)if("enter"===e[d][0])l.push(d);else{d=a(e,l.pop(),d)}for(d=-1;++d<e.length;){const n=t[e[d][0]];mu.call(n,e[d][1].type)&&n[e[d][1].type].call(Object.assign({sliceSerialize:e[d][2].sliceSerialize},s),e[d][1])}if(s.tokenStack.length>0){const e=s.tokenStack[s.tokenStack.length-1];(e[1]||xu).call(s,void 0,e[0])}for(r.position={start:fu(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:fu(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++d<t.transforms.length;)r=t.transforms[d](r)||r;return r}function a(e,t,n){let r,a,s,i,o=t-1,l=-1,c=!1;for(;++o<=n;){const t=e[o];switch(t[1].type){case"listUnordered":case"listOrdered":case"blockQuote":"enter"===t[0]?l++:l--,i=void 0;break;case"lineEndingBlank":"enter"===t[0]&&(!r||i||l||s||(s=o),i=void 0);break;case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:i=void 0}if(!l&&"enter"===t[0]&&"listItemPrefix"===t[1].type||-1===l&&"exit"===t[0]&&("listUnordered"===t[1].type||"listOrdered"===t[1].type)){if(r){let i=o;for(a=void 0;i--;){const t=e[i];if("lineEnding"===t[1].type||"lineEndingBlank"===t[1].type){if("exit"===t[0])continue;a&&(e[a][1].type="lineEndingBlank",c=!0),t[1].type="lineEnding",a=i}else if("linePrefix"!==t[1].type&&"blockQuotePrefix"!==t[1].type&&"blockQuotePrefixWhitespace"!==t[1].type&&"blockQuoteMarker"!==t[1].type&&"listItemIndent"!==t[1].type)break}s&&(!a||s<a)&&(r._spread=!0),r.end=Object.assign({},a?e[a][1].start:t[1].end),e.splice(a||o,0,["exit",r,t[2]]),o++,n++}if("listItemPrefix"===t[1].type){const a={type:"listItem",_spread:!1,start:Object.assign({},t[1].start),end:void 0};r=a,e.splice(o,0,["enter",a,t[2]]),o++,n++,s=void 0,i=!0}}}return e[t][1]._spread=c,n}function s(e,t){return n;function n(n){o.call(this,e(n),n),t&&t.call(this,n)}}function i(){this.stack.push({type:"fragment",children:[]})}function o(e,t,n){this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n||void 0]),e.position={start:fu(t.start),end:void 0}}function l(e){return t;function t(t){e&&e.call(this,t),c.call(this,t)}}function c(e,t){const n=this.stack.pop(),r=this.tokenStack.pop();if(!r)throw new Error("Cannot close `"+e.type+"` ("+tl({start:e.start,end:e.end})+"): it’s not open");if(r[0].type!==e.type)if(t)t.call(this,e,r[0]);else{(r[1]||xu).call(this,e,r[0])}n.position.end=fu(e.end)}function u(){return kl(this.stack.pop())}function d(){this.data.expectingFirstListItemValue=!0}function m(e){if(this.data.expectingFirstListItemValue){this.stack[this.stack.length-2].start=Number.parseInt(this.sliceSerialize(e),10),this.data.expectingFirstListItemValue=void 0}}function p(){const e=this.resume();this.stack[this.stack.length-1].lang=e}function f(){const e=this.resume();this.stack[this.stack.length-1].meta=e}function h(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function g(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/(\r?\n|\r)$/g,"")}function y(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Ll(this.sliceSerialize(e)).toLowerCase()}function v(){const e=this.resume();this.stack[this.stack.length-1].title=e}function b(){const e=this.resume();this.stack[this.stack.length-1].url=e}function w(e){const t=this.stack[this.stack.length-1];if(!t.depth){const n=this.sliceSerialize(e).length;t.depth=n}}function N(){this.data.setextHeadingSlurpLineEnding=!0}function j(e){this.stack[this.stack.length-1].depth=61===this.sliceSerialize(e).codePointAt(0)?1:2}function k(){this.data.setextHeadingSlurpLineEnding=void 0}function C(e){const t=this.stack[this.stack.length-1].children;let n=t[t.length-1];n&&"text"===n.type||(n=ie(),n.position={start:fu(e.start),end:void 0},t.push(n)),this.stack.push(n)}function S(e){const t=this.stack.pop();t.value+=this.sliceSerialize(e),t.position.end=fu(e.end)}function E(e){const n=this.stack[this.stack.length-1];if(this.data.atHardBreak){return n.children[n.children.length-1].position.end=fu(e.end),void(this.data.atHardBreak=void 0)}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(n.type)&&(C.call(this,e),S.call(this,e))}function I(){this.data.atHardBreak=!0}function T(){const e=this.resume();this.stack[this.stack.length-1].value=e}function A(){const e=this.resume();this.stack[this.stack.length-1].value=e}function P(){const e=this.resume();this.stack[this.stack.length-1].value=e}function _(){const e=this.stack[this.stack.length-1];if(this.data.inReference){const t=this.data.referenceType||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function D(){const e=this.stack[this.stack.length-1];if(this.data.inReference){const t=this.data.referenceType||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}function F(e){const t=this.sliceSerialize(e),n=this.stack[this.stack.length-2];n.label=function(e){return e.replace(uu,du)}(t),n.identifier=Ll(t).toLowerCase()}function R(){const e=this.stack[this.stack.length-1],t=this.resume(),n=this.stack[this.stack.length-1];if(this.data.inReference=!0,"link"===n.type){const t=e.children;n.children=t}else n.alt=t}function L(){const e=this.resume();this.stack[this.stack.length-1].url=e}function M(){const e=this.resume();this.stack[this.stack.length-1].title=e}function O(){this.data.inReference=void 0}function z(){this.data.referenceType="collapsed"}function U(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Ll(this.sliceSerialize(e)).toLowerCase(),this.data.referenceType="full"}function B(e){this.data.characterReferenceType=e.type}function $(e){const t=this.sliceSerialize(e),n=this.data.characterReferenceType;let r;if(n)r=Rl(t,"characterReferenceMarkerNumeric"===n?10:16),this.data.characterReferenceType=void 0;else{r=Il(t)}this.stack[this.stack.length-1].value+=r}function q(e){this.stack.pop().position.end=fu(e.end)}function V(e){S.call(this,e);this.stack[this.stack.length-1].url=this.sliceSerialize(e)}function H(e){S.call(this,e);this.stack[this.stack.length-1].url="mailto:"+this.sliceSerialize(e)}function W(){return{type:"blockquote",children:[]}}function Q(){return{type:"code",lang:null,meta:null,value:""}}function K(){return{type:"inlineCode",value:""}}function X(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function Y(){return{type:"emphasis",children:[]}}function G(){return{type:"heading",depth:0,children:[]}}function J(){return{type:"break"}}function Z(){return{type:"html",value:""}}function ee(){return{type:"image",title:null,url:"",alt:null}}function te(){return{type:"link",title:null,url:"",children:[]}}function ne(e){return{type:"list",ordered:"listOrdered"===e.type,start:null,spread:e._spread,children:[]}}function re(e){return{type:"listItem",spread:e._spread,checked:null,children:[]}}function ae(){return{type:"paragraph",children:[]}}function se(){return{type:"strong",children:[]}}function ie(){return{type:"text",value:""}}function oe(){return{type:"thematicBreak"}}}(n)(function(e){for(;!xc(e););return e}(function(e){const t={constructs:_l([ou,...(e||{}).extensions||[]]),content:n(Jl),defined:[],document:n(Zl),flow:n(Qc),lazy:{},string:n(Xc),text:n(Yc)};return t;function n(e){return function(n){return lu(t,e,n)}}}(n).document().write(function(){let e,t=1,n="",r=!0;return function(a,s,i){const o=[];let l,c,u,d,m;for(a=n+("string"==typeof a?a.toString():new TextDecoder(s||void 0).decode(a)),u=0,n="",r&&(65279===a.charCodeAt(0)&&u++,r=void 0);u<a.length;){if(cu.lastIndex=u,l=cu.exec(a),d=l&&void 0!==l.index?l.index:a.length,m=a.charCodeAt(d),!l){n=a.slice(u);break}if(10===m&&u===d&&e)o.push(-3),e=void 0;else switch(e&&(o.push(-5),e=void 0),u<d&&(o.push(a.slice(u,d)),t+=d-u),m){case 0:o.push(65533),t++;break;case 9:for(c=4*Math.ceil(t/4),o.push(-2);t++<c;)o.push(-1);break;case 10:o.push(-4),t=1;break;default:e=!0,t=1}u=d+1}return i&&(e&&o.push(-5),n&&o.push(n),o.push(null)),o}}()(e,t,!0))))}function fu(e){return{line:e.line,column:e.column,offset:e.offset}}function hu(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?hu(e,r):gu(e,r)}}function gu(e,t){let n;for(n in t)if(mu.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function xu(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+tl({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+tl({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+tl({start:t.start,end:t.end})+") is still open")}function yu(e){const t=this;t.parser=function(n){return pu(n,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function vu(e,t){const n=t.referenceType;let r="]";if("collapsed"===n?r+="[]":"full"===n&&(r+="["+(t.label||t.identifier)+"]"),"imageReference"===t.type)return[{type:"text",value:"!["+t.alt+r}];const a=e.all(t),s=a[0];s&&"text"===s.type?s.value="["+s.value:a.unshift({type:"text",value:"["});const i=a[a.length-1];return i&&"text"===i.type?i.value+=r:a.push({type:"text",value:r}),a}function bu(e){const t=e.spread;return null==t?e.children.length>1:t}function wu(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),a=0;const s=[];for(;r;)s.push(Nu(t.slice(a,r.index),a>0,!0),r[0]),a=r.index+r[0].length,r=n.exec(t);return s.push(Nu(t.slice(a),a>0,!1)),s.join("")}function Nu(e,t,n){let r=0,a=e.length;if(t){let t=e.codePointAt(r);for(;9===t||32===t;)r++,t=e.codePointAt(r)}if(n){let t=e.codePointAt(a-1);for(;9===t||32===t;)a--,t=e.codePointAt(a-1)}return a>r?e.slice(r,a):""}const ju={blockquote:function(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)},break:function(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:"\n"}]},code:function(e,t){const n=t.value?t.value+"\n":"",r={};t.lang&&(r.className=["language-"+t.lang]);let a={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(a.data={meta:t.meta}),e.patch(t,a),a=e.applyData(t,a),a={type:"element",tagName:"pre",properties:{},children:[a]},e.patch(t,a),a},delete:function(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},emphasis:function(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},footnoteReference:function(e,t){const n="string"==typeof e.options.clobberPrefix?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=Yl(r.toLowerCase()),s=e.footnoteOrder.indexOf(r);let i,o=e.footnoteCounts.get(r);void 0===o?(o=0,e.footnoteOrder.push(r),i=e.footnoteOrder.length):i=s+1,o+=1,e.footnoteCounts.set(r,o);const l={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+a,id:n+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(i)}]};e.patch(t,l);const c={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,c),e.applyData(t,c)},heading:function(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},html:function(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}},imageReference:function(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return vu(e,t);const a={src:Yl(r.url||""),alt:t.alt};null!==r.title&&void 0!==r.title&&(a.title=r.title);const s={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,s),e.applyData(t,s)},image:function(e,t){const n={src:Yl(t.url)};null!==t.alt&&void 0!==t.alt&&(n.alt=t.alt),null!==t.title&&void 0!==t.title&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)},inlineCode:function(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)},linkReference:function(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return vu(e,t);const a={href:Yl(r.url||"")};null!==r.title&&void 0!==r.title&&(a.title=r.title);const s={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,s),e.applyData(t,s)},link:function(e,t){const n={href:Yl(t.url)};null!==t.title&&void 0!==t.title&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)},listItem:function(e,t,n){const r=e.all(t),a=n?function(e){let t=!1;if("list"===e.type){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=bu(n[r])}return t}(n):bu(t),s={},i=[];if("boolean"==typeof t.checked){const e=r[0];let n;e&&"element"===e.type&&"p"===e.tagName?n=e:(n={type:"element",tagName:"p",properties:{},children:[]},r.unshift(n)),n.children.length>0&&n.children.unshift({type:"text",value:" "}),n.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),s.className=["task-list-item"]}let o=-1;for(;++o<r.length;){const e=r[o];(a||0!==o||"element"!==e.type||"p"!==e.tagName)&&i.push({type:"text",value:"\n"}),"element"!==e.type||"p"!==e.tagName||a?i.push(e):i.push(...e.children)}const l=r[r.length-1];l&&(a||"element"!==l.type||"p"!==l.tagName)&&i.push({type:"text",value:"\n"});const c={type:"element",tagName:"li",properties:s,children:i};return e.patch(t,c),e.applyData(t,c)},list:function(e,t){const n={},r=e.all(t);let a=-1;for("number"==typeof t.start&&1!==t.start&&(n.start=t.start);++a<r.length;){const e=r[a];if("element"===e.type&&"li"===e.tagName&&e.properties&&Array.isArray(e.properties.className)&&e.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const s={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,s),e.applyData(t,s)},paragraph:function(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},root:function(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)},strong:function(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},table:function(e,t){const n=e.all(t),r=n.shift(),a=[];if(r){const n={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],n),a.push(n)}if(n.length>0){const r={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},s=Zo(t.children[1]),i=Jo(t.children[t.children.length-1]);s&&i&&(r.position={start:s,end:i}),a.push(r)}const s={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,s),e.applyData(t,s)},tableCell:function(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)},tableRow:function(e,t,n){const r=n?n.children:void 0,a=0===(r?r.indexOf(t):1)?"th":"td",s=n&&"table"===n.type?n.align:void 0,i=s?s.length:t.children.length;let o=-1;const l=[];for(;++o<i;){const n=t.children[o],r={},i=s?s[o]:void 0;i&&(r.align=i);let c={type:"element",tagName:a,properties:r,children:[]};n&&(c.children=e.all(n),e.patch(n,c),c=e.applyData(n,c)),l.push(c)}const c={type:"element",tagName:"tr",properties:{},children:e.wrap(l,!0)};return e.patch(t,c),e.applyData(t,c)},text:function(e,t){const n={type:"text",value:wu(String(t.value))};return e.patch(t,n),e.applyData(t,n)},thematicBreak:function(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)},toml:ku,yaml:ku,definition:ku,footnoteDefinition:ku};function ku(){}const Cu="object"==typeof self?self:globalThis,Su=e=>((e,t)=>{const n=(t,n)=>(e.set(n,t),t),r=a=>{if(e.has(a))return e.get(a);const[s,i]=t[a];switch(s){case 0:case-1:return n(i,a);case 1:{const e=n([],a);for(const t of i)e.push(r(t));return e}case 2:{const e=n({},a);for(const[t,n]of i)e[r(t)]=r(n);return e}case 3:return n(new Date(i),a);case 4:{const{source:e,flags:t}=i;return n(new RegExp(e,t),a)}case 5:{const e=n(new Map,a);for(const[t,n]of i)e.set(r(t),r(n));return e}case 6:{const e=n(new Set,a);for(const t of i)e.add(r(t));return e}case 7:{const{name:e,message:t}=i;return n(new Cu[e](t),a)}case 8:return n(BigInt(i),a);case"BigInt":return n(Object(BigInt(i)),a);case"ArrayBuffer":return n(new Uint8Array(i).buffer,i);case"DataView":{const{buffer:e}=new Uint8Array(i);return n(new DataView(e),i)}}return n(new Cu[s](i),a)};return r})(new Map,e)(0),Eu="",{toString:Iu}={},{keys:Tu}=Object,Au=e=>{const t=typeof e;if("object"!==t||!e)return[0,t];const n=Iu.call(e).slice(8,-1);switch(n){case"Array":return[1,Eu];case"Object":return[2,Eu];case"Date":return[3,Eu];case"RegExp":return[4,Eu];case"Map":return[5,Eu];case"Set":return[6,Eu];case"DataView":return[1,n]}return n.includes("Array")?[1,n]:n.includes("Error")?[7,n]:[2,n]},Pu=([e,t])=>0===e&&("function"===t||"symbol"===t),_u=(e,{json:t,lossy:n}={})=>{const r=[];return((e,t,n,r)=>{const a=(e,t)=>{const a=r.push(e)-1;return n.set(t,a),a},s=r=>{if(n.has(r))return n.get(r);let[i,o]=Au(r);switch(i){case 0:{let t=r;switch(o){case"bigint":i=8,t=r.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+o);t=null;break;case"undefined":return a([-1],r)}return a([i,t],r)}case 1:{if(o){let e=r;return"DataView"===o?e=new Uint8Array(r.buffer):"ArrayBuffer"===o&&(e=new Uint8Array(r)),a([o,[...e]],r)}const e=[],t=a([i,e],r);for(const n of r)e.push(s(n));return t}case 2:{if(o)switch(o){case"BigInt":return a([o,r.toString()],r);case"Boolean":case"Number":case"String":return a([o,r.valueOf()],r)}if(t&&"toJSON"in r)return s(r.toJSON());const n=[],l=a([i,n],r);for(const t of Tu(r))!e&&Pu(Au(r[t]))||n.push([s(t),s(r[t])]);return l}case 3:return a([i,r.toISOString()],r);case 4:{const{source:e,flags:t}=r;return a([i,{source:e,flags:t}],r)}case 5:{const t=[],n=a([i,t],r);for(const[a,i]of r)(e||!Pu(Au(a))&&!Pu(Au(i)))&&t.push([s(a),s(i)]);return n}case 6:{const t=[],n=a([i,t],r);for(const a of r)!e&&Pu(Au(a))||t.push(s(a));return n}}const{message:l}=r;return a([i,{name:o,message:l}],r)};return s})(!(t||n),!!t,new Map,r)(e),r};var Du="function"==typeof structuredClone?(e,t)=>t&&("json"in t||"lossy"in t)?Su(_u(e,t)):structuredClone(e):(e,t)=>Su(_u(e,t));function Fu(e,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function Ru(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}const Lu=function(e){if(null==e)return Ou;if("function"==typeof e)return Mu(e);if("object"==typeof e)return Array.isArray(e)?function(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Lu(e[n]);return Mu(r);function r(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}(e):function(e){const t=e;return Mu(n);function n(n){const r=n;let a;for(a in e)if(r[a]!==t[a])return!1;return!0}}(e);if("string"==typeof e)return function(e){return Mu(t);function t(t){return t&&t.type===e}}(e);throw new Error("Expected function, string, or object as test")};function Mu(e){return function(t,n,r){return Boolean(function(e){return null!==e&&"object"==typeof e&&"type"in e}(t)&&e.call(this,t,"number"==typeof n?n:void 0,r||void 0))}}function Ou(){return!0}const zu=[],Uu=!0,Bu=!1;function $u(e,t,n,r){let a;"function"==typeof t&&"function"!=typeof n?(r=n,n=t):a=t;const s=Lu(a),i=r?-1:1;!function e(a,o,l){const c=a&&"object"==typeof a?a:{};if("string"==typeof c.type){const e="string"==typeof c.tagName?c.tagName:"string"==typeof c.name?c.name:void 0;Object.defineProperty(u,"name",{value:"node ("+a.type+(e?"<"+e+">":"")+")"})}return u;function u(){let c,u,d,m=zu;if((!t||s(a,o,l[l.length-1]||void 0))&&(m=function(e){if(Array.isArray(e))return e;if("number"==typeof e)return[Uu,e];return null==e?zu:[e]}(n(a,l)),m[0]===Bu))return m;if("children"in a&&a.children){const t=a;if(t.children&&"skip"!==m[0])for(u=(r?t.children.length:-1)+i,d=l.concat(t);u>-1&&u<t.children.length;){const n=t.children[u];if(c=e(n,u,d)(),c[0]===Bu)return c;u="number"==typeof c[1]?c[1]:u+i}}return m}}(e,void 0,[])()}function qu(e,t,n,r){let a,s,i;"function"==typeof t&&"function"!=typeof n?(s=void 0,i=t,a=n):(s=t,i=n,a=r),$u(e,s,function(e,t){const n=t[t.length-1],r=n?n.children.indexOf(e):void 0;return i(e,r,n)},a)}const Vu={}.hasOwnProperty,Hu={};function Wu(e,t){e.position&&(t.position=function(e){const t=Zo(e),n=Jo(e);if(t&&n)return{start:t,end:n}}(e))}function Qu(e,t){let n=t;if(e&&e.data){const t=e.data.hName,r=e.data.hChildren,a=e.data.hProperties;if("string"==typeof t)if("element"===n.type)n.tagName=t;else{n={type:"element",tagName:t,properties:{},children:"children"in n?n.children:[n]}}"element"===n.type&&a&&Object.assign(n.properties,Du(a)),"children"in n&&n.children&&null!=r&&(n.children=r)}return n}function Ku(e,t){const n=t.data||{},r=!("value"in t)||Vu.call(n,"hProperties")||Vu.call(n,"hChildren")?{type:"element",tagName:"div",properties:{},children:e.all(t)}:{type:"text",value:t.value};return e.patch(t,r),e.applyData(t,r)}function Xu(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:"\n"});++r<e.length;)r&&n.push({type:"text",value:"\n"}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:"\n"}),n}function Yu(e){let t=0,n=e.charCodeAt(t);for(;9===n||32===n;)t++,n=e.charCodeAt(t);return e.slice(t)}function Gu(e,t){const n=function(e,t){const n=t||Hu,r=new Map,a=new Map,s=new Map,i={...ju,...n.handlers},o={all:function(e){const t=[];if("children"in e){const n=e.children;let r=-1;for(;++r<n.length;){const a=o.one(n[r],e);if(a){if(r&&"break"===n[r-1].type&&(Array.isArray(a)||"text"!==a.type||(a.value=Yu(a.value)),!Array.isArray(a)&&"element"===a.type)){const e=a.children[0];e&&"text"===e.type&&(e.value=Yu(e.value))}Array.isArray(a)?t.push(...a):t.push(a)}}}return t},applyData:Qu,definitionById:r,footnoteById:a,footnoteCounts:s,footnoteOrder:[],handlers:i,one:function(e,t){const n=e.type,r=o.handlers[n];if(Vu.call(o.handlers,n)&&r)return r(o,e,t);if(o.options.passThrough&&o.options.passThrough.includes(n)){if("children"in e){const{children:t,...n}=e,r=Du(n);return r.children=o.all(e),r}return Du(e)}return(o.options.unknownHandler||Ku)(o,e,t)},options:n,patch:Wu,wrap:Xu};return qu(e,function(e){if("definition"===e.type||"footnoteDefinition"===e.type){const t="definition"===e.type?r:a,n=String(e.identifier).toUpperCase();t.has(n)||t.set(n,e)}}),o}(e,t),r=n.one(e,void 0),a=function(e){const t="string"==typeof e.options.clobberPrefix?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Fu,r=e.options.footnoteBackLabel||Ru,a=e.options.footnoteLabel||"Footnotes",s=e.options.footnoteLabelTagName||"h2",i=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const a=e.footnoteById.get(e.footnoteOrder[l]);if(!a)continue;const s=e.all(a),i=String(a.identifier).toUpperCase(),c=Yl(i.toLowerCase());let u=0;const d=[],m=e.footnoteCounts.get(i);for(;void 0!==m&&++u<=m;){d.length>0&&d.push({type:"text",value:" "});let e="string"==typeof n?n:n(l,u);"string"==typeof e&&(e={type:"text",value:e}),d.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+c+(u>1?"-"+u:""),dataFootnoteBackref:"",ariaLabel:"string"==typeof r?r:r(l,u),className:["data-footnote-backref"]},children:Array.isArray(e)?e:[e]})}const p=s[s.length-1];if(p&&"element"===p.type&&"p"===p.tagName){const e=p.children[p.children.length-1];e&&"text"===e.type?e.value+=" ":p.children.push({type:"text",value:" "}),p.children.push(...d)}else s.push(...d);const f={type:"element",tagName:"li",properties:{id:t+"fn-"+c},children:e.wrap(s,!0)};e.patch(a,f),o.push(f)}if(0!==o.length)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:s,properties:{...Du(i),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:"\n"},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:"\n"}]}}(n),s=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&s.children.push({type:"text",value:"\n"},a),s}function Ju(e,t){return e&&"run"in e?async function(n,r){const a=Gu(n,{file:r,...t});await e.run(a,r)}:function(n,r){return Gu(n,{file:r,...e||t})}}function Zu(e){if(e)throw e}var ed,td;var nd=function(){if(td)return ed;td=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=function(e){return"function"==typeof Array.isArray?Array.isArray(e):"[object Array]"===t.call(e)},s=function(n){if(!n||"[object Object]"!==t.call(n))return!1;var r,a=e.call(n,"constructor"),s=n.constructor&&n.constructor.prototype&&e.call(n.constructor.prototype,"isPrototypeOf");if(n.constructor&&!a&&!s)return!1;for(r in n);return void 0===r||e.call(n,r)},i=function(e,t){n&&"__proto__"===t.name?n(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},o=function(t,n){if("__proto__"===n){if(!e.call(t,n))return;if(r)return r(t,n).value}return t[n]};return ed=function e(){var t,n,r,l,c,u,d=arguments[0],m=1,p=arguments.length,f=!1;for("boolean"==typeof d&&(f=d,d=arguments[1]||{},m=2),(null==d||"object"!=typeof d&&"function"!=typeof d)&&(d={});m<p;++m)if(null!=(t=arguments[m]))for(n in t)r=o(d,n),d!==(l=o(t,n))&&(f&&l&&(s(l)||(c=a(l)))?(c?(c=!1,u=r&&a(r)?r:[]):u=r&&s(r)?r:{},i(d,{name:n,newValue:e(f,u,l)})):void 0!==l&&i(d,{name:n,newValue:l}));return d},ed}(),rd=ie(nd);function ad(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}function sd(){const e=[],t={run:function(...t){let n=-1;const r=t.pop();if("function"!=typeof r)throw new TypeError("Expected function as last argument, not "+r);!function a(s,...i){const o=e[++n];let l=-1;if(s)r(s);else{for(;++l<t.length;)null!==i[l]&&void 0!==i[l]||(i[l]=t[l]);t=i,o?function(e,t){let n;return r;function r(...t){const r=e.length>t.length;let o;r&&t.push(a);try{o=e.apply(this,t)}catch(s){if(r&&n)throw s;return a(s)}r||(o&&o.then&&"function"==typeof o.then?o.then(i,a):o instanceof Error?a(o):i(o))}function a(e,...r){n||(n=!0,t(e,...r))}function i(e){a(null,e)}}(o,a)(...i):r(null,...i)}}(null,...t)},use:function(n){if("function"!=typeof n)throw new TypeError("Expected `middelware` to be a function, not "+n);return e.push(n),t}};return t}const id={basename:function(e,t){if(void 0!==t&&"string"!=typeof t)throw new TypeError('"ext" argument must be a string');od(e);let n,r=0,a=-1,s=e.length;if(void 0===t||0===t.length||t.length>e.length){for(;s--;)if(47===e.codePointAt(s)){if(n){r=s+1;break}}else a<0&&(n=!0,a=s+1);return a<0?"":e.slice(r,a)}if(t===e)return"";let i=-1,o=t.length-1;for(;s--;)if(47===e.codePointAt(s)){if(n){r=s+1;break}}else i<0&&(n=!0,i=s+1),o>-1&&(e.codePointAt(s)===t.codePointAt(o--)?o<0&&(a=s):(o=-1,a=i));r===a?a=i:a<0&&(a=e.length);return e.slice(r,a)},dirname:function(e){if(od(e),0===e.length)return".";let t,n=-1,r=e.length;for(;--r;)if(47===e.codePointAt(r)){if(t){n=r;break}}else t||(t=!0);return n<0?47===e.codePointAt(0)?"/":".":1===n&&47===e.codePointAt(0)?"//":e.slice(0,n)},extname:function(e){od(e);let t,n=e.length,r=-1,a=0,s=-1,i=0;for(;n--;){const o=e.codePointAt(n);if(47!==o)r<0&&(t=!0,r=n+1),46===o?s<0?s=n:1!==i&&(i=1):s>-1&&(i=-1);else if(t){a=n+1;break}}if(s<0||r<0||0===i||1===i&&s===r-1&&s===a+1)return"";return e.slice(s,r)},join:function(...e){let t,n=-1;for(;++n<e.length;)od(e[n]),e[n]&&(t=void 0===t?e[n]:t+"/"+e[n]);return void 0===t?".":function(e){od(e);const t=47===e.codePointAt(0);let n=function(e,t){let n,r,a="",s=0,i=-1,o=0,l=-1;for(;++l<=e.length;){if(l<e.length)n=e.codePointAt(l);else{if(47===n)break;n=47}if(47===n){if(i===l-1||1===o);else if(i!==l-1&&2===o){if(a.length<2||2!==s||46!==a.codePointAt(a.length-1)||46!==a.codePointAt(a.length-2))if(a.length>2){if(r=a.lastIndexOf("/"),r!==a.length-1){r<0?(a="",s=0):(a=a.slice(0,r),s=a.length-1-a.lastIndexOf("/")),i=l,o=0;continue}}else if(a.length>0){a="",s=0,i=l,o=0;continue}t&&(a=a.length>0?a+"/..":"..",s=2)}else a.length>0?a+="/"+e.slice(i+1,l):a=e.slice(i+1,l),s=l-i-1;i=l,o=0}else 46===n&&o>-1?o++:o=-1}return a}(e,!t);0!==n.length||t||(n=".");n.length>0&&47===e.codePointAt(e.length-1)&&(n+="/");return t?"/"+n:n}(t)},sep:"/"};function od(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const ld={cwd:function(){return"/"}};function cd(e){return Boolean(null!==e&&"object"==typeof e&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&void 0===e.auth)}function ud(e){if("string"==typeof e)e=new URL(e);else if(!cd(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if("file:"!==e.protocol){const e=new TypeError("The URL must be of scheme file");throw e.code="ERR_INVALID_URL_SCHEME",e}return function(e){if(""!==e.hostname){const e=new TypeError('File URL host must be "localhost" or empty on darwin');throw e.code="ERR_INVALID_FILE_URL_HOST",e}const t=e.pathname;let n=-1;for(;++n<t.length;)if(37===t.codePointAt(n)&&50===t.codePointAt(n+1)){const e=t.codePointAt(n+2);if(70===e||102===e){const e=new TypeError("File URL path must not include encoded / characters");throw e.code="ERR_INVALID_FILE_URL_PATH",e}}return decodeURIComponent(t)}(e)}const dd=["history","path","basename","stem","extname","dirname"];class md{constructor(e){let t;t=e?cd(e)?{path:e}:"string"==typeof e||function(e){return Boolean(e&&"object"==typeof e&&"byteLength"in e&&"byteOffset"in e)}(e)?{value:e}:e:{},this.cwd="cwd"in t?"":ld.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n,r=-1;for(;++r<dd.length;){const e=dd[r];e in t&&void 0!==t[e]&&null!==t[e]&&(this[e]="history"===e?[...t[e]]:t[e])}for(n in t)dd.includes(n)||(this[n]=t[n])}get basename(){return"string"==typeof this.path?id.basename(this.path):void 0}set basename(e){fd(e,"basename"),pd(e,"basename"),this.path=id.join(this.dirname||"",e)}get dirname(){return"string"==typeof this.path?id.dirname(this.path):void 0}set dirname(e){hd(this.basename,"dirname"),this.path=id.join(e||"",this.basename)}get extname(){return"string"==typeof this.path?id.extname(this.path):void 0}set extname(e){if(pd(e,"extname"),hd(this.dirname,"extname"),e){if(46!==e.codePointAt(0))throw new Error("`extname` must start with `.`");if(e.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=id.join(this.dirname,this.stem+(e||""))}get path(){return this.history[this.history.length-1]}set path(e){cd(e)&&(e=ud(e)),fd(e,"path"),this.path!==e&&this.history.push(e)}get stem(){return"string"==typeof this.path?id.basename(this.path,this.extname):void 0}set stem(e){fd(e,"stem"),pd(e,"stem"),this.path=id.join(this.dirname||"",e+(this.extname||""))}fail(e,t,n){const r=this.message(e,t,n);throw r.fatal=!0,r}info(e,t,n){const r=this.message(e,t,n);return r.fatal=void 0,r}message(e,t,n){const r=new sl(e,t,n);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(e){if(void 0===this.value)return"";if("string"==typeof this.value)return this.value;return new TextDecoder(e||void 0).decode(this.value)}}function pd(e,t){if(e&&e.includes(id.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+id.sep+"`")}function fd(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function hd(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}const gd=function(e){const t=this.constructor.prototype,n=t[e],r=function(){return n.apply(r,arguments)};return Object.setPrototypeOf(r,t),r},xd={}.hasOwnProperty;class yd extends gd{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=sd()}copy(){const e=new yd;let t=-1;for(;++t<this.attachers.length;){const n=this.attachers[t];e.use(...n)}return e.data(rd(!0,{},this.namespace)),e}data(e,t){return"string"==typeof e?2===arguments.length?(Nd("data",this.frozen),this.namespace[e]=t,this):xd.call(this.namespace,e)&&this.namespace[e]||void 0:e?(Nd("data",this.frozen),this.namespace=e,this):this.namespace}freeze(){if(this.frozen)return this;const e=this;for(;++this.freezeIndex<this.attachers.length;){const[t,...n]=this.attachers[this.freezeIndex];if(!1===n[0])continue;!0===n[0]&&(n[0]=void 0);const r=t.call(e,...n);"function"==typeof r&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(e){this.freeze();const t=Cd(e),n=this.parser||this.Parser;return bd("parse",n),n(String(t),t)}process(e,t){const n=this;return this.freeze(),bd("process",this.parser||this.Parser),wd("process",this.compiler||this.Compiler),t?r(void 0,t):new Promise(r);function r(r,a){const s=Cd(e),i=n.parse(s);function o(e,n){e||!n?a(e):r?r(n):t(void 0,n)}n.run(i,s,function(e,t,r){if(e||!t||!r)return o(e);const a=t,s=n.stringify(a,r);!function(e){return"string"==typeof e||function(e){return Boolean(e&&"object"==typeof e&&"byteLength"in e&&"byteOffset"in e)}(e)}(s)?r.result=s:r.value=s,o(e,r)})}}processSync(e){let t,n=!1;return this.freeze(),bd("processSync",this.parser||this.Parser),wd("processSync",this.compiler||this.Compiler),this.process(e,function(e,r){n=!0,Zu(e),t=r}),kd("processSync","process",n),t}run(e,t,n){jd(e),this.freeze();const r=this.transformers;return n||"function"!=typeof t||(n=t,t=void 0),n?a(void 0,n):new Promise(a);function a(a,s){const i=Cd(t);r.run(e,i,function(t,r,i){const o=r||e;t?s(t):a?a(o):n(void 0,o,i)})}}runSync(e,t){let n,r=!1;return this.run(e,t,function(e,t){Zu(e),n=t,r=!0}),kd("runSync","run",r),n}stringify(e,t){this.freeze();const n=Cd(t),r=this.compiler||this.Compiler;return wd("stringify",r),jd(e),r(e,n)}use(e,...t){const n=this.attachers,r=this.namespace;if(Nd("use",this.frozen),null==e);else if("function"==typeof e)o(e,t);else{if("object"!=typeof e)throw new TypeError("Expected usable value, not `"+e+"`");Array.isArray(e)?i(e):s(e)}return this;function a(e){if("function"==typeof e)o(e,[]);else{if("object"!=typeof e)throw new TypeError("Expected usable value, not `"+e+"`");if(Array.isArray(e)){const[t,...n]=e;o(t,n)}else s(e)}}function s(e){if(!("plugins"in e)&&!("settings"in e))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");i(e.plugins),e.settings&&(r.settings=rd(!0,r.settings,e.settings))}function i(e){let t=-1;if(null==e);else{if(!Array.isArray(e))throw new TypeError("Expected a list of plugins, not `"+e+"`");for(;++t<e.length;){a(e[t])}}}function o(e,t){let r=-1,a=-1;for(;++r<n.length;)if(n[r][0]===e){a=r;break}if(-1===a)n.push([e,...t]);else if(t.length>0){let[r,...s]=t;const i=n[a][1];ad(i)&&ad(r)&&(r=rd(!0,i,r)),n[a]=[e,r,...s]}}}}const vd=(new yd).freeze();function bd(e,t){if("function"!=typeof t)throw new TypeError("Cannot `"+e+"` without `parser`")}function wd(e,t){if("function"!=typeof t)throw new TypeError("Cannot `"+e+"` without `compiler`")}function Nd(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function jd(e){if(!ad(e)||"string"!=typeof e.type)throw new TypeError("Expected node, got `"+e+"`")}function kd(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function Cd(e){return function(e){return Boolean(e&&"object"==typeof e&&"message"in e&&"messages"in e)}(e)?e:new md(e)}const Sd=[],Ed={allowDangerousHtml:!0},Id=/^(https?|ircs?|mailto|xmpp)$/i,Td=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Ad(e){const t=function(e){const t=e.rehypePlugins||Sd,n=e.remarkPlugins||Sd,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Ed}:Ed,a=vd().use(yu).use(n).use(Ju,r).use(t);return a}(e),n=function(e){const t=e.children||"",n=new md;"string"==typeof t&&(n.value=t);return n}(e);return function(e,t){const n=t.allowedElements,r=t.allowElement,a=t.components,s=t.disallowedElements,i=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||Pd;for(const u of Td)Object.hasOwn(t,u.from)&&Ji((u.from,u.to&&u.to,u.id));return qu(e,c),ml(e,{Fragment:fe.Fragment,components:a,ignoreInvalidStyle:!0,jsx:fe.jsx,jsxs:fe.jsxs,passKeys:!0,passNode:!0});function c(e,t,a){if("raw"===e.type&&a&&"number"==typeof t)return i?a.children.splice(t,1):a.children[t]={type:"text",value:e.value},t;if("element"===e.type){let t;for(t in Nl)if(Object.hasOwn(Nl,t)&&Object.hasOwn(e.properties,t)){const n=e.properties[t],r=Nl[t];(null===r||r.includes(e.tagName))&&(e.properties[t]=l(String(n||""),t,e))}}if("element"===e.type){let i=n?!n.includes(e.tagName):!!s&&s.includes(e.tagName);if(!i&&r&&"number"==typeof t&&(i=!r(e,t,a)),i&&a&&"number"==typeof t)return o&&e.children?a.children.splice(t,1,...e.children):a.children.splice(t,1),t}}}(t.runSync(t.parse(n),n),e)}function Pd(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),a=e.indexOf("/");return-1===t||-1!==a&&t>a||-1!==n&&t>n||-1!==r&&t>r||Id.test(e.slice(0,t))?e:""}function _d(e,t){const n=String(e);if("string"!=typeof t)throw new TypeError("Expected character");let r=0,a=n.indexOf(t);for(;-1!==a;)r++,a=n.indexOf(t,a+t.length);return r}function Dd(e,t,n){const r=Lu((n||{}).ignore||[]),a=function(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!e[0]||Array.isArray(e[0])?e:[e];let r=-1;for(;++r<n.length;){const e=n[r];t.push([Fd(e[0]),Rd(e[1])])}return t}(t);let s=-1;for(;++s<a.length;)$u(e,"text",i);function i(e,t){let n,i=-1;for(;++i<t.length;){const e=t[i],a=n?n.children:void 0;if(r(e,a?a.indexOf(e):void 0,n))return;n=e}if(n)return function(e,t){const n=t[t.length-1],r=a[s][0],i=a[s][1];let o=0;const l=n.children.indexOf(e);let c=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){const n=d.index,a={index:d.index,input:d.input,stack:[...t,e]};let s=i(...d,a);if("string"==typeof s&&(s=s.length>0?{type:"text",value:s}:void 0),!1===s?r.lastIndex=n+1:(o!==n&&u.push({type:"text",value:e.value.slice(o,n)}),Array.isArray(s)?u.push(...s):s&&u.push(s),o=n+d[0].length,c=!0),!r.global)break;d=r.exec(e.value)}c?(o<e.value.length&&u.push({type:"text",value:e.value.slice(o)}),n.children.splice(l,1,...u)):u=[e];return l+u.length}(e,t)}}function Fd(e){return"string"==typeof e?new RegExp(function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}(e),"g"):e}function Rd(e){return"function"==typeof e?e:function(){return e}}const Ld="phrasing",Md=["autolink","link","image","label"];function Od(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function zd(e){this.config.enter.autolinkProtocol.call(this,e)}function Ud(e){this.config.exit.autolinkProtocol.call(this,e)}function Bd(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function $d(e){this.config.exit.autolinkEmail.call(this,e)}function qd(e){this.exit(e)}function Vd(e){Dd(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Hd],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,Wd]],{ignore:["link","linkReference"]})}function Hd(e,t,n,r,a){let s="";if(!Qd(a))return!1;if(/^w/i.test(t)&&(n=t+n,t="",s="http://"),!function(e){const t=e.split(".");if(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))return!1;return!0}(n))return!1;const i=function(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const a=_d(e,"(");let s=_d(e,")");for(;-1!==r&&a>s;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),s++;return[e,n]}(n+r);if(!i[0])return!1;const o={type:"link",title:null,url:s+t+i[0],children:[{type:"text",value:t+i[0]}]};return i[1]?[o,{type:"text",value:i[1]}]:o}function Wd(e,t,n,r){return!(!Qd(r,!0)||/[-\d_]$/.test(n))&&{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function Qd(e,t){const n=e.input.charCodeAt(e.index-1);return(0===e.index||Kl(n)||Ql(n))&&(!t||47!==n)}function Kd(){this.buffer()}function Xd(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Yd(){this.buffer()}function Gd(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Jd(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ll(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Zd(e){this.exit(e)}function em(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=Ll(this.sliceSerialize(e)).toLowerCase(),n.label=t}function tm(e){this.exit(e)}function nm(e,t,n,r){const a=n.createTracker(r);let s=a.move("[^");const i=n.enter("footnoteReference"),o=n.enter("reference");return s+=a.move(n.safe(n.associationId(e),{after:"]",before:s})),o(),i(),s+=a.move("]"),s}function rm(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:function(e,n,r,a){const s=r.createTracker(a);let i=s.move("[^");const o=r.enter("footnoteDefinition"),l=r.enter("label");i+=s.move(r.safe(r.associationId(e),{before:i,after:"]"})),l(),i+=s.move("]:"),e.children&&e.children.length>0&&(s.shift(4),i+=s.move((t?"\n":" ")+r.indentLines(r.containerFlow(e,s.current()),t?sm:am)));return o(),i},footnoteReference:nm},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]}}function am(e,t,n){return 0===t?e:sm(e,t,n)}function sm(e,t,n){return(n?"":" ")+e}nm.peek=function(){return"["};const im=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];function om(e){this.enter({type:"delete",children:[]},e)}function lm(e){this.exit(e)}function cm(e,t,n,r){const a=n.createTracker(r),s=n.enter("strikethrough");let i=a.move("~~");return i+=n.containerPhrasing(e,{...a.current(),before:i,after:"~"}),i+=a.move("~~"),s(),i}function um(e){return e.length}function dm(e){return null==e?"":String(e)}function mm(e){const t="string"==typeof e?e.codePointAt(0):0;return 67===t||99===t?99:76===t||108===t?108:82===t||114===t?114:0}function pm(e,t,n){return">"+(n?"":" ")+e}function fm(e,t){return hm(e,t.inConstruct,!0)&&!hm(e,t.notInConstruct,!1)}function hm(e,t,n){if("string"==typeof t&&(t=[t]),!t||0===t.length)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function gm(e,t,n,r){let a=-1;for(;++a<n.unsafe.length;)if("\n"===n.unsafe[a].character&&fm(n.stack,n.unsafe[a]))return/[ \t]/.test(r.before)?"":" ";return"\\\n"}function xm(e,t,n){return(n?"":" ")+e}function ym(e){const t=e.options.quote||'"';if('"'!==t&&"'"!==t)throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function vm(e){return"&#x"+e.toString(16).toUpperCase()+";"}function bm(e,t,n){const r=tc(e),a=tc(t);return void 0===r?void 0===a?"_"===n?{inside:!0,outside:!0}:{inside:!1,outside:!1}:1===a?{inside:!0,outside:!0}:{inside:!1,outside:!0}:1===r?void 0===a?{inside:!1,outside:!1}:1===a?{inside:!0,outside:!0}:{inside:!1,outside:!1}:void 0===a?{inside:!1,outside:!1}:1===a?{inside:!0,outside:!1}:{inside:!1,outside:!1}}function wm(e,t,n,r){const a=function(e){const t=e.options.emphasis||"*";if("*"!==t&&"_"!==t)throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}(n),s=n.enter("emphasis"),i=n.createTracker(r),o=i.move(a);let l=i.move(n.containerPhrasing(e,{after:a,before:o,...i.current()}));const c=l.charCodeAt(0),u=bm(r.before.charCodeAt(r.before.length-1),c,a);u.inside&&(l=vm(c)+l.slice(1));const d=l.charCodeAt(l.length-1),m=bm(r.after.charCodeAt(0),d,a);m.inside&&(l=l.slice(0,-1)+vm(d));const p=i.move(a);return s(),n.attentionEncodeSurroundingInfo={after:m.outside,before:u.outside},o+l+p}function Nm(e){return e.value||""}function jm(e,t,n,r){const a=ym(n),s='"'===a?"Quote":"Apostrophe",i=n.enter("image");let o=n.enter("label");const l=n.createTracker(r);let c=l.move("![");return c+=l.move(n.safe(e.alt,{before:c,after:"]",...l.current()})),c+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),c+=l.move("<"),c+=l.move(n.safe(e.url,{before:c,after:">",...l.current()})),c+=l.move(">")):(o=n.enter("destinationRaw"),c+=l.move(n.safe(e.url,{before:c,after:e.title?" ":")",...l.current()}))),o(),e.title&&(o=n.enter(`title${s}`),c+=l.move(" "+a),c+=l.move(n.safe(e.title,{before:c,after:a,...l.current()})),c+=l.move(a),o()),c+=l.move(")"),i(),c}function km(e,t,n,r){const a=e.referenceType,s=n.enter("imageReference");let i=n.enter("label");const o=n.createTracker(r);let l=o.move("![");const c=n.safe(e.alt,{before:l,after:"]",...o.current()});l+=o.move(c+"]["),i();const u=n.stack;n.stack=[],i=n.enter("reference");const d=n.safe(n.associationId(e),{before:l,after:"]",...o.current()});return i(),n.stack=u,s(),"full"!==a&&c&&c===d?"shortcut"===a?l=l.slice(0,-1):l+=o.move("]"):l+=o.move(d+"]"),l}function Cm(e,t,n){let r=e.value||"",a="`",s=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(r);)a+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++s<n.unsafe.length;){const e=n.unsafe[s],t=n.compilePattern(e);let a;if(e.atBreak)for(;a=t.exec(r);){let e=a.index;10===r.charCodeAt(e)&&13===r.charCodeAt(e-1)&&e--,r=r.slice(0,e)+" "+r.slice(a.index+1)}}return a+r+a}function Sm(e,t){const n=kl(e);return Boolean(!t.options.resourceLink&&e.url&&!e.title&&e.children&&1===e.children.length&&"text"===e.children[0].type&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}function Em(e,t,n,r){const a=ym(n),s='"'===a?"Quote":"Apostrophe",i=n.createTracker(r);let o,l;if(Sm(e,n)){const t=n.stack;n.stack=[],o=n.enter("autolink");let r=i.move("<");return r+=i.move(n.containerPhrasing(e,{before:r,after:">",...i.current()})),r+=i.move(">"),o(),n.stack=t,r}o=n.enter("link"),l=n.enter("label");let c=i.move("[");return c+=i.move(n.containerPhrasing(e,{before:c,after:"](",...i.current()})),c+=i.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),c+=i.move("<"),c+=i.move(n.safe(e.url,{before:c,after:">",...i.current()})),c+=i.move(">")):(l=n.enter("destinationRaw"),c+=i.move(n.safe(e.url,{before:c,after:e.title?" ":")",...i.current()}))),l(),e.title&&(l=n.enter(`title${s}`),c+=i.move(" "+a),c+=i.move(n.safe(e.title,{before:c,after:a,...i.current()})),c+=i.move(a),l()),c+=i.move(")"),o(),c}function Im(e,t,n,r){const a=e.referenceType,s=n.enter("linkReference");let i=n.enter("label");const o=n.createTracker(r);let l=o.move("[");const c=n.containerPhrasing(e,{before:l,after:"]",...o.current()});l+=o.move(c+"]["),i();const u=n.stack;n.stack=[],i=n.enter("reference");const d=n.safe(n.associationId(e),{before:l,after:"]",...o.current()});return i(),n.stack=u,s(),"full"!==a&&c&&c===d?"shortcut"===a?l=l.slice(0,-1):l+=o.move("]"):l+=o.move(d+"]"),l}function Tm(e){const t=e.options.bullet||"*";if("*"!==t&&"+"!==t&&"-"!==t)throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Am(e){const t=e.options.rule||"*";if("*"!==t&&"-"!==t&&"_"!==t)throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}cm.peek=function(){return"~"},wm.peek=function(e,t,n){return n.options.emphasis||"*"},Nm.peek=function(){return"<"},jm.peek=function(){return"!"},km.peek=function(){return"!"},Cm.peek=function(){return"`"},Em.peek=function(e,t,n){return Sm(e,n)?"<":"["},Im.peek=function(){return"["};const Pm=Lu(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function _m(e,t,n,r){const a=function(e){const t=e.options.strong||"*";if("*"!==t&&"_"!==t)throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}(n),s=n.enter("strong"),i=n.createTracker(r),o=i.move(a+a);let l=i.move(n.containerPhrasing(e,{after:a,before:o,...i.current()}));const c=l.charCodeAt(0),u=bm(r.before.charCodeAt(r.before.length-1),c,a);u.inside&&(l=vm(c)+l.slice(1));const d=l.charCodeAt(l.length-1),m=bm(r.after.charCodeAt(0),d,a);m.inside&&(l=l.slice(0,-1)+vm(d));const p=i.move(a+a);return s(),n.attentionEncodeSurroundingInfo={after:m.outside,before:u.outside},o+l+p}_m.peek=function(e,t,n){return n.options.strong||"*"};const Dm={blockquote:function(e,t,n,r){const a=n.enter("blockquote"),s=n.createTracker(r);s.move("> "),s.shift(2);const i=n.indentLines(n.containerFlow(e,s.current()),pm);return a(),i},break:gm,code:function(e,t,n,r){const a=function(e){const t=e.options.fence||"`";if("`"!==t&&"~"!==t)throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}(n),s=e.value||"",i="`"===a?"GraveAccent":"Tilde";if(function(e,t){return Boolean(!1===t.options.fences&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}(e,n)){const e=n.enter("codeIndented"),t=n.indentLines(s,xm);return e(),t}const o=n.createTracker(r),l=a.repeat(Math.max(function(e,t){const n=String(e);let r=n.indexOf(t),a=r,s=0,i=0;if("string"!=typeof t)throw new TypeError("Expected substring");for(;-1!==r;)r===a?++s>i&&(i=s):s=1,a=r+t.length,r=n.indexOf(t,a);return i}(s,a)+1,3)),c=n.enter("codeFenced");let u=o.move(l);if(e.lang){const t=n.enter(`codeFencedLang${i}`);u+=o.move(n.safe(e.lang,{before:u,after:" ",encode:["`"],...o.current()})),t()}if(e.lang&&e.meta){const t=n.enter(`codeFencedMeta${i}`);u+=o.move(" "),u+=o.move(n.safe(e.meta,{before:u,after:"\n",encode:["`"],...o.current()})),t()}return u+=o.move("\n"),s&&(u+=o.move(s+"\n")),u+=o.move(l),c(),u},definition:function(e,t,n,r){const a=ym(n),s='"'===a?"Quote":"Apostrophe",i=n.enter("definition");let o=n.enter("label");const l=n.createTracker(r);let c=l.move("[");return c+=l.move(n.safe(n.associationId(e),{before:c,after:"]",...l.current()})),c+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=n.enter("destinationLiteral"),c+=l.move("<"),c+=l.move(n.safe(e.url,{before:c,after:">",...l.current()})),c+=l.move(">")):(o=n.enter("destinationRaw"),c+=l.move(n.safe(e.url,{before:c,after:e.title?" ":"\n",...l.current()}))),o(),e.title&&(o=n.enter(`title${s}`),c+=l.move(" "+a),c+=l.move(n.safe(e.title,{before:c,after:a,...l.current()})),c+=l.move(a),o()),i(),c},emphasis:wm,hardBreak:gm,heading:function(e,t,n,r){const a=Math.max(Math.min(6,e.depth||1),1),s=n.createTracker(r);if(function(e,t){let n=!1;return qu(e,function(e){if("value"in e&&/\r?\n|\r/.test(e.value)||"break"===e.type)return n=!0,Bu}),Boolean((!e.depth||e.depth<3)&&kl(e)&&(t.options.setext||n))}(e,n)){const t=n.enter("headingSetext"),r=n.enter("phrasing"),i=n.containerPhrasing(e,{...s.current(),before:"\n",after:"\n"});return r(),t(),i+"\n"+(1===a?"=":"-").repeat(i.length-(Math.max(i.lastIndexOf("\r"),i.lastIndexOf("\n"))+1))}const i="#".repeat(a),o=n.enter("headingAtx"),l=n.enter("phrasing");s.move(i+" ");let c=n.containerPhrasing(e,{before:"# ",after:"\n",...s.current()});return/^[\t ]/.test(c)&&(c=vm(c.charCodeAt(0))+c.slice(1)),c=c?i+" "+c:i,n.options.closeAtx&&(c+=" "+i),l(),o(),c},html:Nm,image:jm,imageReference:km,inlineCode:Cm,link:Em,linkReference:Im,list:function(e,t,n,r){const a=n.enter("list"),s=n.bulletCurrent;let i=e.ordered?function(e){const t=e.options.bulletOrdered||".";if("."!==t&&")"!==t)throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}(n):Tm(n);const o=e.ordered?"."===i?")":".":function(e){const t=Tm(e),n=e.options.bulletOther;if(!n)return"*"===t?"-":"*";if("*"!==n&&"+"!==n&&"-"!==n)throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}(n);let l=!(!t||!n.bulletLastUsed)&&i===n.bulletLastUsed;if(!e.ordered){const t=e.children?e.children[0]:void 0;if("*"!==i&&"-"!==i||!t||t.children&&t.children[0]||"list"!==n.stack[n.stack.length-1]||"listItem"!==n.stack[n.stack.length-2]||"list"!==n.stack[n.stack.length-3]||"listItem"!==n.stack[n.stack.length-4]||0!==n.indexStack[n.indexStack.length-1]||0!==n.indexStack[n.indexStack.length-2]||0!==n.indexStack[n.indexStack.length-3]||(l=!0),Am(n)===i&&t){let t=-1;for(;++t<e.children.length;){const n=e.children[t];if(n&&"listItem"===n.type&&n.children&&n.children[0]&&"thematicBreak"===n.children[0].type){l=!0;break}}}}l&&(i=o),n.bulletCurrent=i;const c=n.containerFlow(e,r);return n.bulletLastUsed=i,n.bulletCurrent=s,a(),c},listItem:function(e,t,n,r){const a=function(e){const t=e.options.listItemIndent||"one";if("tab"!==t&&"one"!==t&&"mixed"!==t)throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}(n);let s=n.bulletCurrent||Tm(n);t&&"list"===t.type&&t.ordered&&(s=("number"==typeof t.start&&t.start>-1?t.start:1)+(!1===n.options.incrementListMarker?0:t.children.indexOf(e))+s);let i=s.length+1;("tab"===a||"mixed"===a&&(t&&"list"===t.type&&t.spread||e.spread))&&(i=4*Math.ceil(i/4));const o=n.createTracker(r);o.move(s+" ".repeat(i-s.length)),o.shift(i);const l=n.enter("listItem"),c=n.indentLines(n.containerFlow(e,o.current()),function(e,t,n){if(t)return(n?"":" ".repeat(i))+e;return(n?s:s+" ".repeat(i-s.length))+e});return l(),c},paragraph:function(e,t,n,r){const a=n.enter("paragraph"),s=n.enter("phrasing"),i=n.containerPhrasing(e,r);return s(),a(),i},root:function(e,t,n,r){return(e.children.some(function(e){return Pm(e)})?n.containerPhrasing:n.containerFlow).call(n,e,r)},strong:_m,text:function(e,t,n,r){return n.safe(e.value,r)},thematicBreak:function(e,t,n){const r=(Am(n)+(n.options.ruleSpaces?" ":"")).repeat(function(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}(n));return n.options.ruleSpaces?r.slice(0,-1):r}};function Fm(e){const t=e._align;this.enter({type:"table",align:t.map(function(e){return"none"===e?null:e}),children:[]},e),this.data.inTable=!0}function Rm(e){this.exit(e),this.data.inTable=void 0}function Lm(e){this.enter({type:"tableRow",children:[]},e)}function Mm(e){this.exit(e)}function Om(e){this.enter({type:"tableCell",children:[]},e)}function zm(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,Um));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function Um(e,t){return"|"===t?t:e}function Bm(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,a=t.stringLength,s=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:"\n",inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[\t :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:function(e,t,n){let r=Dm.inlineCode(e,t,n);n.stack.includes("tableCell")&&(r=r.replace(/\|/g,"\\$&"));return r},table:function(e,t,n,r){return o(function(e,t,n){const r=e.children;let a=-1;const s=[],i=t.enter("table");for(;++a<r.length;)s[a]=l(r[a],t,n);return i(),s}(e,n,r),e.align)},tableCell:i,tableRow:function(e,t,n,r){const a=l(e,n,r),s=o([a]);return s.slice(0,s.indexOf("\n"))}}};function i(e,t,n,r){const a=n.enter("tableCell"),i=n.enter("phrasing"),o=n.containerPhrasing(e,{...r,before:s,after:s});return i(),a(),o}function o(e,t){return function(e,t){const n=t||{},r=(n.align||[]).concat(),a=n.stringLength||um,s=[],i=[],o=[],l=[];let c=0,u=-1;for(;++u<e.length;){const t=[],r=[];let s=-1;for(e[u].length>c&&(c=e[u].length);++s<e[u].length;){const i=dm(e[u][s]);if(!1!==n.alignDelimiters){const e=a(i);r[s]=e,(void 0===l[s]||e>l[s])&&(l[s]=e)}t.push(i)}i[u]=t,o[u]=r}let d=-1;if("object"==typeof r&&"length"in r)for(;++d<c;)s[d]=mm(r[d]);else{const e=mm(r);for(;++d<c;)s[d]=e}d=-1;const m=[],p=[];for(;++d<c;){const e=s[d];let t="",r="";99===e?(t=":",r=":"):108===e?t=":":114===e&&(r=":");let a=!1===n.alignDelimiters?1:Math.max(1,l[d]-t.length-r.length);const i=t+"-".repeat(a)+r;!1!==n.alignDelimiters&&(a=t.length+a+r.length,a>l[d]&&(l[d]=a),p[d]=a),m[d]=i}i.splice(1,0,m),o.splice(1,0,p),u=-1;const f=[];for(;++u<i.length;){const e=i[u],t=o[u];d=-1;const r=[];for(;++d<c;){const a=e[d]||"";let i="",o="";if(!1!==n.alignDelimiters){const e=l[d]-(t[d]||0),n=s[d];114===n?i=" ".repeat(e):99===n?e%2?(i=" ".repeat(e/2+.5),o=" ".repeat(e/2-.5)):(i=" ".repeat(e/2),o=i):o=" ".repeat(e)}!1===n.delimiterStart||d||r.push("|"),!1===n.padding||!1===n.alignDelimiters&&""===a||!1===n.delimiterStart&&!d||r.push(" "),!1!==n.alignDelimiters&&r.push(i),r.push(a),!1!==n.alignDelimiters&&r.push(o),!1!==n.padding&&r.push(" "),!1===n.delimiterEnd&&d===c-1||r.push("|")}f.push(!1===n.delimiterEnd?r.join("").replace(/ +$/,""):r.join(""))}return f.join("\n")}(e,{align:t,alignDelimiters:r,padding:n,stringLength:a})}function l(e,t,n){const r=e.children;let a=-1;const s=[],o=t.enter("tableRow");for(;++a<r.length;)s[a]=i(r[a],0,t,n);return o(),s}}function $m(e){const t=this.stack[this.stack.length-2];t.type,t.checked="taskListCheckValueChecked"===e.type}function qm(e){const t=this.stack[this.stack.length-2];if(t&&"listItem"===t.type&&"boolean"==typeof t.checked){const e=this.stack[this.stack.length-1];e.type;const n=e.children[0];if(n&&"text"===n.type){const r=t.children;let a,s=-1;for(;++s<r.length;){const e=r[s];if("paragraph"===e.type){a=e;break}}a===e&&(n.value=n.value.slice(1),0===n.value.length?e.children.shift():e.position&&n.position&&"number"==typeof n.position.start.offset&&(n.position.start.column++,n.position.start.offset++,e.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function Vm(e,t,n,r){const a=e.children[0],s="boolean"==typeof e.checked&&a&&"paragraph"===a.type,i="["+(e.checked?"x":" ")+"] ",o=n.createTracker(r);s&&o.move(i);let l=Dm.listItem(e,t,n,{...r,...o.current()});return s&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,function(e){return e+i})),l}const Hm={tokenize:function(e,t,n){let r=0;return function t(s){if((87===s||119===s)&&r<3)return r++,e.consume(s),t;if(46===s&&3===r)return e.consume(s),a;return n(s)};function a(e){return null===e?n(e):t(e)}},partial:!0},Wm={tokenize:function(e,t,n){let r,a,s;return i;function i(t){return 46===t||95===t?e.check(Km,l,o)(t):null===t||Hl(t)||Kl(t)||45!==t&&Ql(t)?l(t):(s=!0,e.consume(t),i)}function o(t){return 95===t?r=!0:(a=r,r=void 0),e.consume(t),i}function l(e){return a||r||!s?n(e):t(e)}},partial:!0},Qm={tokenize:function(e,t){let n=0,r=0;return a;function a(i){return 40===i?(n++,e.consume(i),a):41===i&&r<n?s(i):33===i||34===i||38===i||39===i||41===i||42===i||44===i||46===i||58===i||59===i||60===i||63===i||93===i||95===i||126===i?e.check(Km,t,s)(i):null===i||Hl(i)||Kl(i)?t(i):(e.consume(i),a)}function s(t){return 41===t&&r++,e.consume(t),a}},partial:!0},Km={tokenize:function(e,t,n){return r;function r(i){return 33===i||34===i||39===i||41===i||42===i||44===i||46===i||58===i||59===i||63===i||95===i||126===i?(e.consume(i),r):38===i?(e.consume(i),s):93===i?(e.consume(i),a):60===i||null===i||Hl(i)||Kl(i)?t(i):n(i)}function a(e){return null===e||40===e||91===e||Hl(e)||Kl(e)?t(e):r(e)}function s(e){return Ml(e)?i(e):n(e)}function i(t){return 59===t?(e.consume(t),r):Ml(t)?(e.consume(t),i):n(t)}},partial:!0},Xm={tokenize:function(e,t,n){return function(t){return e.consume(t),r};function r(e){return Ol(e)?n(e):t(e)}},partial:!0},Ym={name:"wwwAutolink",tokenize:function(e,t,n){const r=this;return function(t){if(87!==t&&119!==t||!tp.call(r,r.previous)||sp(r.events))return n(t);return e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Hm,e.attempt(Wm,e.attempt(Qm,a),n),n)(t)};function a(n){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(n)}},previous:tp},Gm={name:"protocolAutolink",tokenize:function(e,t,n){const r=this;let a="",s=!1;return function(t){if((72===t||104===t)&&np.call(r,r.previous)&&!sp(r.events))return e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(t),e.consume(t),i;return n(t)};function i(t){if(Ml(t)&&a.length<5)return a+=String.fromCodePoint(t),e.consume(t),i;if(58===t){const n=a.toLowerCase();if("http"===n||"https"===n)return e.consume(t),o}return n(t)}function o(t){return 47===t?(e.consume(t),s?l:(s=!0,o)):n(t)}function l(t){return null===t||Ul(t)||Hl(t)||Kl(t)||Ql(t)?n(t):e.attempt(Wm,e.attempt(Qm,c),n)(t)}function c(n){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(n)}},previous:np},Jm={name:"emailAutolink",tokenize:function(e,t,n){const r=this;let a,s;return function(t){if(!ap(t)||!rp.call(r,r.previous)||sp(r.events))return n(t);return e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),i(t)};function i(t){return ap(t)?(e.consume(t),i):64===t?(e.consume(t),o):n(t)}function o(t){return 46===t?e.check(Xm,c,l)(t):45===t||95===t||Ol(t)?(s=!0,e.consume(t),o):c(t)}function l(t){return e.consume(t),a=!0,o}function c(i){return s&&a&&Ml(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(i)):n(i)}},previous:rp},Zm={};let ep=48;for(;ep<123;)Zm[ep]=Jm,ep++,58===ep?ep=65:91===ep&&(ep=97);function tp(e){return null===e||40===e||42===e||95===e||91===e||93===e||126===e||Hl(e)}function np(e){return!Ml(e)}function rp(e){return!(47===e||ap(e))}function ap(e){return 43===e||45===e||46===e||95===e||Ol(e)}function sp(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if(("labelLink"===r.type||"labelImage"===r.type)&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}Zm[43]=Jm,Zm[45]=Jm,Zm[46]=Jm,Zm[95]=Jm,Zm[72]=[Jm,Gm],Zm[104]=[Jm,Gm],Zm[87]=[Jm,Ym],Zm[119]=[Jm,Ym];const ip={tokenize:function(e,t,n){const r=this;return Gl(e,function(e){const a=r.events[r.events.length-1];return a&&"gfmFootnoteDefinitionIndent"===a[1].type&&4===a[2].sliceSerialize(a[1],!0).length?t(e):n(e)},"gfmFootnoteDefinitionIndent",5)},partial:!0};function op(e,t,n){const r=this;let a=r.events.length;const s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i;for(;a--;){const e=r.events[a][1];if("labelImage"===e.type){i=e;break}if("gfmFootnoteCall"===e.type||"labelLink"===e.type||"label"===e.type||"image"===e.type||"link"===e.type)break}return function(a){if(!i||!i._balanced)return n(a);const o=Ll(r.sliceSerialize({start:i.end,end:r.now()}));if(94!==o.codePointAt(0)||!s.includes(o.slice(1)))return n(a);return e.enter("gfmFootnoteCallLabelMarker"),e.consume(a),e.exit("gfmFootnoteCallLabelMarker"),t(a)}}function lp(e,t){let n=e.length;for(;n--;)if("labelImage"===e[n][1].type&&"enter"===e[n][0]){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const s={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},i={type:"chunkString",contentType:"string",start:Object.assign({},s.start),end:Object.assign({},s.end)},o=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",a,t],["exit",a,t],["enter",s,t],["enter",i,t],["exit",i,t],["exit",s,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...o),e}function cp(e,t,n){const r=this,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,i=0;return function(t){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(t),e.exit("gfmFootnoteCallLabelMarker"),o};function o(t){return 94!==t?n(t):(e.enter("gfmFootnoteCallMarker"),e.consume(t),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",l)}function l(o){if(i>999||93===o&&!s||null===o||91===o||Hl(o))return n(o);if(93===o){e.exit("chunkString");const s=e.exit("gfmFootnoteCallString");return a.includes(Ll(r.sliceSerialize(s)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(o),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(o)}return Hl(o)||(s=!0),i++,e.consume(o),92===o?c:l}function c(t){return 91===t||92===t||93===t?(e.consume(t),i++,l):l(t)}}function up(e,t,n){const r=this,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let s,i,o=0;return function(t){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionLabelMarker"),l};function l(t){return 94===t?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",c):n(t)}function c(t){if(o>999||93===t&&!i||null===t||91===t||Hl(t))return n(t);if(93===t){e.exit("chunkString");const n=e.exit("gfmFootnoteDefinitionLabelString");return s=Ll(r.sliceSerialize(n)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(t),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),d}return Hl(t)||(i=!0),o++,e.consume(t),92===t?u:c}function u(t){return 91===t||92===t||93===t?(e.consume(t),o++,c):c(t)}function d(t){return 58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),a.includes(s)||a.push(s),Gl(e,m,"gfmFootnoteDefinitionWhitespace")):n(t)}function m(e){return t(e)}}function dp(e,t,n){return e.check(ic,t,e.attempt(ip,t,n))}function mp(e){e.exit("gfmFootnoteDefinition")}function pp(e){let t=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:function(e,n,r){const a=this.previous,s=this.events;let i=0;return function(t){if(126===a&&"characterEscape"!==s[s.length-1][1].type)return r(t);return e.enter("strikethroughSequenceTemporary"),o(t)};function o(s){const l=tc(a);if(126===s)return i>1?r(s):(e.consume(s),i++,o);if(i<2&&!t)return r(s);const c=e.exit("strikethroughSequenceTemporary"),u=tc(s);return c._open=!u||2===u&&Boolean(l),c._close=!l||2===l&&Boolean(u),n(s)}},resolveAll:function(e,t){let n=-1;for(;++n<e.length;)if("enter"===e[n][0]&&"strikethroughSequenceTemporary"===e[n][1].type&&e[n][1]._close){let r=n;for(;r--;)if("exit"===e[r][0]&&"strikethroughSequenceTemporary"===e[r][1].type&&e[r][1]._open&&e[n][1].end.offset-e[n][1].start.offset===e[r][1].end.offset-e[r][1].start.offset){e[n][1].type="strikethroughSequence",e[r][1].type="strikethroughSequence";const a={type:"strikethrough",start:Object.assign({},e[r][1].start),end:Object.assign({},e[n][1].end)},s={type:"strikethroughText",start:Object.assign({},e[r][1].end),end:Object.assign({},e[n][1].start)},i=[["enter",a,t],["enter",e[r][1],t],["exit",e[r][1],t],["enter",s,t]],o=t.parser.constructs.insideSpan.null;o&&Tl(i,i.length,0,nc(o,e.slice(r+1,n),t)),Tl(i,i.length,0,[["exit",s,t],["enter",e[n][1],t],["exit",e[n][1],t],["exit",a,t]]),Tl(e,r-1,n-r+3,i),n=r+i.length-2;break}}n=-1;for(;++n<e.length;)"strikethroughSequenceTemporary"===e[n][1].type&&(e[n][1].type="data");return e}};return null==t&&(t=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}}}class fp{constructor(){this.map=[]}add(e,t,n){!function(e,t,n,r){let a=0;if(0===n&&0===r.length)return;for(;a<e.map.length;){if(e.map[a][0]===t)return e.map[a][1]+=n,void e.map[a][2].push(...r);a+=1}e.map.push([t,n,r])}(this,e,t,n)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),0===this.map.length)return;let t=this.map.length;const n=[];for(;t>0;)t-=1,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(const t of r)e.push(t);r=n.pop()}this.map.length=0}}function hp(e,t){let n=!1;const r=[];for(;t<e.length;){const a=e[t];if(n){if("enter"===a[0])"tableContent"===a[1].type&&r.push("tableDelimiterMarker"===e[t+1][1].type?"left":"none");else if("tableContent"===a[1].type){if("tableDelimiterMarker"===e[t-1][1].type){const e=r.length-1;r[e]="left"===r[e]?"center":"right"}}else if("tableDelimiterRow"===a[1].type)break}else"enter"===a[0]&&"tableDelimiterRow"===a[1].type&&(n=!0);t+=1}return r}function gp(e,t,n){const r=this;let a,s=0,i=0;return function(e){let t=r.events.length-1;for(;t>-1;){const e=r.events[t][1].type;if("lineEnding"!==e&&"linePrefix"!==e)break;t--}const a=t>-1?r.events[t][1].type:null,s="tableHead"===a||"tableRow"===a?b:o;if(s===b&&r.parser.lazy[r.now().line])return n(e);return s(e)};function o(t){return e.enter("tableHead"),e.enter("tableRow"),function(e){if(124===e)return l(e);return a=!0,i+=1,l(e)}(t)}function l(t){return null===t?n(t):Vl(t)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),d):n(t):Wl(t)?Gl(e,l,"whitespace")(t):(i+=1,a&&(a=!1,s+=1),124===t?(e.enter("tableCellDivider"),e.consume(t),e.exit("tableCellDivider"),a=!0,l):(e.enter("data"),c(t)))}function c(t){return null===t||124===t||Hl(t)?(e.exit("data"),l(t)):(e.consume(t),92===t?u:c)}function u(t){return 92===t||124===t?(e.consume(t),c):c(t)}function d(t){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(t):(e.enter("tableDelimiterRow"),a=!1,Wl(t)?Gl(e,m,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):m(t))}function m(t){return 45===t||58===t?f(t):124===t?(a=!0,e.enter("tableCellDivider"),e.consume(t),e.exit("tableCellDivider"),p):v(t)}function p(t){return Wl(t)?Gl(e,f,"whitespace")(t):f(t)}function f(t){return 58===t?(i+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(t),e.exit("tableDelimiterMarker"),h):45===t?(i+=1,h(t)):null===t||Vl(t)?y(t):v(t)}function h(t){return 45===t?(e.enter("tableDelimiterFiller"),g(t)):v(t)}function g(t){return 45===t?(e.consume(t),g):58===t?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(t),e.exit("tableDelimiterMarker"),x):(e.exit("tableDelimiterFiller"),x(t))}function x(t){return Wl(t)?Gl(e,y,"whitespace")(t):y(t)}function y(n){return 124===n?m(n):(null===n||Vl(n))&&a&&s===i?(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(n)):v(n)}function v(e){return n(e)}function b(t){return e.enter("tableRow"),w(t)}function w(n){return 124===n?(e.enter("tableCellDivider"),e.consume(n),e.exit("tableCellDivider"),w):null===n||Vl(n)?(e.exit("tableRow"),t(n)):Wl(n)?Gl(e,w,"whitespace")(n):(e.enter("data"),N(n))}function N(t){return null===t||124===t||Hl(t)?(e.exit("data"),w(t)):(e.consume(t),92===t?j:N)}function j(t){return 92===t||124===t?(e.consume(t),N):N(t)}}function xp(e,t){let n,r,a,s=-1,i=!0,o=0,l=[0,0,0,0],c=[0,0,0,0],u=!1,d=0;const m=new fp;for(;++s<e.length;){const p=e[s],f=p[1];"enter"===p[0]?"tableHead"===f.type?(u=!1,0!==d&&(vp(m,t,d,n,r),r=void 0,d=0),n={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},m.add(s,0,[["enter",n,t]])):"tableRow"===f.type||"tableDelimiterRow"===f.type?(i=!0,a=void 0,l=[0,0,0,0],c=[0,s+1,0,0],u&&(u=!1,r={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},m.add(s,0,[["enter",r,t]])),o="tableDelimiterRow"===f.type?2:r?3:1):!o||"data"!==f.type&&"tableDelimiterMarker"!==f.type&&"tableDelimiterFiller"!==f.type?"tableCellDivider"===f.type&&(i?i=!1:(0!==l[1]&&(c[0]=c[1],a=yp(m,t,l,o,void 0,a)),l=c,c=[l[1],s,0,0])):(i=!1,0===c[2]&&(0!==l[1]&&(c[0]=c[1],a=yp(m,t,l,o,void 0,a),l=[0,0,0,0]),c[2]=s)):"tableHead"===f.type?(u=!0,d=s):"tableRow"===f.type||"tableDelimiterRow"===f.type?(d=s,0!==l[1]?(c[0]=c[1],a=yp(m,t,l,o,s,a)):0!==c[1]&&(a=yp(m,t,c,o,s,a)),o=0):!o||"data"!==f.type&&"tableDelimiterMarker"!==f.type&&"tableDelimiterFiller"!==f.type||(c[3]=s)}for(0!==d&&vp(m,t,d,n,r),m.consume(t.events),s=-1;++s<t.events.length;){const e=t.events[s];"enter"===e[0]&&"table"===e[1].type&&(e[1]._align=hp(t.events,s))}return e}function yp(e,t,n,r,a,s){const i=1===r?"tableHeader":2===r?"tableDelimiter":"tableData";0!==n[0]&&(s.end=Object.assign({},bp(t.events,n[0])),e.add(n[0],0,[["exit",s,t]]));const o=bp(t.events,n[1]);if(s={type:i,start:Object.assign({},o),end:Object.assign({},o)},e.add(n[1],0,[["enter",s,t]]),0!==n[2]){const a=bp(t.events,n[2]),s=bp(t.events,n[3]),i={type:"tableContent",start:Object.assign({},a),end:Object.assign({},s)};if(e.add(n[2],0,[["enter",i,t]]),2!==r){const r=t.events[n[2]],a=t.events[n[3]];if(r[1].end=Object.assign({},a[1].end),r[1].type="chunkText",r[1].contentType="text",n[3]>n[2]+1){const t=n[2]+1,r=n[3]-n[2]-1;e.add(t,r,[])}}e.add(n[3]+1,0,[["exit",i,t]])}return void 0!==a&&(s.end=Object.assign({},bp(t.events,a)),e.add(a,0,[["exit",s,t]]),s=void 0),s}function vp(e,t,n,r,a){const s=[],i=bp(t.events,n);a&&(a.end=Object.assign({},i),s.push(["exit",a,t])),r.end=Object.assign({},i),s.push(["exit",r,t]),e.add(n+1,0,s)}function bp(e,t){const n=e[t],r="enter"===n[0]?"start":"end";return n[1][r]}const wp={name:"tasklistCheck",tokenize:function(e,t,n){const r=this;return function(t){if(null!==r.previous||!r._gfmTasklistFirstContentOfListItem)return n(t);return e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(t),e.exit("taskListCheckMarker"),a};function a(t){return Hl(t)?(e.enter("taskListCheckValueUnchecked"),e.consume(t),e.exit("taskListCheckValueUnchecked"),s):88===t||120===t?(e.enter("taskListCheckValueChecked"),e.consume(t),e.exit("taskListCheckValueChecked"),s):n(t)}function s(t){return 93===t?(e.enter("taskListCheckMarker"),e.consume(t),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),i):n(t)}function i(r){return Vl(r)?t(r):Wl(r)?e.check({tokenize:Np},t,n)(r):n(r)}}};function Np(e,t,n){return Gl(e,function(e){return null===e?n(e):t(e)},"whitespace")}const jp={};function kp(e){const t=e||jp,n=this.data(),r=n.micromarkExtensions||(n.micromarkExtensions=[]),a=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),s=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);r.push(function(e){return _l([{text:Zm},{document:{91:{name:"gfmFootnoteDefinition",tokenize:up,continuation:{tokenize:dp},exit:mp}},text:{91:{name:"gfmFootnoteCall",tokenize:cp},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:op,resolveTo:lp}}},pp(e),{flow:{null:{name:"table",tokenize:gp,resolveAll:xp}}},{text:{91:wp}}])}(t)),a.push([{transforms:[Vd],enter:{literalAutolink:Od,literalAutolinkEmail:zd,literalAutolinkHttp:zd,literalAutolinkWww:zd},exit:{literalAutolink:qd,literalAutolinkEmail:$d,literalAutolinkHttp:Ud,literalAutolinkWww:Bd}},{enter:{gfmFootnoteCallString:Kd,gfmFootnoteCall:Xd,gfmFootnoteDefinitionLabelString:Yd,gfmFootnoteDefinition:Gd},exit:{gfmFootnoteCallString:Jd,gfmFootnoteCall:Zd,gfmFootnoteDefinitionLabelString:em,gfmFootnoteDefinition:tm}},{canContainEols:["delete"],enter:{strikethrough:om},exit:{strikethrough:lm}},{enter:{table:Fm,tableData:Om,tableHeader:Om,tableRow:Lm},exit:{codeText:zm,table:Rm,tableData:Mm,tableHeader:Mm,tableRow:Mm}},{exit:{taskListCheckValueChecked:$m,taskListCheckValueUnchecked:$m,paragraph:qm}}]),s.push(function(e){return{extensions:[{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ld,notInConstruct:Md},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ld,notInConstruct:Md},{character:":",before:"[ps]",after:"\\/",inConstruct:Ld,notInConstruct:Md}]},rm(e),{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:im}],handlers:{delete:cm}},Bm(e),{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Vm}}]}}(t))}function Cp({content:e,className:t}){return fe.jsx("div",{className:ge("prose prose-sm max-w-none",t),children:fe.jsx(Ad,{remarkPlugins:[kp],components:{h1:({children:e})=>fe.jsx("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:e}),h2:({children:e})=>fe.jsx("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:e}),h3:({children:e})=>fe.jsx("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:e}),p:({children:e})=>fe.jsx("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:e}),ul:({children:e})=>fe.jsx("ul",{className:"list-disc list-inside mb-2 space-y-1",children:e}),ol:({children:e})=>fe.jsx("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:e}),li:({children:e})=>fe.jsx("li",{className:"text-sm text-foreground",children:e}),code:({inline:e,children:t,...n})=>e?fe.jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...n,children:t}):fe.jsx("code",{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...n,children:t}),pre:({children:e})=>fe.jsx("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:e}),a:({children:e,href:t})=>fe.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:e}),blockquote:({children:e})=>fe.jsx("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:e}),strong:({children:e})=>fe.jsx("strong",{className:"font-bold text-foreground",children:e}),em:({children:e})=>fe.jsx("em",{className:"italic text-foreground",children:e})},children:e})})}function Sp({open:t,onOpenChange:n,placeId:r,placeName:a,onMakeManager:s,onMakeMembers:i,currentManagerId:l,currentMemberIds:c=[]}){const[u,d]=e.useState([]),[m,p]=e.useState(!1),[f,h]=e.useState(""),{data:g=[],isLoading:x}=qr({enabled:t}),y=e.useMemo(()=>{let e=[...g];if(e.sort((e,t)=>{const n=e.userName?.toLowerCase()||"",r=t.userName?.toLowerCase()||"";return n.localeCompare(r)}),f){const t=f.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(t)||e.userEmail?.toLowerCase().includes(t))}return e},[g,f]),v=e=>{d(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},b=1===u.length,w=u.length>0;return fe.jsx(Ae,{open:t,onOpenChange:n,children:fe.jsxs(Re,{className:"max-w-2xl",children:[fe.jsx(Le,{children:fe.jsxs(Oe,{className:"flex items-center gap-2",children:[fe.jsx(o.Users,{className:"h-5 w-5"}),"Gerenciar Acessos - ",a]})}),fe.jsxs("div",{className:"relative",children:[fe.jsx(o.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),fe.jsx(we,{placeholder:"Buscar por nome ou email...",value:f,onChange:e=>h(e.target.value),className:"pl-9"})]}),fe.jsx(Or,{className:"h-[400px] pr-4",children:x?fe.jsx("div",{className:"space-y-2",children:[...Array(5)].map((e,t)=>fe.jsx(zt,{className:"h-16 w-full"},t))}):0===y.length?fe.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[fe.jsx(o.Users,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),fe.jsx("p",{className:"text-sm text-muted-foreground",children:f?"Nenhum usuário encontrado":"Nenhum usuário disponível"})]}):fe.jsx("div",{className:"space-y-2",children:y.map(e=>{const t=e.userId===l,n=c.includes(e.userId||""),r=u.includes(e.userId||"");return fe.jsxs("div",{className:ge("flex items-center gap-3 p-3 rounded-lg border transition-colors",r&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>v(e.userId||""),children:[fe.jsx(st,{checked:r,onCheckedChange:()=>v(e.userId||""),onClick:e=>e.stopPropagation()}),fe.jsxs("div",{className:"flex-1",children:[fe.jsxs("div",{className:"flex items-center gap-2",children:[fe.jsx("p",{className:"font-medium",children:e.userName}),t&&fe.jsx(o.Crown,{className:"h-4 w-4 text-yellow-500"})]}),fe.jsx("p",{className:"text-sm text-muted-foreground",children:e.userEmail})]}),(t||n)&&fe.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},e.userId)})})}),fe.jsxs(Me,{className:"flex gap-2 sm:gap-2",children:[fe.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&fe.jsxs("span",{children:[u.length," selecionado(s)"]})}),b&&s&&fe.jsxs(ve,{onClick:async()=>{if(s&&1===u.length){p(!0);try{await s(u[0],r),d([])}finally{p(!1)}}},disabled:m,variant:"outline",children:[fe.jsx(o.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),w&&i&&fe.jsxs(ve,{onClick:async()=>{if(i&&0!==u.length){p(!0);try{await i(u,r),d([])}finally{p(!1)}}},disabled:m,children:[fe.jsx(o.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Ep({place:t,level:n=0,manageAccessConfig:r}){const[a,s]=e.useState(!1),[i,l]=e.useState(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,d=t.usersCount??0;return fe.jsxs("div",{children:[fe.jsxs(Oa,{open:a,onOpenChange:s,children:[fe.jsxs("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*n+1+"rem"},children:[c?fe.jsxs(za,{className:"flex items-center gap-2 flex-1",children:[fe.jsx(o.ChevronRight,{className:ge("h-4 w-4 transition-transform shrink-0",a&&"rotate-90")}),fe.jsx(o.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),fe.jsx("span",{className:"font-medium",children:t.name}),fe.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",t.subPlaces.length,")"]})]}):fe.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[fe.jsx("div",{className:"w-4 shrink-0"}),fe.jsx(o.Building2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),fe.jsx("span",{className:"font-medium",children:t.name})]}),fe.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[fe.jsxs("div",{className:"flex items-center gap-1.5",children:[fe.jsx(o.Users,{className:"h-3.5 w-3.5 text-muted-foreground"}),fe.jsx("span",{className:"text-sm text-muted-foreground",children:d})]}),fe.jsx(lt,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&fe.jsx(Ni,{customActions:[{label:"Gerenciar Acessos",icon:o.Settings,onClick:()=>l(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&fe.jsx(Ua,{children:t.subPlaces.map(e=>fe.jsx(Ep,{place:e,level:n+1,manageAccessConfig:r},e.id))})]}),0===n&&fe.jsx(rs,{}),r&&fe.jsx(Sp,{open:i,onOpenChange:l,placeId:t.id,placeName:t.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(t.id),currentMemberIds:r.getCurrentMemberIds?.(t.id)})]})}var Ip=Object.defineProperty,Tp=(e,t,n)=>((e,t,n)=>t in e?Ip(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,t+"",n);const Ap=new class{constructor(){Tp(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,t,n){const r=gn.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const a=Jt.getAccessToken();if(!a)throw new Error("Token Qualiex não encontrado");if(!n||""===n.trim())throw new Error("Alias da unidade é obrigatório");const s=new URL(e,this.baseUrl);Object.entries(t).forEach(([e,t])=>{s.searchParams.append(e,t)});const i=await fetch(s.toString(),{method:"GET",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json","un-alias":n}});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,n=[];return e.forEach(e=>{t.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=t.get(e.id);if(e.parentId){const a=t.get(e.parentId);a?(a.subPlaces=a.subPlaces||[],a.subPlaces.push(r)):n.push(r)}else n.push(r)}),n}async getPlaces(e,t){try{const n=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),r=n.data||n||[];return this.buildHierarchy(r)}catch(n){if(await gn.handleApiError(n))try{const n=await this.makeApiCall("/api/common/v1/places",{companyId:t},e),r=n.data||n||[];return this.buildHierarchy(r)}catch(r){return tn.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return tn.handleError(n instanceof Error?n.message:"Erro ao buscar locais",!0),[]}}};function Pp(e){const t=new Map,n=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};t.set(e.id,r),n.set(e.id_user,r)}),e.forEach(e=>{const a=t.get(e.id);if(e.id_leader){const t=n.get(e.id_leader);if(t)return void t.children.push(a)}r.push(a)});const a=(e,t)=>{e.level=t,e.children.forEach(e=>a(e,t+1))};r.forEach(e=>a(e,0));const s=e=>{e.sort((e,t)=>{const n=e.name||e.id_user||e.email||"",r=t.name||t.id_user||t.email||"";return n.localeCompare(r)}),e.forEach(e=>e.children.length>0&&s(e.children))};return s(r),r}function _p(e){const t=[],n=e=>{t.push(e),e.children.forEach(n)};return e.forEach(n),t}function Dp(){const{alias:e,isAuthenticated:t}=qn(),n=Jt.getAccessToken(),{data:r=[]}=qr({enabled:!0});return g.useQuery({queryKey:["leadership",e,r.length],queryFn:async()=>{if(!n||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=cn(),{data:a,error:s}=await t.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",e);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!a||0===a.length)return[];const i={};r.forEach(e=>{i[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const o=a.map(e=>({...e,name:i[e.id_user]?.name||e.id_user,email:i[e.id_user]?.email||"",subordinatesCount:a.filter(t=>t.id_leader===e.id_user).length})),l=new Set(a.map(e=>e.id_user));return new Set(a.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:a[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:a.filter(t=>t.id_leader===e).length})}),Pp(o)},enabled:!!n&&!!e&&t&&r.length>0})}function Fp(){const e="common",{alias:t}=qn(),n=g.useQueryClient(),r=cn();return g.useMutation({mutationFn:async n=>{if(!t)throw new Error("Unidade não selecionada");if(n.id_user===n.id_leader)throw new Error("Usuário não pode ser seu próprio líder");n.id_leader&&await zp(r,t,e,n.id_user,n.id_leader);const{data:a,error:s}=await r.schema(e).from("leaders").insert({alias:t,id_user:n.id_user,id_leader:n.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return a},onSuccess:()=>{n.invalidateQueries({queryKey:["leadership",t]}),i.toast.success("Líder virtual promovido com sucesso")},onError:e=>{i.toast.error(e.message||"Erro ao criar líder")}})}function Rp(){const e="common",{alias:t}=qn(),n=g.useQueryClient(),r=cn();return g.useMutation({mutationFn:async n=>{if(!t)throw new Error("Unidade não selecionada");if(!n.users.length)throw new Error("Selecione pelo menos um liderado");const a=n.users.map(e=>e.id_user),{data:s}=await r.schema(e).from("leaders").select("id_user").eq("alias",t).in("id_user",a).eq("is_removed",!1);if(s&&s.length>0){const e=s.map(e=>e.id_user);throw new Error(`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`)}for(const c of n.users){if(c.id_user===n.id_leader)throw new Error("Usuário não pode ser seu próprio líder");await zp(r,t,e,c.id_user,n.id_leader)}const i=n.users.map(e=>({alias:t,id_user:e.id_user,id_leader:n.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await r.schema(e).from("leaders").insert(i).select();if(l)throw l;return o},onSuccess:e=>{n.invalidateQueries({queryKey:["leadership",t]}),i.toast.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{i.toast.error(e.message||"Erro ao adicionar liderados")}})}function Lp(){const e="common",{alias:t}=qn(),n=g.useQueryClient(),r=cn();return g.useMutation({mutationFn:async n=>{if(!t)throw new Error("Unidade não selecionada");const{data:a}=await r.schema(e).from("leaders").select("id_user").eq("id",n.id).eq("alias",t).single();if(!a)throw new Error("Líder não encontrado");if(a.id_user===n.id_leader)throw new Error("Usuário não pode ser seu próprio líder");n.id_leader&&await zp(r,t,e,a.id_user,n.id_leader,n.id);const{data:s,error:i}=await r.schema(e).from("leaders").update({id_leader:n.id_leader}).eq("id",n.id).eq("alias",t).select().single();if(i)throw i;return s},onSuccess:()=>{n.invalidateQueries({queryKey:["leadership",t]}),i.toast.success("Líder atualizado com sucesso")},onError:e=>{i.toast.error(e.message||"Erro ao atualizar líder")}})}function Mp(){const{alias:e}=qn(),t=g.useQueryClient(),n=cn();return g.useMutation({mutationFn:async t=>{if(!e)throw new Error("Unidade não selecionada");const{error:r}=await n.schema("common").from("leaders").update({is_removed:!0}).eq("id",t).eq("alias",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",e]}),i.toast.success("Líder removido com sucesso")},onError:e=>{i.toast.error(e.message||"Erro ao remover líder")}})}function Op(){const e="common",{alias:t}=qn(),n=g.useQueryClient(),r=cn();return g.useMutation({mutationFn:async({leaderUserId:n,selectedUsers:a})=>{if(!t)throw new Error("Unidade não selecionada");const s=a.map(e=>e.id_user),i=await Promise.all([r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).eq("id_leader",n),r.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1).in("id_user",s.length?s:["__none__"])]),[{data:o,error:l},{data:c,error:u}]=i;if(l)throw l;if(u)throw u;const d=o||[],m=c||[],p=new Set(s),f=d.filter(e=>!p.has(e.id_user)),h=m.filter(e=>e.id_leader!==n),g=new Set(m.map(e=>e.id_user)),x=a.filter(e=>!g.has(e.id_user));for(const b of h)await zp(r,t,e,b.id_user,n,b.id);for(const b of x){if(b.id_user===n)throw new Error("Usuário não pode ser seu próprio líder");await zp(r,t,e,b.id_user,n)}const y=[];if(f.length){const n=f.map(e=>e.id);y.push(r.schema(e).from("leaders").update({id_leader:null}).in("id",n).eq("alias",t))}if(h.length){const a=h.map(e=>e.id);y.push(r.schema(e).from("leaders").update({id_leader:n}).in("id",a).eq("alias",t))}if(x.length){const a=x.map(e=>({alias:t,id_user:e.id_user,id_leader:n,is_active:!0,is_removed:!1}));y.push(r.schema(e).from("leaders").insert(a))}const v=(await Promise.all(y)).find(e=>e?.error);if(v?.error)throw v.error;return{unlinked:f.length,updated:h.length,created:x.length}},onSuccess:e=>{n.invalidateQueries({queryKey:["leadership",t]}),i.toast.success(`Subordinados sincronizados (${e.created} adicionados, ${e.updated} atualizados, ${e.unlinked} removidos)`)},onError:e=>{i.toast.error(e.message||"Erro ao sincronizar subordinados")}})}async function zp(e,t,n,r,a,s){const{data:i,error:o}=await e.schema(n).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(o)throw o;const l=s?i.filter(e=>e.id!==s):i,c=new Set;let u=a;for(;u;){if(c.has(u))throw new Error("Esta associação criaria um ciclo na hierarquia");if(u===r)throw new Error("Esta associação criaria um ciclo na hierarquia");c.add(u);const e=l.find(e=>e.id_user===u);u=e?.id_leader||null}}function Up({leader:e,expandedIds:t,onToggleExpand:n,onEdit:r}){const a=t.has(e.id),s=e.children.length>0,i=32*e.level;return fe.jsxs(fe.Fragment,{children:[fe.jsxs("tr",{className:"border-b hover:bg-muted/50 transition-colors",children:[fe.jsx("td",{className:"py-3 px-4",children:fe.jsxs("div",{className:"flex items-center gap-2",style:{paddingLeft:`${i}px`},children:[s?fe.jsx("button",{onClick:()=>n(e.id),className:"p-1 hover:bg-accent rounded",children:a?fe.jsx(o.ChevronDown,{className:"h-4 w-4"}):fe.jsx(o.ChevronRight,{className:"h-4 w-4"})}):fe.jsx("div",{className:"w-6"}),fe.jsx(o.User,{className:"h-4 w-4 text-muted-foreground"}),fe.jsx("button",{onClick:()=>{r(e)},className:"font-medium hover:text-primary hover:underline text-left",children:e.name||e.id_user||e.email})]})}),fe.jsx("td",{className:"py-3 px-4 text-center",children:fe.jsx("span",{className:"text-sm",children:e.subordinatesCount||0})})]}),s&&a&&e.children.map(e=>fe.jsx(Up,{leader:e,expandedIds:t,onToggleExpand:n,onEdit:r},e.id))]})}var Bp=function(e,t){for(var n={};e.length;){var r=e[0],a=r.code,s=r.message,i=r.path.join(".");if(!n[i])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];n[i]={message:o.message,type:o.code}}else n[i]={message:s,type:a};if("unionErrors"in r&&r.unionErrors.forEach(function(t){return t.errors.forEach(function(t){return e.push(t)})}),t){var l=n[i].types,c=l&&l[r.code];n[i]=u.appendErrors(i,t,n,a,c?[].concat(c,r.message):r.message)}e.shift()}return n},$p=function(e,t,n){return void 0===n&&(n={}),function(r,a,s){try{return Promise.resolve(function(a,i){try{var o=Promise.resolve(e["sync"===n.mode?"parse":"parseAsync"](r,t)).then(function(e){return s.shouldUseNativeValidation&&L.validateFieldsNatively({},s),{errors:{},values:n.raw?r:e}})}catch(l){return i(l)}return o&&o.then?o.then(void 0,i):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:L.toNestErrors(Bp(e.errors,!s.shouldUseNativeValidation&&"all"===s.criteriaMode),s)};throw e}))}catch(i){return Promise.reject(i)}}};const qp=R.z.object({id_leader:R.z.string().nullable(),id_users:R.z.array(R.z.string()).min(1,"Selecione pelo menos um liderado")}),Vp=R.z.object({id_leader:R.z.string().nullable(),id_users:R.z.array(R.z.string())});function Hp({value:t,onChange:n,excludeUserIds:r=[],error:a}){const{data:s=[],isLoading:i}=qr(),[l,c]=e.useState(""),u=e.useRef(null),d=e.useRef(0),m=s.filter(e=>!r.includes(e.userId||"")).filter(e=>{const t=l.toLowerCase(),n=e.userName?.toLowerCase().includes(t);return n}).sort((e,n)=>{const r=t.includes(e.userId),a=t.includes(n.userId);if(r&&!a)return-1;if(!r&&a)return 1;const s=e.userName||e.userEmail||"",i=n.userName||n.userEmail||"";return s.localeCompare(i)});return e.useEffect(()=>{u.current&&d.current>0&&(u.current.scrollTop=d.current)},[m]),i?fe.jsxs("div",{className:"flex items-center justify-center p-4",children:[fe.jsx(o.Loader2,{className:"h-6 w-6 animate-spin"}),fe.jsx("span",{className:"ml-2",children:"Carregando usuários..."})]}):fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(we,{placeholder:"Buscar usuário...",value:l,onChange:e=>c(e.target.value)}),fe.jsx("div",{ref:u,className:"border rounded-md p-4 h-[300px] overflow-y-auto",children:0===m.length?fe.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum usuário encontrado"}):fe.jsx("div",{className:"space-y-2",children:m.map(e=>fe.jsxs("div",{className:"flex items-center space-x-2",children:[fe.jsx(st,{id:e.userId,checked:t.includes(e.userId),onCheckedChange:()=>{return r=e.userId,u.current&&(d.current=u.current.scrollTop),void(t.includes(r)?n(t.filter(e=>e!==r)):n([...t,r]));var r}}),fe.jsx(je,{htmlFor:e.userId,className:"flex-1 cursor-pointer",children:e.userName||e.userEmail})]},e.userId))})}),t.length>0&&fe.jsxs("p",{className:"text-sm text-muted-foreground",children:[t.length," usuário(s) selecionado(s)"]}),a&&fe.jsx("p",{className:"text-sm text-destructive",children:a})]})}function Wp({leader:t,prefilledLeaderId:n,onSuccess:r}){const{alias:a}=qn(),s=!!t,i=t?.id.startsWith("virtual-"),l=Rp(),c=Fp(),d=Lp(),m=Op(),p=Mp(),{data:f=[]}=Dp(),{data:h=[]}=qr(),[g,x]=e.useState(""),y=_p(f).map(e=>e.id_user),v=s?_p(f).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user):[],b=u.useForm({resolver:$p(s?Vp:qp),defaultValues:{id_leader:n||(s?t?.id_leader:null)||null,id_users:s?v:[]}});e.useEffect(()=>{if(t){const e=_p(f).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user);b.reset({id_leader:t.id_leader||null,id_users:e})}else n?b.reset({id_leader:n,id_users:[]}):b.reset({id_leader:null,id_users:[]})},[a,t?.id,t?.id_user,t?.id_leader,n,f]);const w=l.isPending||c.isPending||d.isPending||m.isPending||p.isPending,N=b.watch("id_leader"),j=b.watch("id_users"),k=s?[t.id_user,...y.filter(e=>e!==t.id_user&&!j.includes(e)&&!v.includes(e))]:[N,...y.filter(e=>!j.includes(e))].filter(Boolean);return fe.jsxs("form",{onSubmit:b.handleSubmit(async e=>{try{if(s)if(i){await c.mutateAsync({id_user:t.id_user,id_leader:e.id_leader});const n=h.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:t.id_user,selectedUsers:n})}else{await d.mutateAsync({id:t.id,id_leader:e.id_leader});const n=h.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await m.mutateAsync({leaderUserId:t.id_user,selectedUsers:n})}else{const t=h.filter(t=>e.id_users.includes(t.userId)).map(e=>({id_user:e.userId}));await l.mutateAsync({id_leader:e.id_leader,users:t})}r?.()}catch(n){}}),className:"space-y-4",children:[s&&fe.jsxs("div",{children:[fe.jsx(je,{children:"Líder"}),fe.jsx(we,{value:h.find(e=>e.userId===t.id_user)?.userName||t.name||t.id_user,disabled:!0,className:"bg-muted"})]}),fe.jsxs("div",{children:[fe.jsx(je,{children:"Líder Superior"}),fe.jsxs(Xe,{value:N||"none",onValueChange:e=>b.setValue("id_leader","none"===e?null:e),children:[fe.jsx(Je,{children:fe.jsx(Ge,{placeholder:"Nenhum (líder raiz)"})}),fe.jsxs(tt,{children:[fe.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:fe.jsx(we,{placeholder:"Buscar líder...",value:g,onChange:e=>x(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),fe.jsxs(Or,{className:"h-[200px]",children:[fe.jsx(rt,{value:"none",children:"Nenhum (líder raiz)"}),h.filter(e=>{const n=s?e.userId!==t.id_user:!j.includes(e.userId),r=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return n&&r}).sort((e,t)=>{const n=e.userName||e.userEmail||"",r=t.userName||t.userEmail||"";return n.localeCompare(r)}).map(e=>fe.jsx(rt,{value:e.userId,children:e.userName},e.userId))]})]})]},`superior-select-${a}`),b.formState.errors.id_leader&&fe.jsx("p",{className:"text-sm text-destructive mt-1",children:b.formState.errors.id_leader.message})]}),fe.jsxs("div",{children:[fe.jsx(je,{children:"Liderados *"}),fe.jsx(Hp,{value:j,onChange:e=>b.setValue("id_users",e),excludeUserIds:k,error:b.formState.errors.id_users?.message},`users-multiselect-${a}`)]}),fe.jsxs("div",{className:"flex items-center justify-between gap-2",children:[fe.jsx(ve,{type:"submit",disabled:w||!s&&0===j.length,children:w&&!p.isPending?fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),s?"Atualizando...":"Salvando..."]}):s?j.length>0?`Atualizar (${j.length})`:"Atualizar":`Adicionar (${j.length})`}),s&&!N&&0===j.length&&fe.jsx(ve,{type:"button",variant:"destructive",disabled:w,onClick:async()=>{if(t&&window.confirm("Tem certeza que deseja remover esta liderança?"))try{await p.mutateAsync(t.id),r?.()}catch(e){}},className:"ml-auto",children:p.isPending?fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Trash2,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function Qp({open:e,onOpenChange:t,leader:n,prefilledLeaderId:r,title:a}){return fe.jsx(Ae,{open:e,onOpenChange:t,children:fe.jsxs(Re,{className:"sm:max-w-[500px]",children:[fe.jsx(Le,{children:fe.jsx(Oe,{children:a})}),fe.jsx(Wp,{leader:n,prefilledLeaderId:r,onSuccess:()=>t(!1)})]})})}const Kp="leadership-expanded-nodes",Xp=(e,t)=>{try{localStorage.setItem(`${Kp}-${e}`,JSON.stringify(Array.from(t)))}catch(n){}};function Yp(t){const[n,r]=e.useState(!1),[a,s]=e.useState(0),{uploadFunction:i,deleteFunction:o,defaultOptions:l,onSuccess:c,onError:u}=t||{};return{upload:async(e,t)=>{if(!i){const e=new Error("uploadFunction não fornecida");throw yt({title:"Erro de configuração",description:"Função de upload não configurada. Verifique a documentação.",variant:"destructive"}),e}r(!0),s(0);try{const n={...l,...t};if(n.maxSize&&e.size>n.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(n.maxSize/1024/1024)}MB`);if(n.allowedTypes){if(!n.allowedTypes.some(t=>t.endsWith("/*")?e.type.startsWith(t.replace("/*","")):e.type===t))throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${n.allowedTypes.join(", ")}`)}const r=await i(e,n);return s(100),yt({title:"Sucesso",description:"Arquivo enviado com sucesso"}),c?.(r),r}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw yt({title:"Erro",description:e.message,variant:"destructive"}),u?.(e),e}finally{r(!1)}},deleteMedia:async(e,t)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw yt({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await o(e,t),yt({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(n){throw yt({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),n}},uploading:n,progress:a}}function Gp(e){const t=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const n of t){const t=e.match(n);if(t)return t[1]}return null}function Jp(e,t){const n=Gp(e);if(!n)return e;return`https://www.youtube.com/embed/${n}${t?"?autoplay=1&mute=1":""}`}function Zp(e){const t=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function ef(e,t){const n=Zp(e);if(!n)return e;return`https://player.vimeo.com/video/${n}${t?"?autoplay=1&muted=1":""}`}function tf(e){if(!e)return;const t=e.match(/src="([^"]+)"/);return t?t[1]:void 0}function nf(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function rf(e,t){return e/t}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return i.toast}}),exports.AUTH_CONFIG=bn,exports.Accordion=ma,exports.AccordionContent=ha,exports.AccordionItem=pa,exports.AccordionTrigger=fa,exports.ActionButton=be,exports.ActionMenu=Ni,exports.ActionMenuItems=Ar,exports.Alert=ia,exports.AlertDescription=la,exports.AlertDialog=Hn,exports.AlertDialogAction=er,exports.AlertDialogCancel=tr,exports.AlertDialogContent=Xn,exports.AlertDialogDescription=Zn,exports.AlertDialogFooter=Gn,exports.AlertDialogHeader=Yn,exports.AlertDialogOverlay=Kn,exports.AlertDialogPortal=Qn,exports.AlertDialogTitle=Jn,exports.AlertDialogTrigger=Wn,exports.AlertTitle=oa,exports.AppHeader=Ai,exports.AppLayout=Vi,exports.AppSidebar=qi,exports.AspectRatio=ga,exports.AuthErrorInterceptor=fn,exports.AuthProvider=({children:t})=>{const[n,r]=e.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 a=null;try{a=g.useQueryClient()}catch{}const[s,i]=e.useState(!1),[o,l]=e.useState(0),c=e.useCallback(e=>{r(t=>({...t,...e}))},[]),u=e.useCallback(e=>{r(t=>({...t,isLoading:e}))},[]),d=e.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})},[]),m=e.useCallback(async e=>{try{u(!0);const r=Jt.getAccessToken();if(!r)return;const s=await un.generateToken(r,e.alias,void 0,!0);if(!s)return;Jt.setSupabaseToken(s),Jt.setSelectedAlias(e.alias);const i=Jt.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Jt.getCompanyId(e.alias),d={id:l||e.id,name:e.name,alias:o};let m=null,p=null;if(n.user?.id&&o&&l)try{const e=(await vn.fetchActiveUsersMap(o,l)).get(n.user.id);if(e){const t=zn(e);m=t.placeId,p=t.placeName}}catch(t){}c({alias:o,selectedUnit:d,placeId:m,placeName:p,activePlaceId:m,activePlaceName:p}),a&&(await a.clear(),await new Promise(e=>setTimeout(e,100)))}catch(t){}finally{u(!1)}},[c,a,u,n.user]),p=e.useCallback(async()=>await Bn.processCallback(),[]),f=e.useCallback(async()=>{Bn.logout(),d(),a&&await a.clear()},[d,a]),h=e.useCallback(e=>{i(e)},[]),x=e.useCallback(()=>{l(e=>e+1)},[]),y=e.useCallback(()=>{l(e=>e+1)},[]);e.useEffect(()=>{if(!n.isAuthenticated)return;let e=!0;const t=setInterval(()=>{e&&(Jt.areAllTokensValid()||e&&f())},6e5);return()=>{e=!1,clearInterval(t)}},[n.isAuthenticated,f]),e.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const t=await Bn.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&&(fn.handleError(t),u(!1))}})(),()=>{e=!1}},[c,u,f]);const v=e.useMemo(()=>({...n,logout:f,processCallback:p,switchUnit:m,availableUnits:n.companies,isSearchVisible:s,setSearchVisible:h,clearSearch:x,refreshData:y}),[n.user,n.companies,n.alias,n.isAuthenticated,n.isLoading,n.selectedUnit,n.userId,n.userAlias,n.placeId,n.placeName,n.activePlaceId,n.activePlaceName,f,p,m,s,h,x,y]);return fe.jsx($n.Provider,{value:v,children:t})},exports.AuthService=Bn,exports.Avatar=xa,exports.AvatarFallback=va,exports.AvatarImage=ya,exports.Badge=lt,exports.BaseForm=Hr,exports.Breadcrumb=ba,exports.BreadcrumbEllipsis=Sa,exports.BreadcrumbItem=Na,exports.BreadcrumbLink=ja,exports.BreadcrumbList=wa,exports.BreadcrumbPage=ka,exports.BreadcrumbSeparator=Ca,exports.BulkActionBar=Kr,exports.Button=ve,exports.CRUD_CONFIG=wn,exports.Calendar=Ma,exports.CallbackPage=()=>{const{processCallback:t}=qn(),[n,r]=e.useState(null),[a,s]=e.useState(!1);e.useEffect(()=>{(async()=>{try{if(await t()){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.")}})()},[t]);const i=async()=>{s(!0),r(null);try{await t()||r("Falha na autenticação. Tente novamente.")}catch(e){r(e?.message||"Erro ao tentar novamente.")}finally{s(!1)}},l=()=>{window.location.href="/"};return n?fe.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:fe.jsxs(ke,{className:"w-full max-w-md",children:[fe.jsx(Ce,{className:"text-center",children:fe.jsxs(Se,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[fe.jsx(o.AlertCircle,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),fe.jsxs(Ie,{className:"space-y-4",children:[fe.jsx(ia,{variant:"destructive",children:fe.jsx(la,{children:n})}),fe.jsx("div",{className:"text-sm text-muted-foreground",children:fe.jsx("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),fe.jsxs("div",{className:"flex gap-2",children:[fe.jsx(ve,{onClick:i,disabled:a,className:"flex-1",children:a?fe.jsxs(fe.Fragment,{children:[fe.jsx(ut,{size:"sm",className:"mr-2"}),"Tentando..."]}):fe.jsxs(fe.Fragment,{children:[fe.jsx(o.RefreshCw,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),fe.jsx(ve,{onClick:l,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}):fe.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:fe.jsxs(ke,{className:"w-full max-w-md",children:[fe.jsx(Ce,{className:"text-center",children:fe.jsx(Se,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),fe.jsxs(Ie,{className:"text-center",children:[fe.jsx("div",{className:"flex justify-center mb-4",children:fe.jsx(ut,{size:"lg"})}),fe.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=ke,exports.CardContent=Ie,exports.CardDescription=Ee,exports.CardFooter=Te,exports.CardHeader=Ce,exports.CardSkeleton=mr,exports.CardTitle=Se,exports.Cards=function({data:e,renderCard:t,isLoading:n=!1,emptyMessage:r="Nenhum item encontrado",columns:a,gap:s="md",className:i}){return n?fe.jsx(Va,{cols:a?String(a):"auto-fit",gap:s,className:i,children:[...Array(6)].map((e,t)=>fe.jsx(zt,{className:"h-48 w-full"},t))}):0===e.length?fe.jsx("div",{className:"flex items-center justify-center p-8",children:fe.jsx("div",{className:"text-center text-muted-foreground",children:fe.jsx("p",{children:r})})}):fe.jsx(Va,{cols:a?String(a):"auto-fit",gap:s,className:i,children:e.map(t)})},exports.ChatbotPage=function(){const[t,n]=e.useState(!1),[r,a]=e.useState(""),{messages:s,isLoading:i,error:l,sendMessage:c}=Yi(),u=e.useRef(null),d=e.useRef(null);e.useEffect(()=>{if(u.current){const e=u.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[s]),e.useEffect(()=>{t&&d.current&&d.current.focus()},[t]),e.useEffect(()=>{const e=e=>{"Escape"===e.key&&t&&n(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t]);const m=()=>{r.trim()&&!i&&(c(r),a(""))};return fe.jsxs(fe.Fragment,{children:[fe.jsx(ve,{onClick:()=>n(!t),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:t?fe.jsx(o.X,{className:"h-6 w-6"}):fe.jsx(o.MessageCircle,{className:"h-6 w-6"})}),t&&fe.jsxs(ke,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[fe.jsxs(Ce,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[fe.jsx(Se,{className:"text-lg font-semibold",children:"Chat Assistant"}),fe.jsx(ve,{variant:"ghost",size:"icon",onClick:()=>n(!1),className:"h-8 w-8",children:fe.jsx(o.X,{className:"h-4 w-4"})})]}),fe.jsxs(Ie,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[fe.jsx(Or,{ref:u,className:"flex-1 px-4",children:fe.jsxs("div",{className:"space-y-4 py-4",children:[s.map(e=>fe.jsx("div",{className:"flex "+("user"===e.role?"justify-end":"justify-start"),children:fe.jsx("div",{className:"max-w-[80%] rounded-lg px-4 py-2 "+("user"===e.role?"bg-primary text-primary-foreground":"bg-muted"),children:"assistant"===e.role?fe.jsx(Cp,{content:e.content}):fe.jsx("p",{className:"text-sm whitespace-pre-wrap",children:e.content})})},e.id)),i&&fe.jsx("div",{className:"flex justify-start",children:fe.jsx("div",{className:"bg-muted rounded-lg px-4 py-2",children:fe.jsxs("div",{className:"flex space-x-2",children:[fe.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce"}),fe.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.2s]"}),fe.jsx("div",{className:"w-2 h-2 bg-foreground/40 rounded-full animate-bounce [animation-delay:0.4s]"})]})})}),l&&fe.jsx("div",{className:"text-center text-sm text-destructive py-2",children:l})]})}),fe.jsx("div",{className:"border-t p-4",children:fe.jsxs("div",{className:"flex space-x-2",children:[fe.jsx(we,{ref:d,value:r,onChange:e=>a(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),m())},placeholder:"Digite sua mensagem...",disabled:i,className:"flex-1"}),fe.jsx(ve,{onClick:m,disabled:i||!r.trim(),size:"icon",children:fe.jsx(o.Send,{className:"h-4 w-4"})})]})})]})]})]})},exports.Checkbox=st,exports.Collapsible=Oa,exports.CollapsibleContent=Ua,exports.CollapsibleTrigger=za,exports.ColorPicker=Mr,exports.Command=Pt,exports.CommandDialog=({children:e,...t})=>fe.jsx("div",{...t,children:fe.jsx(Pt,{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:e})}),exports.CommandEmpty=Ft,exports.CommandGroup=Rt,exports.CommandInput=_t,exports.CommandItem=Mt,exports.CommandList=Dt,exports.CommandSeparator=Lt,exports.CommandShortcut=Ot,exports.CrudCards=function({manager:e,config:t,onEdit:n,onDelete:r}){return e.isLoading?fe.jsx(Va,{children:Array.from({length:3}).map((e,t)=>fe.jsxs(ke,{children:[fe.jsxs(Ce,{children:[fe.jsx(zt,{className:"h-4 w-3/4"}),fe.jsx(zt,{className:"h-3 w-1/2"})]}),fe.jsx(Ie,{children:fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(zt,{className:"h-3 w-full"}),fe.jsx(zt,{className:"h-3 w-2/3"})]})})]},t))}):fe.jsx(Ba.Root,{children:e.entities.map(e=>fe.jsxs(Ba.Item,{onClick:()=>n(e),children:[fe.jsx(Ce,{className:"pb-3",children:fe.jsxs("div",{className:"flex items-start justify-between",children:[fe.jsxs("div",{className:"flex-1 min-w-0",children:[fe.jsx(Se,{className:"text-base leading-6 truncate",children:e.title||e.name||"Sem título"}),fe.jsx(Ee,{className:"text-sm",children:s.format(new Date(e.created_at),"dd/MM/yyyy HH:mm",{locale:La})})]}),fe.jsxs("div",{className:"flex items-center gap-2 ml-2",children:[e.link&&fe.jsx(ve,{variant:"external-link",size:"icon-xs",onClick:t=>{t.stopPropagation(),(e=>{try{const t=window.open(e,"_blank");t&&!t.closed&&void 0!==t.closed||(navigator.clipboard.writeText(e),i.toast.info("Link copiado para a área de transferência"))}catch(t){window.location.href=e}})(e.link)},title:"Abrir link externo",children:fe.jsx(o.ExternalLink,{className:"h-4 w-4"})}),fe.jsx("div",{onClick:e=>e.stopPropagation(),children:fe.jsx(Pr,{onEdit:()=>n(e),onDelete:r?()=>r(e):void 0,canDelete:!!r})})]})]})}),fe.jsx(Ie,{className:"pt-0",children:fe.jsx("div",{className:"space-y-2",children:t.cardFields?.map(t=>{const n=e[t.key];return n?fe.jsx(Ba.Field,{label:t.label,value:t.render?t.render(n,e):String(n)},String(t.key)):null})})})]},e.id))})},exports.CrudPageInternal=ea,exports.CrudPagination=Qr,exports.CrudPrimitiveFilterBar=function({searchValue:e="",onSearchChange:t,customFilters:n=[],onClearFilters:r,showClearButton:a=!0,layout:s="horizontal"}){const i=e||n.length>0;return fe.jsxs("div",{className:`flex ${"vertical"===s?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[t&&fe.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[fe.jsx(o.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),fe.jsx(we,{type:"text",placeholder:"Buscar...",value:e,onChange:e=>t(e.target.value),className:"pl-9 h-9"})]}),n.map((e,t)=>fe.jsx("div",{className:"vertical"===s?"w-full":"",children:e},t)),a&&i&&r&&fe.jsxs(ve,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[fe.jsx(o.X,{size:14,className:"mr-1"}),"Limpar"]})]})},exports.CrudPrimitivePagination=Wr,exports.CrudPrimitiveTable=function({data:t,columns:n,sortField:r,sortDirection:a,onSort:s,onRowClick:i,renderActions:l,isLoading:c=!1,emptyMessage:u="Nenhum item encontrado",className:d,enableSelection:m=!1,selectedIds:p=[],onSelectItem:f,onSelectAll:h,isAllSelected:g=!1}){const x=e.useMemo(()=>{const e=n.reduce((e,t)=>t.width?e:e+(t.weight??1),0);return n.map(t=>{if(t.width)return`${t.width}px`;if(t.minWidth&&!t.weight)return`${t.minWidth}px`;const n=(t.weight??1)/e*100;return t.minWidth?`minmax(${t.minWidth}px, ${n}%)`:`${n}%`})},[n]);return c?fe.jsx("div",{className:"flex-1 overflow-auto",children:fe.jsx("div",{className:"p-4 space-y-3",children:[...Array(5)].map((e,t)=>fe.jsx(zt,{className:"h-12 w-full"},t))})}):0===t.length?fe.jsx("div",{className:"flex-1 flex items-center justify-center",children:fe.jsx("div",{className:"text-center text-muted-foreground",children:fe.jsx("p",{children:u})})}):fe.jsx("div",{className:"flex-1 overflow-auto",children:fe.jsxs(rr,{className:d,children:[fe.jsx(ar,{className:"sticky top-0 bg-background z-10",children:fe.jsxs(or,{children:[m&&fe.jsx(lr,{className:"w-[40px]",children:fe.jsx(st,{checked:g,onCheckedChange:h,"aria-label":"Selecionar todos"})}),n.map((e,t)=>{return fe.jsx(lr,{className:e.className,style:{width:x[t]},children:e.sortable&&s?fe.jsxs("button",{onClick:()=>s(String(e.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[e.header,(n=String(e.key),r!==n?fe.jsx(o.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===a?fe.jsx(o.ArrowUp,{size:14,className:"ml-1"}):fe.jsx(o.ArrowDown,{size:14,className:"ml-1"}))]}):fe.jsx("span",{className:"font-medium",children:e.header})},String(e.key));var n}),l&&fe.jsx(lr,{className:"w-[80px] text-right",children:"Ações"})]})}),fe.jsx(sr,{children:t.map(e=>fe.jsxs(or,{onClick:()=>i?.(e),className:i?"cursor-pointer":"",children:[m&&fe.jsx(cr,{children:fe.jsx(st,{checked:p.includes(e.id),onCheckedChange:()=>f?.(e.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${e.id}`})}),n.map(t=>fe.jsx(cr,{className:t.className,children:t.render?t.render(e):String(e[t.key]??"-")},String(t.key))),l&&fe.jsx(cr,{className:"text-right",onClick:e=>e.stopPropagation(),children:l(e)})]},e.id))})]})})},exports.CrudTable=Fr,exports.DataList=Ba,exports.DeleteConfirmationDialog=nr,exports.Dialog=Ae,exports.DialogClose=De,exports.DialogContent=Re,exports.DialogDescription=ze,exports.DialogFooter=Me,exports.DialogHeader=Le,exports.DialogOverlay=Fe,exports.DialogPortal=_e,exports.DialogTitle=Oe,exports.DialogTrigger=Pe,exports.DropdownMenu=hr,exports.DropdownMenuCheckboxItem=Cr,exports.DropdownMenuContent=jr,exports.DropdownMenuGroup=xr,exports.DropdownMenuItem=kr,exports.DropdownMenuLabel=Er,exports.DropdownMenuPortal=yr,exports.DropdownMenuRadioGroup=br,exports.DropdownMenuRadioItem=Sr,exports.DropdownMenuSeparator=Ir,exports.DropdownMenuShortcut=Tr,exports.DropdownMenuSub=vr,exports.DropdownMenuSubContent=Nr,exports.DropdownMenuSubTrigger=wr,exports.DropdownMenuTrigger=gr,exports.EmailService=Ki,exports.EmptyState=fr,exports.EntitySelect=$r,exports.ErrorBoundary=Qi,exports.FilterBar=Zr,exports.Form=Ue,exports.FormControl=We,exports.FormDescription=Qe,exports.FormField=({...e})=>fe.jsx(Be.Provider,{value:{name:e.name},children:fe.jsx(u.Controller,{...e})}),exports.FormItem=Ve,exports.FormLabel=He,exports.FormMessage=Ke,exports.FormSkeleton=function({fields:e=4}){return fe.jsxs("div",{className:"space-y-4",children:[Array.from({length:e}).map((e,t)=>fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(zt,{className:"h-4 w-24"}),fe.jsx(zt,{className:"h-10 w-full"})]},t)),fe.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[fe.jsx(zt,{className:"h-10 w-20"}),fe.jsx(zt,{className:"h-10 w-20"})]})]})},exports.Grid=Va,exports.HeaderSkeleton=function(){return fe.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[fe.jsxs("div",{className:"flex items-center space-x-3",children:[fe.jsx(zt,{className:"h-8 w-8 rounded-full"}),fe.jsx(zt,{className:"h-6 w-32"})]}),fe.jsxs("div",{className:"flex items-center space-x-2",children:[fe.jsx(zt,{className:"h-8 w-8"}),fe.jsx(zt,{className:"h-8 w-24"})]})]})},exports.IconPicker=Br,exports.ImageEditor=function({value:t,onChange:n,onSubmit:r,onCancel:a,uploadFunction:s,deleteFunction:i,uploadOptions:l}){const[c,u]=e.useState(t||{alignment:"center",allowDownload:!1}),d=e.useRef(null),{upload:m,uploading:p}=Yp({uploadFunction:s,deleteFunction:i,defaultOptions:{...l,allowedTypes:["image/*"],maxSize:5242880}}),f=(e,t)=>{const r={...c,[e]:t};u(r),n(r)};return fe.jsxs("div",{className:"space-y-6",children:[fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"URL da imagem"}),fe.jsxs("div",{className:"flex gap-2",children:[fe.jsx(we,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:c.imageUrl||"",onChange:e=>f("imageUrl",e.target.value),className:"flex-1"}),s&&fe.jsxs(fe.Fragment,{children:[fe.jsx("input",{ref:d,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await m(t),r={...c,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};u(r),n(r)}catch(r){}finally{d.current&&(d.current.value="")}},className:"hidden"}),fe.jsx(ve,{type:"button",variant:"outline",onClick:()=>d.current?.click(),disabled:p,children:p?fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),c.imageFile&&fe.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.imageFile," (",Math.round((c.imageSize||0)/1024)," KB)"]})]}),c.imageUrl&&fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"Preview"}),fe.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:fe.jsx("div",{className:"flex "+("left"===c.alignment?"justify-start":"right"===c.alignment?"justify-end":"justify-center"),children:fe.jsx("img",{src:c.imageUrl,alt:c.alt||"Preview",style:{width:c.width?`${c.width}px`:"auto",height:c.height?`${c.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{htmlFor:"caption",children:"Legenda (opcional)"}),fe.jsx(it,{id:"caption",placeholder:"Descrição da imagem",value:c.caption||"",onChange:e=>f("caption",e.target.value),rows:2})]}),fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{htmlFor:"alt",children:"Texto alternativo (acessibilidade)"}),fe.jsx(we,{id:"alt",placeholder:"Descrição para leitores de tela",value:c.alt||"",onChange:e=>f("alt",e.target.value)})]}),fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"Alinhamento"}),fe.jsxs(Xe,{value:c.alignment||"center",onValueChange:e=>f("alignment",e),children:[fe.jsx(Je,{children:fe.jsx(Ge,{})}),fe.jsxs(tt,{children:[fe.jsx(rt,{value:"left",children:"Esquerda"}),fe.jsx(rt,{value:"center",children:"Centro"}),fe.jsx(rt,{value:"right",children:"Direita"})]})]})]}),fe.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{htmlFor:"width",children:"Largura (px, opcional)"}),fe.jsx(we,{id:"width",type:"number",placeholder:"Auto",value:c.width||"",onChange:e=>f("width",e.target.value?Number(e.target.value):void 0)})]}),fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{htmlFor:"height",children:"Altura (px, opcional)"}),fe.jsx(we,{id:"height",type:"number",placeholder:"Auto",value:c.height||"",onChange:e=>f("height",e.target.value?Number(e.target.value):void 0)})]})]}),fe.jsxs("div",{className:"flex items-center gap-2",children:[fe.jsx("input",{id:"allowDownload",type:"checkbox",checked:c.allowDownload||!1,onChange:e=>f("allowDownload",e.target.checked),className:"h-4 w-4"}),fe.jsx(je,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download da imagem"})]}),fe.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[fe.jsx(ve,{variant:"outline",onClick:a,children:"Cancelar"}),fe.jsx(ve,{onClick:()=>{c.imageUrl?r(c):yt({title:"Erro",description:"Adicione uma URL ou faça upload de uma imagem",variant:"destructive"})},disabled:!c.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:e,className:t="",style:n}){if(!e.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[e.alignment||"center"];return fe.jsx("div",{className:`flex ${r} my-4 ${t}`,style:n,children:fe.jsxs("div",{className:"space-y-2 max-w-full",children:[fe.jsx("img",{src:e.imageUrl,alt:e.alt||"",style:{width:e.width?`${e.width}px`:"auto",height:e.height?`${e.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),e.caption&&fe.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:e.caption}),e.allowDownload&&e.imageUrl&&fe.jsxs("a",{href:e.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[fe.jsx(o.Download,{className:"h-4 w-4"}),"Baixar imagem"]})]})})},exports.Input=we,exports.Label=je,exports.LeaderRow=Up,exports.LeadershipDialog=Qp,exports.LeadershipForm=Wp,exports.LeadershipPage=function(){const{alias:t}=qn(),{data:n,isLoading:r,error:a,refetch:s}=Dp(),{data:i=[]}=qr(),[l,c]=e.useState(()=>t?(e=>{try{const t=localStorage.getItem(`${Kp}-${e}`);if(t)return new Set(JSON.parse(t))}catch(a){}return new Set})(t):new Set),[u,d]=e.useState(!1),[m,p]=e.useState(),[f,h]=e.useState(null),g=i.length-(n?new Set(_p(n).map(e=>e.id_user)).size:0);e.useEffect(()=>{if(n&&n.length>0&&t){if(!localStorage.getItem(`${Kp}-${t}`)){const e=n.map(e=>e.id),r=new Set(e);c(r),Xp(t,r)}}},[n,t]);const x=e=>{c(n=>{const r=new Set(n);return r.has(e)?r.delete(e):r.add(e),t&&Xp(t,r),r})},y=e=>{p(e),h(null),d(!0)};return r?fe.jsx("div",{className:"flex items-center justify-center h-full",children:fe.jsxs("div",{className:"text-center",children:[fe.jsx(o.RefreshCw,{className:"h-8 w-8 animate-spin mx-auto mb-4 text-muted-foreground"}),fe.jsx("p",{className:"text-muted-foreground",children:"Carregando hierarquia de liderança..."})]})}):a?fe.jsx("div",{className:"flex items-center justify-center h-full",children:fe.jsxs("div",{className:"text-center",children:[fe.jsx("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),fe.jsx(ve,{onClick:()=>s(),children:"Tentar novamente"})]})}):fe.jsxs("div",{className:"flex flex-col h-full",children:[fe.jsx("div",{className:"flex items-center justify-between p-4 border-b",children:fe.jsxs("div",{className:"flex gap-2 items-center",children:[fe.jsxs(ve,{size:"sm",onClick:()=>{p(void 0),h(null),d(!0)},children:[fe.jsx(o.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),fe.jsxs(ve,{variant:"outline",size:"sm",onClick:()=>{if(!n)return;const e=_p(n).filter(e=>e.children.length>0).map(e=>e.id),r=new Set(e);c(r),t&&Xp(t,r)},disabled:!n||0===n.length,children:[fe.jsx(o.ChevronDown,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),fe.jsxs(ve,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;c(e),t&&Xp(t,e)},disabled:!n||0===n.length,children:[fe.jsx(o.ChevronRight,{className:"h-4 w-4 mr-2"}),"Recolher todos"]}),fe.jsx("div",{className:"flex items-center gap-2 ml-4",children:fe.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[fe.jsx(o.Users,{className:"h-4 w-4 text-muted-foreground"}),fe.jsxs("span",{className:"text-sm font-medium",children:[g," usuário",1!==g?"s":""," não associado",1!==g?"s":""]})]})})]})}),n&&0!==n.length?fe.jsx(Or,{className:"flex-1",children:fe.jsx("div",{children:fe.jsxs("table",{className:"w-full",children:[fe.jsx("thead",{children:fe.jsxs("tr",{className:"border-b bg-muted/50",children:[fe.jsx("th",{className:"py-3 px-4 text-left font-semibold",children:"Nome"}),fe.jsx("th",{className:"py-3 px-4 text-center font-semibold",children:"Liderados"})]})}),fe.jsx("tbody",{children:n.map(e=>fe.jsx(Up,{leader:e,expandedIds:l,onToggleExpand:x,onEdit:y},e.id))})]})})}):fe.jsx("div",{className:"flex items-center justify-center flex-1",children:fe.jsxs("div",{className:"text-center space-y-4",children:[fe.jsx("p",{className:"text-muted-foreground",children:"Nenhuma hierarquia de liderança encontrada"}),fe.jsx("p",{className:"text-sm text-muted-foreground",children:'Clique em "Definir Líder" para começar'})]})}),fe.jsx(Qp,{open:u,onOpenChange:()=>{d(!1),p(void 0),h(null)},leader:m,prefilledLeaderId:f,title:m?"Editar Líder":f?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})},exports.LoadingState=function({isLoading:e,children:t,className:n,type:r="spinner",size:a="md"}){return e?"overlay"===r?fe.jsxs("div",{className:ge("relative",n),children:[t,fe.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:fe.jsx(ut,{size:a})})]}):"skeleton"===r?fe.jsx("div",{className:ge("animate-pulse",n),children:fe.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):fe.jsx("div",{className:ge("flex items-center justify-center py-8",n),children:fe.jsx(ut,{size:a})}):fe.jsx(fe.Fragment,{children:t})},exports.LoginPage=()=>fe.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:fe.jsxs(ke,{className:"w-full max-w-md",children:[fe.jsx(Ce,{className:"text-center",children:fe.jsx(Se,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),fe.jsxs(Ie,{className:"text-center space-y-4",children:[fe.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),fe.jsx(ve,{onClick:async()=>{jn()?await Bn.loginDev():Bn.loginProd()},className:"w-full",size:"lg",children:jn()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=Sn,exports.ManageAccessModal=Sp,exports.MarkdownMessage=Cp,exports.MultiSelect=$t,exports.NavigationProvider=Si,exports.PageBreadcrumb=function({items:e,maxItems:t=3,className:n}){return e.length>t&&(e[0],e.slice(-(t-1))),e.length,fe.jsx(ba,{className:n})},exports.PageMetadataProvider=ua,exports.Pagination=Qa,exports.PaginationContent=Ka,exports.PaginationEllipsis=Za,exports.PaginationItem=Xa,exports.PaginationLink=Ya,exports.PaginationNext=Ja,exports.PaginationPrevious=Ga,exports.PlaceCard=Ep,exports.PlacesList=function({places:e,isLoading:t,manageAccessConfig:n}){return t?fe.jsx("div",{className:"flex items-center justify-center py-12",children:fe.jsxs("div",{className:"text-center space-y-2",children:[fe.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),fe.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando locais..."})]})}):e&&0!==e.length?fe.jsxs("div",{className:"space-y-1",children:[fe.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),e.map(e=>fe.jsx(Ep,{place:e,manageAccessConfig:n},e.id))]}):fe.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[fe.jsx(o.Building2,{className:"h-12 w-12 text-muted-foreground/50"}),fe.jsxs("div",{children:[fe.jsx("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),fe.jsx("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})},exports.Popover=It,exports.PopoverContent=At,exports.PopoverTrigger=Tt,exports.Progress=es,exports.ProtectedRoute=({children:t})=>{const{isAuthenticated:n,isLoading:r}=qn();if(e.useEffect(()=>{if(!n)return;const e=()=>{Jt.areAllTokensValid()||Bn.logout()};e();const t=setInterval(e,3e5);return()=>clearInterval(t)},[n]),e.useEffect(()=>{if(r)return;if(n)return;if(Jt.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 s=jn();(async()=>{s?await Bn.loginDev():Bn.loginProd()})()},[n,r]),r)return fe.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:fe.jsxs(ke,{className:"w-full max-w-md",children:[fe.jsx(Ce,{className:"text-center",children:fe.jsx(Se,{className:"text-xl font-semibold",children:"Carregando..."})}),fe.jsxs(Ie,{className:"text-center",children:[fe.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),fe.jsx("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!n){if(new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token"))return fe.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:fe.jsxs(ke,{className:"w-full max-w-md",children:[fe.jsx(Ce,{className:"text-center",children:fe.jsx(Se,{className:"text-xl font-semibold",children:"Processando..."})}),fe.jsxs(Ie,{className:"text-center",children:[fe.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),fe.jsx("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})});try{if(Jt.areAllTokensValid())return fe.jsx(fe.Fragment,{children:t})}catch{}return fe.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:fe.jsxs(ke,{className:"w-full max-w-md",children:[fe.jsx(Ce,{className:"text-center",children:fe.jsx(Se,{className:"text-xl font-semibold",children:"Iniciando..."})}),fe.jsxs(Ie,{className:"text-center",children:[fe.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),fe.jsx("p",{className:"text-muted-foreground",children:jn()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return fe.jsx(fe.Fragment,{children:t})},exports.QUALIEX_CONFIG=kn,exports.QUERY_KEYS={crud:e=>[e],list:(e,t)=>[e,"list",t],detail:(e,t)=>[e,"detail",t]},exports.QualiexEnrichmentService=_n,exports.QualiexErrorInterceptor=gn,exports.QualiexUserField=Vr,exports.RadioGroup=ts,exports.RadioGroupItem=ns,exports.ResizableRail=$i,exports.SEARCH_CONFIG=Nn,exports.ScrollArea=Or,exports.ScrollBar=zr,exports.Select=Xe,exports.SelectContent=tt,exports.SelectGroup=Ye,exports.SelectItem=rt,exports.SelectLabel=nt,exports.SelectScrollDownButton=et,exports.SelectScrollUpButton=Ze,exports.SelectSearch=function({multiple:e=!1,options:t=[],value:n,onChange:r,getOptionValue:a=e=>e.value,getOptionLabel:s=e=>e.label,placeholder:i="Selecione...",label:l,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:d="Buscar...",disabled:m=!1,required:p=!1,isLoading:f=!1,error:h,className:g,sortOptions:x=!0,maxDisplayedBadges:y,popoverContainer:v,onOpen:b,onClose:w}){if(f)return fe.jsxs("div",{className:ge("space-y-2",g),children:[l&&fe.jsxs(je,{children:[l,p&&fe.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),fe.jsx(zt,{className:"h-10 w-full"})]});const N="string"==typeof h?h:h?"Erro ao carregar dados":void 0;return N?fe.jsxs("div",{className:ge("space-y-2",g),children:[l&&fe.jsxs(je,{children:[l,p&&fe.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),fe.jsxs("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[fe.jsx(o.AlertCircle,{className:"h-4 w-4"}),fe.jsx("span",{className:"text-sm",children:N})]})]}):fe.jsx(Wa,{multiple:e,options:t,value:n||(e?[]:""),onChange:r,getOptionValue:a,getOptionLabel:s,placeholder:i,label:l,icon:c,emptyMessage:u,searchPlaceholder:d,disabled:m,required:p,className:g,sortOptions:x,maxDisplayedBadges:y,popoverContainer:v,onOpen:b,onClose:w})},exports.SelectSeparator=at,exports.SelectTrigger=Je,exports.SelectValue=Ge,exports.Separator=rs,exports.Sheet=as,exports.SheetClose=is,exports.SheetContent=us,exports.SheetDescription=fs,exports.SheetFooter=ms,exports.SheetHeader=ds,exports.SheetOverlay=ls,exports.SheetPortal=os,exports.SheetTitle=ps,exports.SheetTrigger=ss,exports.Sidebar=js,exports.SidebarContent=Ps,exports.SidebarFooter=Ts,exports.SidebarGroup=_s,exports.SidebarGroupAction=Fs,exports.SidebarGroupContent=Rs,exports.SidebarGroupLabel=Ds,exports.SidebarHeader=Ui,exports.SidebarInput=Es,exports.SidebarInset=Ss,exports.SidebarMenu=Ls,exports.SidebarMenuAction=Us,exports.SidebarMenuBadge=Bs,exports.SidebarMenuButton=zs,exports.SidebarMenuItem=Ms,exports.SidebarMenuSkeleton=$s,exports.SidebarMenuSub=qs,exports.SidebarMenuSubButton=Hs,exports.SidebarMenuSubItem=Vs,exports.SidebarProvider=Ns,exports.SidebarRail=Cs,exports.SidebarSeparator=As,exports.SidebarSkeleton=function(){return fe.jsx("div",{className:"w-64 border-r bg-muted/10",children:fe.jsxs("div",{className:"p-4",children:[fe.jsx(zt,{className:"h-8 w-32 mb-6"}),fe.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((e,t)=>fe.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[fe.jsx(zt,{className:"h-4 w-4"}),fe.jsx(zt,{className:"h-4 w-20"})]},t))})]})})},exports.SidebarTrigger=ks,exports.Skeleton=zt,exports.Slider=Ws,exports.SonnerToaster=({...e})=>{const{theme:t="system"}=P.useTheme();return fe.jsx(i.Toaster,{theme:t,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"}},...e})},exports.Spinner=ut,exports.Stack=Jr,exports.StatusSelect=function({value:e,onChange:t,activeLabel:n="Ativo",inactiveLabel:r="Inativo",allLabel:a="[Todos]",placeholder:s="Status",className:i="w-full sm:w-[180px]"}){const o=[{id:"active",name:n},{id:"inactive",name:r},{id:"all",name:a}];return fe.jsx($r,{value:e,onChange:e=>t(e),items:o,getItemValue:e=>e.id,getItemLabel:e=>e.name,placeholder:s,className:i})},exports.Switch=mi,exports.TabPageContent=function({children:e,className:t}){return fe.jsx("div",{className:ge("space-y-6",t),children:e})},exports.TabPageHeader=function({title:e,description:t,actions:n,className:r}){return fe.jsxs("div",{className:ge("space-y-4",r),children:[fe.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[fe.jsxs("div",{className:"space-y-1",children:[fe.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:e}),t&&fe.jsx("p",{className:"text-muted-foreground text-sm",children:t})]}),n&&fe.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),fe.jsx(rs,{})]})},exports.TabPageLayout=function({children:e,className:t}){return fe.jsx("div",{className:ge("flex flex-col h-full",t),children:fe.jsx(Or,{className:"flex-1",children:fe.jsx("div",{className:"space-y-6 p-6",children:e})})})},exports.Table=rr,exports.TableBody=sr,exports.TableCaption=ur,exports.TableCell=cr,exports.TableFooter=ir,exports.TableHead=lr,exports.TableHeader=ar,exports.TableRow=or,exports.TableRowActions=Pr,exports.TableSkeleton=dr,exports.Tabs=pi,exports.TabsContent=gi,exports.TabsList=fi,exports.TabsTrigger=hi,exports.Textarea=it,exports.Toast=jt,exports.ToastAction=kt,exports.ToastClose=Ct,exports.ToastDescription=Et,exports.ToastProvider=bt,exports.ToastTitle=St,exports.ToastViewport=wt,exports.Toaster=function(){const{toasts:e}=vt();return fe.jsxs(bt,{children:[e.map(function({id:e,title:t,description:n,action:r,...a}){return fe.jsxs(jt,{...a,children:[fe.jsxs("div",{className:"grid gap-1",children:[t&&fe.jsx(St,{children:t}),n&&fe.jsx(Et,{children:n})]}),r,fe.jsx(Ct,{})]},e)}),fe.jsx(wt,{})]})},exports.Toggle=yi,exports.ToggleGroup=bi,exports.ToggleGroupItem=wi,exports.TokenManager=Jt,exports.TokenService=Vt,exports.Tooltip=gs,exports.TooltipContent=ys,exports.TooltipProvider=hs,exports.TooltipTrigger=xs,exports.VideoEditor=function({value:t,onChange:n,onSubmit:r,onCancel:a,uploadFunction:s,deleteFunction:i,uploadOptions:l}){const[c,u]=e.useState(t||{inputType:"url",controls:!0}),d=e.useRef(null),m=e.useRef(null),{upload:p,uploading:f}=Yp({uploadFunction:s,deleteFunction:i,defaultOptions:{...l,allowedTypes:["video/*"],maxSize:104857600}}),{upload:h,uploading:g}=Yp({uploadFunction:s,deleteFunction:i,defaultOptions:{...l,allowedTypes:["image/*"],maxSize:5242880}}),x=e.useMemo(()=>nf(c.videoUrl||tf(c.embedCode)||""),[c.videoUrl,c.embedCode]),y=(e,t)=>{const r={...c,[e]:t};u(r),n(r)};return fe.jsxs("div",{className:"space-y-6",children:[fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"Tipo de entrada"}),fe.jsxs(Xe,{value:c.inputType||"url",onValueChange:e=>y("inputType",e),children:[fe.jsx(Je,{children:fe.jsx(Ge,{})}),fe.jsxs(tt,{children:[fe.jsx(rt,{value:"url",children:"URL (YouTube/Vimeo/arquivo)"}),fe.jsx(rt,{value:"upload",children:"Upload de arquivo"}),fe.jsx(rt,{value:"embed",children:"Código de incorporação (iframe)"})]})]})]}),"embed"!==c.inputType&&fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"URL do vídeo"}),fe.jsx(we,{type:"url",placeholder:"https://www.youtube.com/watch?v=... ou arquivo direto",value:c.videoUrl||"",onChange:e=>y("videoUrl",e.target.value)})]}),"upload"===c.inputType&&s&&fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"Arquivo de vídeo"}),fe.jsxs("div",{className:"flex gap-2",children:[fe.jsx("input",{ref:d,type:"file",accept:"video/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await p(t),r={...c,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:c.title||t.name.replace(/\.[^/.]+$/,"")};u(r),n(r)}catch(r){}finally{d.current&&(d.current.value="")}},className:"hidden"}),fe.jsx(ve,{type:"button",variant:"outline",onClick:()=>d.current?.click(),disabled:f,children:f?fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Upload,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),c.videoFile&&fe.jsxs("span",{className:"text-xs text-muted-foreground truncate self-center",children:[c.videoFile," (",Math.round((c.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===c.inputType&&fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"Código embed (iframe)"}),fe.jsx(it,{placeholder:'<iframe src="https://www.youtube.com/embed/..." ...></iframe>',value:c.embedCode||"",onChange:e=>y("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),s&&fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"Thumbnail/Poster (opcional)"}),fe.jsxs("div",{className:"flex gap-2",children:[fe.jsx(we,{type:"url",placeholder:"https://exemplo.com/thumbnail.jpg",value:c.thumbnail||"",onChange:e=>y("thumbnail",e.target.value),className:"flex-1"}),fe.jsx("input",{ref:m,type:"file",accept:"image/*",onChange:async e=>{const t=e.target.files?.[0];if(t)try{const e=await h(t),r={...c,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};u(r),n(r)}catch(r){}finally{m.current&&(m.current.value="")}},className:"hidden"}),fe.jsx(ve,{type:"button",variant:"outline",onClick:()=>m.current?.click(),disabled:g,children:g?fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):fe.jsxs(fe.Fragment,{children:[fe.jsx(o.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),c.thumbnailFile&&fe.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.thumbnailFile]})]}),fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{htmlFor:"title",children:"Título (opcional)"}),fe.jsx(we,{id:"title",placeholder:"Título do vídeo",value:c.title||"",onChange:e=>y("title",e.target.value)})]}),fe.jsxs("div",{className:"flex gap-6",children:[fe.jsxs("div",{className:"flex items-center gap-2",children:[fe.jsx("input",{id:"autoplay",type:"checkbox",checked:c.autoplay||!1,onChange:e=>y("autoplay",e.target.checked),className:"h-4 w-4"}),fe.jsx(je,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay (mudo em embeds)"})]}),fe.jsxs("div",{className:"flex items-center gap-2",children:[fe.jsx("input",{id:"controls",type:"checkbox",checked:!1!==c.controls,onChange:e=>y("controls",e.target.checked),className:"h-4 w-4"}),fe.jsx(je,{htmlFor:"controls",className:"cursor-pointer",children:"Mostrar controles"})]})]}),fe.jsxs("div",{className:"space-y-2",children:[fe.jsx(je,{children:"Preview"}),fe.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const e=c.videoUrl||tf(c.embedCode)||"";if(!e)return fe.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Adicione uma URL, faça upload ou insira um código embed para visualizar"});if("file"===x)return fe.jsxs("video",{controls:!1!==c.controls,autoPlay:c.autoplay,poster:c.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[fe.jsx("source",{src:e}),"Seu navegador não suporta vídeos HTML5."]});const t="youtube"===x?Jp(e,c.autoplay):ef(e,c.autoplay);return fe.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:fe.jsx("iframe",{title:c.title||"Vídeo",src:t,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),fe.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[fe.jsx(ve,{variant:"outline",onClick:a,children:"Cancelar"}),fe.jsx(ve,{onClick:()=>{c.videoUrl||c.embedCode?r(c):yt({title:"Erro",description:"Adicione uma URL, faça upload de um vídeo ou insira um código embed",variant:"destructive"})},disabled:!(c.videoUrl||c.embedCode),children:"Salvar"})]})]})},exports.VideoRenderer=function({content:e,className:t="",style:n}){const r=e.videoUrl||tf(e.embedCode)||"";if(!r)return null;const a=nf(r);return fe.jsx(ke,{className:`overflow-hidden my-4 ${t}`,style:n,children:fe.jsxs(Ie,{className:"p-0",children:["file"===a?fe.jsxs("video",{controls:!1!==e.controls,autoPlay:e.autoplay,poster:e.thumbnail,className:"w-full h-auto",playsInline:!0,muted:e.autoplay,children:[fe.jsx("source",{src:r}),"Seu navegador não suporta vídeos HTML5."]}):fe.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:fe.jsx("iframe",{title:e.title||"Vídeo",src:"youtube"===a?Jp(r,e.autoplay):ef(r,e.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),e.title&&fe.jsx("div",{className:"p-4",children:fe.jsx("p",{className:"text-sm font-medium",children:e.title})})]})})},exports.assets=Mi,exports.badgeVariants=ot,exports.buildHierarchy=Pp,exports.buttonVariants=ye,exports.calculateAspectRatio=rf,exports.cn=ge,exports.createCrudPage=function(e){return({manager:t})=>{const{manager:n,config:r,onSave:a,onEdit:s,onToggleStatus:i}=e,o=t??n,l={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:s||r.onEdit};return fe.jsx(ea,{manager:o,config:l,formSections:r.formSections,onSave:a,onToggleStatus:i,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,t){const n=ji({basePath:e,newPath:t.newPath,editPath:t.editPath});return{useCustomRouting:!0,onNew:n.onNew,onEdit:n.onEdit}},exports.createRoutingHandlers=ji,exports.createService=Rn,exports.createSimpleSaveHandler=function(e,t,n){return r=>{if(r.id){const t=n(r);e.updateEntity(r.id,t)}else{const n=t(r);e.createEntity(n)}}},exports.createSimpleService=function(e){const t=Rn({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:(n,r)=>Vn({queryKey:e.tableName,service:{...t,getAll:async(e={})=>await t.getAll({...e})},entityName:e.entityName,additionalFilters:n,onSuccess:r})}},exports.crudPresets=aa,exports.debounce=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},exports.deriveEmailField=In,exports.deriveNameField=En,exports.deriveUsernameField=Tn,exports.detectVideoProvider=nf,exports.emailService=Xi,exports.errorService=tn,exports.extractImageFileName=function(e){try{const t=new URL(e),n=t.pathname.split("/");return n[n.length-1]||"image"}catch{const t=e.split("/");return t[t.length-1]||"image"}},exports.extractVimeoId=Zp,exports.extractYouTubeId=Gp,exports.flattenTree=_p,exports.formatCurrency=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDatetime=e=>{if(!e)return"";const t=s.parseISO(e);if(!s.isValid(t))return"Data inválida";return`${t.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`},exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=ta,exports.getQualiexConfig=Cn,exports.getSupabaseClient=cn,exports.handleExternalLink=he,exports.isDevEnvironment=jn,exports.isImageUrl=function(e){const t=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>t.includes(e))},exports.logoSrc=Oi,exports.normalizeVideoUrl=function(e,t,n){switch(t||nf(e)){case"youtube":return Jp(e,n);case"vimeo":return ef(e,n);default:return e}},exports.normalizeVimeoUrl=ef,exports.normalizeYouTubeUrl=Jp,exports.parseIframeSrc=tf,exports.placeService=Ap,exports.qualiexApi=vn,exports.resizeKeepingAspect=function(e,t,n,r){const a=rf(e,t);return n&&!r?{width:n,height:Math.round(n/a)}:r&&!n?{width:Math.round(r*a),height:r}:{width:e,height:t}},exports.resolveFieldMappings=An,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=zi,exports.toast=yt,exports.toggleVariants=xi,exports.trimTextFields=xe,exports.useActiveModules=_i,exports.useAuth=qn,exports.useBaseForm=Rr,exports.useCreateLeaderMutation=function(){const e="common",{alias:t}=qn(),n=g.useQueryClient(),r=cn();return g.useMutation({mutationFn:async n=>{if(!t)throw new Error("Unidade não selecionada");if(n.id_user===n.id_leader)throw new Error("Usuário não pode ser seu próprio líder");if((await r.schema(e).from("leaders").select("id").eq("alias",t).eq("id_user",n.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");n.id_leader&&await zp(r,t,e,n.id_user,n.id_leader);const{data:a,error:s}=await r.schema(e).from("leaders").insert({alias:t,id_user:n.id_user,id_leader:n.id_leader,is_active:!0,is_removed:!1}).select().single();if(s)throw s;return a},onSuccess:()=>{n.invalidateQueries({queryKey:["leadership",t]}),i.toast.success("Líder adicionado com sucesso")},onError:e=>{i.toast.error(e.message||"Erro ao adicionar líder")}})},exports.useCreateMultipleLeadersMutation=Rp,exports.useCreateSingleLeaderMutation=Fp,exports.useCrud=Vn,exports.useDebounce=Ti,exports.useFormField=$e,exports.useLeadershipApi=Dp,exports.useMediaUpload=Yp,exports.useNavigation=Ei,exports.useOpenAIChat=Yi,exports.usePageMetadata=function(t){const{setMetadata:n,clearMetadata:r}=da();e.useEffect(()=>(n(t),()=>r()),[t.title,t.subtitle,n,r])},exports.usePageTitle=Ii,exports.usePermissionQuery=Pi,exports.useQualiexUsers=qr,exports.useRemoveLeaderMutation=Mp,exports.useRouteBreadcrumbs=function(){const e=x.useLocation();return(()=>{const t=e.pathname.split("/").filter(Boolean),n=[{label:"Exemplos",href:"/"}];let r="";return t.forEach((e,a)=>{r+=`/${e}`;const s=a===t.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");n.push({label:i,href:s?void 0:r,isCurrentPage:s})}),n})()},exports.useSidebar=ws,exports.useSidebarResize=Bi,exports.useSyncSubordinatesMutation=Op,exports.useToast=vt,exports.useUpdateLeaderMutation=Lp,exports.withPreset=function(e,t,n={}){const r=aa[e];return ta(r.title,t,{...r,...n})};
|
|
1
|
+
"use strict";var e=require("react/jsx-runtime"),a=require("react"),t=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"),x=require("@radix-ui/react-popover"),f=require("@supabase/supabase-js"),g=require("@tanstack/react-query"),b=require("react-router-dom"),v=require("@radix-ui/react-alert-dialog"),N=require("@radix-ui/react-dropdown-menu"),j=require("@radix-ui/react-scroll-area"),y=require("@radix-ui/react-accordion"),w=require("@radix-ui/react-aspect-ratio"),C=require("@radix-ui/react-avatar"),k=require("react-day-picker"),S=require("@radix-ui/react-collapsible"),E=require("@radix-ui/react-progress"),A=require("@radix-ui/react-radio-group"),T=require("@radix-ui/react-separator"),I=require("@radix-ui/react-tooltip"),P=require("@radix-ui/react-slider"),_=require("next-themes"),R=require("@radix-ui/react-switch"),F=require("@radix-ui/react-tabs"),D=require("@radix-ui/react-toggle"),M=require("@radix-ui/react-toggle-group"),L=require("react-markdown"),z=require("remark-gfm"),O=require("zod"),U=require("@hookform/resolvers");function $(e){var a=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}}),a.default=e,Object.freeze(a)}var q=$(a),V=$(d),B=$(c),W=$(m),H=$(p),Q=$(h),K=$(x),G=$(v),X=$(N),J=$(j),Y=$(y),Z=$(w),ee=$(C),ae=$(S),te=$(E),se=$(A),re=$(T),ne=$(I),ie=$(P),oe=$(R),le=$(F),de=$(D),ce=$(M);function ue(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{o.toast.info("Link copiado para a área de transferência")})}function me(...e){return n.twMerge(r.clsx(e))}const pe=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(pe);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,s]of Object.entries(e))a[t]=pe(s);return a}return e},he=s.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium 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 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline",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:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6"}},defaultVariants:{variant:"default",size:"default"}}),xe=q.forwardRef(({className:a,variant:s,size:r,asChild:n=!1,...i},o)=>{const l=n?t.Slot:"button";return e.jsx(l,{className:me(he({variant:s,size:r,className:a})),ref:o,...i})});xe.displayName="Button";const fe=a.forwardRef(({variant:a="default",className:t,children:s,...r},n)=>e.jsx(xe,{ref:n,variant:"action",size:"sm",className:me("h-7 px-2 text-xs",t),...r,children:s||e.jsx(l.EllipsisVertical,{size:12})}));fe.displayName="ActionButton";const ge=q.forwardRef(({className:a,type:t,...s},r)=>e.jsx("input",{type:t,className:me("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",a),ref:r,...s}));ge.displayName="Input";const be=s.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ve=q.forwardRef(({className:a,...t},s)=>e.jsx(V.Root,{ref:s,className:me(be(),a),...t}));ve.displayName=V.Root.displayName;const Ne=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("rounded-lg border bg-card text-card-foreground shadow-sm",a),...t}));Ne.displayName="Card";const je=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex flex-col space-y-1.5 p-6",a),...t}));je.displayName="CardHeader";const ye=q.forwardRef(({className:a,...t},s)=>e.jsx("h3",{ref:s,className:me("text-2xl font-semibold leading-none tracking-tight",a),...t}));ye.displayName="CardTitle";const we=q.forwardRef(({className:a,...t},s)=>e.jsx("p",{ref:s,className:me("text-sm text-muted-foreground",a),...t}));we.displayName="CardDescription";const Ce=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("p-6 pt-0",a),...t}));Ce.displayName="CardContent";const ke=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex items-center p-6 pt-0",a),...t}));ke.displayName="CardFooter";const Se=B.Root,Ee=B.Trigger,Ae=B.Portal,Te=B.Close,Ie=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Overlay,{ref:s,className:me("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",a),...t}));Ie.displayName=B.Overlay.displayName;const Pe=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(Ae,{children:[e.jsx(Ie,{}),e.jsxs(B.Content,{ref:r,className:me("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 bg-background p-6 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%] rounded-lg max-h-[90vh] overflow-auto",a),...s,children:[t,e.jsxs(B.Close,{className:"absolute right-4 top-4 z-10 rounded-sm text-white opacity-70 ring-offset-background transition-opacity hover:opacity-100 hover:text-white 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:"Close"})]})]})]}));Pe.displayName=B.Content.displayName;const _e=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col space-y-1.5 text-center sm:text-left bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-3 rounded-t-lg",a),...t});_e.displayName="DialogHeader";const Re=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Re.displayName="DialogFooter";const Fe=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Title,{ref:s,className:me("text-lg font-semibold leading-none tracking-tight",a),...t}));Fe.displayName=B.Title.displayName;const De=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Description,{ref:s,className:me("text-sm text-white",a),...t}));De.displayName=B.Description.displayName;const Me=u.FormProvider,Le=q.createContext({}),ze=()=>{const e=q.useContext(Le),a=q.useContext(Oe),{getFieldState:t,formState:s}=u.useFormContext(),r=t(e.name,s);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:n}=a;return{id:n,name:e.name,formItemId:`${n}-form-item`,formDescriptionId:`${n}-form-item-description`,formMessageId:`${n}-form-item-message`,...r}},Oe=q.createContext({}),Ue=q.forwardRef(({className:a,...t},s)=>{const r=q.useId();return e.jsx(Oe.Provider,{value:{id:r},children:e.jsx("div",{ref:s,className:me("space-y-2",a),...t})})});Ue.displayName="FormItem";const $e=q.forwardRef(({className:a,...t},s)=>{const{error:r,formItemId:n}=ze();return e.jsx(ve,{ref:s,className:me(r&&"text-destructive",a),htmlFor:n,...t})});$e.displayName="FormLabel";const qe=q.forwardRef(({...a},s)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=ze();return e.jsx(t.Slot,{ref:s,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...a})});qe.displayName="FormControl";const Ve=q.forwardRef(({className:a,...t},s)=>{const{formDescriptionId:r}=ze();return e.jsx("p",{ref:s,id:r,className:me("text-sm text-muted-foreground",a),...t})});Ve.displayName="FormDescription";const Be=q.forwardRef(({className:a,children:t,...s},r)=>{const{error:n,formMessageId:i}=ze(),o=n?String(n?.message):t;return o?e.jsx("p",{ref:r,id:i,className:me("text-sm font-medium text-destructive",a),...s,children:o}):null});Be.displayName="FormMessage";const We=W.Root,He=W.Group,Qe=W.Value,Ke=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(W.Trigger,{ref:r,className:me("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",a),...s,children:[t,e.jsx(W.Icon,{asChild:!0,children:e.jsx(l.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Ke.displayName=W.Trigger.displayName;const Ge=q.forwardRef(({className:a,...t},s)=>e.jsx(W.ScrollUpButton,{ref:s,className:me("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronUp,{className:"h-4 w-4"})}));Ge.displayName=W.ScrollUpButton.displayName;const Xe=q.forwardRef(({className:a,...t},s)=>e.jsx(W.ScrollDownButton,{ref:s,className:me("flex cursor-default items-center justify-center py-1",a),...t,children:e.jsx(l.ChevronDown,{className:"h-4 w-4"})}));Xe.displayName=W.ScrollDownButton.displayName;const Je=q.forwardRef(({className:a,children:t,position:s="popper",container:r,collisionBoundary:n,...i},o)=>e.jsx(W.Portal,{container:r,children:e.jsxs(W.Content,{ref:o,className:me("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===s&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:s,collisionBoundary:n,...i,children:[e.jsx(Ge,{}),e.jsx(W.Viewport,{className:me("p-1","popper"===s&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Xe,{})]})}));Je.displayName=W.Content.displayName;const Ye=q.forwardRef(({className:a,...t},s)=>e.jsx(W.Label,{ref:s,className:me("py-1.5 pl-8 pr-2 text-sm font-semibold",a),...t}));Ye.displayName=W.Label.displayName;const Ze=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(W.Item,{ref:r,className:me("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e.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:t})]}));Ze.displayName=W.Item.displayName;const ea=q.forwardRef(({className:a,...t},s)=>e.jsx(W.Separator,{ref:s,className:me("-mx-1 my-1 h-px bg-muted",a),...t}));ea.displayName=W.Separator.displayName;const aa=q.forwardRef(({className:a,...t},s)=>e.jsx(H.Root,{ref:s,className:me("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",a),...t,children:e.jsx(H.Indicator,{className:me("flex items-center justify-center text-current"),children:e.jsx(l.Check,{className:"h-4 w-4"})})}));aa.displayName=H.Root.displayName;const ta=q.forwardRef(({className:a,...t},s)=>e.jsx("textarea",{className:me("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",a),ref:s,...t}));ta.displayName="Textarea";const sa=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"}}),ra=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,className:me(sa({variant:t}),a),...s}));ra.displayName="Badge";const na={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ia({size:a="md",className:t}){return e.jsx(l.Loader2,{className:me("animate-spin text-muted-foreground",na[a],t)})}let oa=0;const la=new Map,da=e=>{if(la.has(e))return;const a=setTimeout(()=>{la.delete(e),pa({type:"REMOVE_TOAST",toastId:e})},1e6);la.set(e,a)},ca=(e,a)=>{switch(a.type){case"ADD_TOAST":return{...e,toasts:[a.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===a.toast.id?{...e,...a.toast}:e)};case"DISMISS_TOAST":{const{toastId:t}=a;return t?da(t):e.toasts.forEach(e=>{da(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===t||void 0===t?{...e,open:!1}:e)}}case"REMOVE_TOAST":return void 0===a.toastId?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(e=>e.id!==a.toastId)}}},ua=[];let ma={toasts:[]};function pa(e){ma=ca(ma,e),ua.forEach(e=>{e(ma)})}function ha({...e}){const a=(oa=(oa+1)%Number.MAX_SAFE_INTEGER,oa.toString()),t=()=>pa({type:"DISMISS_TOAST",toastId:a});return pa({type:"ADD_TOAST",toast:{...e,id:a,open:!0,onOpenChange:e=>{e||t()}}}),{id:a,dismiss:t,update:e=>pa({type:"UPDATE_TOAST",toast:{...e,id:a}})}}function xa(){const[e,a]=q.useState(ma);return q.useEffect(()=>(ua.push(a),()=>{const e=ua.indexOf(a);e>-1&&ua.splice(e,1)}),[e]),{...e,toast:ha,dismiss:e=>pa({type:"DISMISS_TOAST",toastId:e})}}const fa=Q.Provider,ga=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Viewport,{ref:s,className:me("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",a),...t}));ga.displayName=Q.Viewport.displayName;const ba=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"}}),va=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx(Q.Root,{ref:r,className:me(ba({variant:t}),a),...s}));va.displayName=Q.Root.displayName;const Na=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Action,{ref:s,className:me("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",a),...t}));Na.displayName=Q.Action.displayName;const ja=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Close,{ref:s,className:me("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",a),"toast-close":"",...t,children:e.jsx(l.X,{className:"h-4 w-4"})}));ja.displayName=Q.Close.displayName;const ya=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Title,{ref:s,className:me("text-sm font-semibold",a),...t}));ya.displayName=Q.Title.displayName;const wa=q.forwardRef(({className:a,...t},s)=>e.jsx(Q.Description,{ref:s,className:me("text-sm opacity-90",a),...t}));wa.displayName=Q.Description.displayName;const Ca=K.Root,ka=K.Trigger,Sa=q.forwardRef(({className:a,align:t="center",sideOffset:s=4,container:r,...n},i)=>e.jsx(K.Portal,{container:r,children:e.jsx(K.Content,{ref:i,align:t,sideOffset:s,className:me("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",a),...n})}));Sa.displayName=K.Content.displayName;const Ea=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",a),...t}));Ea.displayName="Command";const Aa=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:e.jsx("input",{ref:s,className:me("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",a),...t})}));Aa.displayName="CommandInput";const Ta=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("max-h-[300px] overflow-y-auto overflow-x-hidden",a),...t}));Ta.displayName="CommandList";const Ia=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("py-6 text-center text-sm text-muted-foreground",a),...t}));Ia.displayName="CommandEmpty";const Pa=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("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",a),...t}));Pa.displayName="CommandGroup";const _a=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("-mx-1 h-px bg-border",a),...t}));_a.displayName="CommandSeparator";const Ra=q.forwardRef(({className:a,disabled:t,onSelect:s,value:r,...n},i)=>e.jsx("div",{ref:i,className:me("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",a),"data-disabled":t,onClick:()=>!t&&s?.(r||""),...n}));Ra.displayName="CommandItem";const Fa=({className:a,...t})=>e.jsx("span",{className:me("ml-auto text-xs tracking-widest text-muted-foreground",a),...t});function Da({className:a,...t}){return e.jsx("div",{className:me("animate-pulse rounded-md bg-muted",a),...t})}Fa.displayName="CommandShortcut";const Ma=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function La({multiple:t,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:x,className:f,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:N,onClose:j}){const[y,w]=a.useState(!1),[C,k]=a.useState(""),S=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,g]),T=a.useMemo(()=>{if(!C)return A;const e=Ma(C);return A.filter(a=>Ma(a.label).includes(e))},[A,C]),I=a.useMemo(()=>A.filter(e=>S.includes(e.value)),[A,S]),P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?S.filter(a=>a!==e):"")},_=b?I.slice(0,b):I,R=b&&I.length>b?I.length-b:0;return e.jsxs("div",{className:me("space-y-2",f),children:[c&&e.jsxs(ve,{children:[c,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ca,{open:y,onOpenChange:e=>{w(e),e?N?.():(k(""),j?.())},modal:!1,children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",role:"combobox","aria-expanded":y,disabled:h,className:me("w-full justify-between min-h-10 h-auto",0===I.length&&"text-muted-foreground"),children:[0===I.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),d]}):t?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[_.map(a=>e.jsxs(ra,{variant:"secondary",className:"gap-1 pr-1",children:[a.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&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),R>0&&e.jsxs(ra,{variant:"outline",className:"gap-1",children:["+",R]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),I[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Sa,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(Ea,{children:[e.jsx(Aa,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),e.jsx(Ta,{children:0===s.length?e.jsx(Ia,{children:m}):0===T.length?e.jsx(Ia,{children:"Nenhum item encontrado."}):e.jsx(Pa,{children:T.map(a=>e.jsxs(Ra,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=S.includes(e)?S.filter(a=>a!==e):[...S,e];n(a)}else n(e),w(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:me("mr-2 h-4 w-4",S.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}function za({multiple:a=!0,options:t=[],value:s,onChange:r,getOptionValue:n=e=>e.value,getOptionLabel:i=e=>e.label,placeholder:o="Selecione itens...",label:d,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:m="Buscar...",disabled:p=!1,required:h=!1,isLoading:x=!1,error:f,className:g,sortOptions:b=!0,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y}){if(x)return e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Da,{className:"h-10 w-full"})]});const w="string"==typeof f?f:f?"Erro ao carregar dados":void 0;return w?e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&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:w})]})]}):e.jsx(La,{multiple:a,options:t,value:s||(a?[]:""),onChange:r,getOptionValue:n,getOptionLabel:i,placeholder:o,label:d,icon:c,emptyMessage:u,searchPlaceholder:m,disabled:p,required:h,className:g,sortOptions:b,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y})}var Oa=Object.defineProperty;class Ua{static normalizeBase64Url(e){let a=e.replace(/-/g,"+").replace(/_/g,"/");const t=(4-a.length%4)%4;return a+="=".repeat(t),a}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),a=atob(e),t=new Uint8Array(a.length);for(let r=0;r<a.length;r++)t[r]=a.charCodeAt(r);const s=new TextDecoder("utf-8").decode(t);return JSON.parse(s)}catch(a){try{const e=this.normalizeBase64Url(n),a=decodeURIComponent(atob(e).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(a)}catch(t){try{const e=this.normalizeBase64Url(n),a=atob(e);return JSON.parse(a)}catch(s){throw s}}}}catch(r){return null}}static validateTokens(e,a){const t=[],s=[];try{a.split(".")[1],e.split(".")[1];const r=this.parseJwtPayload(a),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:t,errors:s}}let i=!0;if(!n){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.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";t.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:t,errors:s}}return{isValid:!0,idTokenValid:!0,accessTokenValid:i,warnings:t,errors:s}}catch(r){const e=`Erro na validação de tokens: ${r}`;return s.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:s}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}static extractTokenData(e){return this.parseJwtPayload(e)}}((e,a,t)=>{a in e?Oa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(Ua,"LARGE_PAYLOAD_THRESHOLD"+"",1e3);const $a="qualiex_access_token",qa="qualiex_id_token",Va="supabase_token",Ba="oauth_state",Wa="oauth_nonce",Ha="selected_alias",Qa="manual_logout",Ka={setAccessToken:e=>localStorage.setItem($a,e),getAccessToken:()=>localStorage.getItem($a),setIdToken:e=>localStorage.setItem(qa,e),getIdToken:()=>localStorage.getItem(qa),getSupabaseToken:()=>localStorage.getItem(Va),setOAuthState:e=>sessionStorage.setItem(Ba,e),getOAuthState:()=>sessionStorage.getItem(Ba),clearOAuthState:()=>sessionStorage.removeItem(Ba),setOAuthNonce:e=>sessionStorage.setItem(Wa,e),getOAuthNonce:()=>sessionStorage.getItem(Wa),clearOAuthNonce:()=>sessionStorage.removeItem(Wa),setSelectedAlias:e=>localStorage.setItem(Ha,e),getSelectedAlias:()=>localStorage.getItem(Ha),clearSelectedAlias:()=>localStorage.removeItem(Ha),generateOAuthState:()=>"Lw==",generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ka.getAccessToken()||!Ka.getIdToken()),setSupabaseToken:e=>{localStorage.setItem(Va,e),Ka._clearValidationCache()},areAllTokensValid:()=>{const e=Ka.getAccessToken(),a=Ka.getIdToken();if(!e||!a)return!1;try{const t=Ua.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ka.getAccessToken(),t=Ka.getIdToken(),s=Ka.getSupabaseToken();return a&&Ka.isTokenExpired(a)&&(localStorage.removeItem($a),e=!0),t&&Ka.isTokenExpired(t)&&(localStorage.removeItem(qa),e=!0),s&&Ka.isTokenExpired(s)&&(localStorage.removeItem(Va),e=!0),e},clearAll:()=>{localStorage.removeItem($a),localStorage.removeItem(qa),localStorage.removeItem(Va),localStorage.removeItem(Ha),localStorage.removeItem(Qa),sessionStorage.removeItem(Ba),sessionStorage.removeItem(Wa)},setManualLogout:()=>localStorage.setItem(Qa,"true"),isManualLogout:()=>"true"===localStorage.getItem(Qa),clearManualLogout:()=>localStorage.removeItem(Qa),isTokenExpired:e=>{try{return Ua.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ka._validationCache.isValid=!1,Ka._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ka.getSupabaseToken();if(!e)return!1;if(Ka.isTokenExpired(e))return Ka._clearValidationCache(),Ka._handleExpiredToken(),!1;const a=Date.now();return a-Ka._validationCache.timestamp<Ka._validationCache.cacheValidityMs?Ka._validationCache.isValid:(Ka._validationCache.isValid=!0,Ka._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ka.isSupabaseTokenValid()?Ka.getSupabaseToken():null,_handleExpiredToken:()=>{Ka.clearAll(),"undefined"!=typeof window&&(window.location.href="/")},extractTokenData:()=>{if(!Ka.isSupabaseTokenValid())return null;const e=Ka.getSupabaseToken();if(!e)return null;try{const a=Ua.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,s=a.place_id||null,r=a.place_name||null;let n=a.company_id;if(!n&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");if(e.length>7&&e[0]===t){n=e[7];break}}}return{alias:t,companyId:n,placeId:s,placeName:r,payload:a}}catch(a){return Ka._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ka.getAccessToken();if(a)try{const t=Ua.parseJwtPayload(a);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 a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}const t=Ka.extractTokenData();if(t?.companyId)return t.companyId;const s=Ka.getIdToken();if(s)try{const a=Ua.parseJwtPayload(s);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 a=s.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(r){}return null},getCurrentCompanyId:()=>{const e=Ka.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ka.getIdToken();if(!e)return[];try{const a=Ua.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const s=a[e];if(s&&"string"==typeof s){const e=s.split(";");e.length>=4&&t.push({id:e.length>7?e[7]:"",alias:e[0].trim(),name:e[3].trim(),payload:a})}}return t}catch{return[]}}};var Ga=Object.defineProperty,Xa=(e,a,t)=>((e,a,t)=>a in e?Ga(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const Ja=new class{constructor(){Xa(this,"errors",[]),Xa(this,"toastCount",0),Xa(this,"lastToastTime",0)}handleError(e,a=!0){const t="string"==typeof e?e:e.message;if(this.errors.push({id:Date.now().toString(),message:t,timestamp:Date.now(),count:1}),a&&this.shouldShowToast()){ha({title:this.getErrorTitle(t),description:t,variant:"destructive"})}}getErrorTitle(e){const a=e.toLowerCase();return a.includes("401")||a.includes("unauthorized")||a.includes("expirou")?"Sessão Expirada":a.includes("token")||a.includes("autenticação")?"Erro de Autenticação":a.includes("api")||a.includes("network")?"Erro de Conexão":"Erro"}success(e,a){ha({title:e,description:a,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 Ya=Object.defineProperty,Za=(e,a,t)=>((e,a,t)=>a in e?Ya(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);const et=(void 0).VITE_SUPABASE_URL,at=(void 0).VITE_SUPABASE_PUBLISHABLE_KEY,tt=class e{constructor(){Za(this,"client"),Za(this,"currentToken",null),Za(this,"instanceCount",0),this.instanceCount++,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:at};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return f.createClient(et,at,{auth:{persistSession:!1,autoRefreshToken:!1,detectSessionInUrl:!1,storage:void 0},global:{headers:a,fetch:async(e,a)=>("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,a)}})}static getInstance(){return e.instance||(e.instance=new e),e.instance}getClient(){const e=Ka.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{const a=JSON.parse(atob(e.split(".")[1])),t=Math.floor(Date.now()/1e3);return a.exp>t}catch(a){return Ja.handleError(a instanceof Error?a:"❌ Supabase - Error validating token",!1),!1}}};Za(tt,"instance");let st=tt;function rt(){return st.getInstance().getClient()}class nt{static async generateToken(e,a,t,s=!1){try{if(!s){const e=Ka.getSupabaseToken();if(e&&Ka.isSupabaseTokenValid())return e}const r=rt(),{data:n,error:i}=await r.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return i&&(i.message?.includes("401")||i.message?.includes("Unauthorized"))?(t?.(),null):n?.access_token&&n.access_token?(Ka.setSupabaseToken(n.access_token),n.access_token):null}catch(r){return r instanceof Error&&(r.message.includes("401")||r.message.includes("Unauthorized"))&&t?.(),null}}}var it=Object.defineProperty,ot=(e,a,t)=>((e,a,t)=>a in e?it(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,"symbol"!=typeof a?a+"":a,t);class lt{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(){if(this.isRegenerating)return null;this.isRegenerating=!0;try{const e=Ka.getAccessToken(),a=Ka.getSelectedAlias();if(!e||!a)return null;const t=await nt.generateToken(e,a,this.onLogoutCallback||void 0,!1);return t?(Ka.setSupabaseToken(t),t):null}catch(e){return null}finally{this.isRegenerating=!1}}}ot(lt,"isRegenerating",!1),ot(lt,"onLogoutCallback",null);class dt{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ka.clearAll(),window.location.href="/",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token","expired","invalid","authentication","login","session"].some(e=>t.includes(e))}static async wrapAsync(e){try{return await e}catch(a){if(!this.handleError(a))throw a;throw new Error("Sua sessão expirou. Você será redirecionado para fazer login novamente.")}}}var ct=Object.defineProperty;class ut{static async handleApiError(e){if(!e||this.isRetrying)return!1;const a=e.status||e.statusCode,t=e.message||e.toString();if(401===a||t.includes("401")||t.includes("Unauthorized")){this.isRetrying=!0;try{return await lt.attemptRegeneration()?(this.isRetrying=!1,!0):(dt.handleError(e),this.isRetrying=!1,!1)}catch(s){return dt.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ka.getAccessToken();return e?Ka.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,a,t)=>{((e,a,t)=>{a in e?ct(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t})(e,a+"",t)})(ut,"isRetrying",!1);var mt=Object.defineProperty,pt=(e,a,t)=>((e,a,t)=>a in e?mt(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const ht=new class{constructor(){pt(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const s=ut.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=Ka.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório para chamadas à API do Qualiex");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status} ${i.statusText}`);throw e.status=i.status,e.statusCode=i.status,e}return await i.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}async fetchUsers(e,a){try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let s=t;if(t.data)s=t.data;else{if(!Array.isArray(t))return Ja.handleError("[QualiexApi] Formato de resposta inesperado",!1),[];s=t}if(!Array.isArray(s))return Ja.handleError("[QualiexApi] Resposta não é um array",!1),[];return s.map(this.mapToQualiexUser)}catch(t){if(await ut.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/companiesusers",{companyId:a,search:"",filterStatus:"active"},e);let s=t;if(t.data)s=t.data;else{if(!Array.isArray(t))return Ja.handleError("[QualiexApi] Formato de resposta inesperado após retry",!1),[];s=t}return Array.isArray(s)?s.map(this.mapToQualiexUser):(Ja.handleError("[QualiexApi] Resposta não é um array após retry",!1),[])}catch(s){return Ja.handleError(s instanceof Error?s:"Erro ao buscar usuários após renovação de token",!0),[]}const r=t instanceof Error?t.message:"Erro ao buscar usuários da API Qualiex";return Ja.handleError(r,!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(s){return Ja.handleError(s instanceof Error?s:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),s=new Map;return t.forEach(e=>{s.set(e.userId,e)}),s}async getUsers(e){const a=Ka.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}},xt={oauth:{authUrl:(void 0).VITE_OAUTH_AUTH_URL,clientId:(void 0).VITE_OAUTH_CLIENT_ID,responseType:"id_token token",scope:"openid profile email"}},ft={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},gt={debounceDelay:500},bt=()=>{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},vt={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Nt=()=>vt,jt={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 yt(e,a){const t=Nt(),s=a||t.userNameFieldSuffix||"_name";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function wt(e,a){const t=Nt(),s=a||t.userEmailFieldSuffix||"_email";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function Ct(e,a){const t=Nt(),s=a||t.userUsernameFieldSuffix||"_username";return e.endsWith("_id")?e.replace(/_id$/,s):`${e}${s}`}function kt(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||yt(e.idField),emailField:e.emailField||wt(e.idField),usernameField:e.usernameField||Ct(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:yt(e),emailField:wt(e),usernameField:Ct(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const St=new Map;class Et{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,s=St.get(t);if(s&&Date.now()-s.timestamp<3e5)return s.users;const r=await ht.fetchUsers(e,a);return St.set(t,{users:r,timestamp:Date.now()}),r}static extractUserIds(e,a){const t=new Set;for(const s of e)for(const e of a){const a=s[e.idField];a&&"string"==typeof a&&""!==a.trim()&&t.add(a)}return t}static indexUsers(e){const a=new Map;for(const t of e)t.id&&a.set(t.id,t),t.userId&&a.set(t.userId,t);return a}static enrichEntity(e,a,t){const s={...e};for(const r of a){const a=e[r.idField];if(!a)continue;const n=t.get(a);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,a){if(!Array.isArray(e)||0===e.length)return e;try{const t=Ka.extractTokenData();if(!t)return e;const{alias:s,companyId:r}=t;if(!s||!r)return e;const n=kt(a.userIdFields,a.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(t){return Ja.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}static async enrichWithResponsibleNames(e,a){return this.enrichWithUserData(e,{entityName:a.entityName,userIdFields:["id_user"],userFieldsMapping:[{idField:"id_user",nameField:"responsible_name"}]})}}const At=["responsible_name"],Tt=e=>At.includes(e);function It(e,a,t){const s="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"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(!Ka.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return rt().schema(o).from(r)},u=(e,a,t,s)=>{let r=c().select(i||"*",{count:"exact"});r=r.eq("is_removed",!1),Object.entries(s).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?r=r.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?r=r.not(e,"is",null):"is_null"===a.operator&&(r=r.is(e,null)):null!==a&&(r=r.eq(e,a)))}),r=((e,a)=>{if(a&&n.length>0){const t=n.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(r,e);const o=a.includes(".");return o||Tt(a)||(r=r.order(a,{ascending:"asc"===t})),{query:r,isForeignKey:o}},m=async(e,a,t,r,n)=>{const i=kt(s.userIdFields,s.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Tt(a)||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 Et.enrichWithUserData(i.data,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping});let c;c=o?d.sort((e,s)=>{const r=a.split(".").reduce((e,a)=>e?.[a],e)||"",n=a.split(".").reduce((e,a)=>e?.[a],s)||"",i=String(r).localeCompare(String(n),"pt-BR");return"asc"===t?i:-i}):((e,a,t)=>[...e].sort((e,s)=>{const r=e[a]||"",n=s[a]||"",i=r.localeCompare(n,"pt-BR",{sensitivity:"base"});return"asc"===t?i:-i}))(d,a,t);const u=((e,a=1,t=25)=>{const s=(a-1)*t,r=s+t,n=e.slice(s,r);return{data:n,pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:n.length,totalCount:e.length,itemsPerPage:t,hasNextPage:r<e.length,hasPreviousPage:a>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 Et.enrichWithUserData(e,{entityName:l,userIdFields:s.userIdFields,userFieldsMapping:s.userFieldsMapping})};return{async getAll(e={}){const{search:a,sortField:t,sortDirection:n,page:i,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:s="desc",page:r=1,limit:n=25,...i}=e;return{search:a,sortField:t,sortDirection:s,page:r,limit:n,additionalFilters:i}})(e),{query:p}=u(a,t,n,c),h=((e,a,t)=>{const s=(a-1)*t,r=s+t-1;return e.range(s,r)})(p,i,o),{data:x,error:f,count:g}=await h;if(f)throw new Error(`Error fetching ${r}: ${f.message}`);let b=((e,a,t,s)=>{const r=Math.ceil((a||0)/s);return{data:e,currentPage:t,totalPages:r,totalItems:a||0,itemsPerPage:s,hasNextPage:t<r,hasPreviousPage:t>1}})(x||[],g,i,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=kt(s.userIdFields,s.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,n,i,o);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await c().select(i||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${r}: ${t.message}`);return a},async create(e){const a=pe(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:s,error:n}=await c().insert(t).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,a){const t={...pe(a),updated_at:(new Date).toISOString()},{data:s,error:n}=await c().update(t).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 a={is_removed:!0,updated_at:(new Date).toISOString()},{error:t}=await c().update(a).eq("id",e);if(t)throw new Error(`Error soft deleting ${r}: ${t.message}`)}}}const Pt=()=>{Ka.clearManualLogout()},_t=e=>e?.placeId||null,Rt=e=>e?.placeName||null,Ft=e=>({placeId:_t(e),placeName:Rt(e)}),Dt=class{static async initialize(){try{if(!Ka.hasAllTokens()||!Ka.areAllTokensValid())return Ka.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 a=Ka.getAccessToken(),t=Ka.getIdToken();Pt();const s=this.extractUserFromIdToken(t),r=this.extractCompaniesFromIdToken(t),n=this.extractAliasFromAccessToken(a),i=Ka.extractTokenData(),o=i?.alias;let l=null;if(o&&r.some(e=>e.alias===o))l=o;else{const e=Ka.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);l=a?e:n||r[0]?.alias||null}!Ka.isSupabaseTokenValid()&&l&&await lt.attemptRegeneration();let d=null;if(l){const e=Ka.getCompanyId(l),a=r.find(e=>e.alias===l);a&&(d={id:e||a.id,name:a.name,alias:a.alias})}let c=null,u=null;if(s?.id&&l){const a=Ka.getCompanyId(l);if(a)try{const e=(await ht.fetchActiveUsersMap(l,a)).get(s.id);if(e){const a=Ft(e);c=a.placeId,u=a.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=rt(),{data:a,error:t}=await e.functions.invoke("dev-tokens",{body:{environment:"development"}});if(t)return!1;if(!a?.access_token||!a?.id_token)return!1;const s=new URL("/callback",window.location.origin);return s.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=s.toString(),!0}catch(e){return!1}}static loginProd(){const e=Ka.generateOAuthState();Ka.setOAuthState(e);const a=Ka.generateOAuthNonce();Ka.setOAuthNonce(a);const t=`${window.location.origin}/callback`,s=new URL(xt.oauth.authUrl);s.searchParams.set("client_id",xt.oauth.clientId),s.searchParams.set("response_type",xt.oauth.responseType),s.searchParams.set("scope",xt.oauth.scope),s.searchParams.set("redirect_uri",t),s.searchParams.set("state",e),s.searchParams.set("nonce",a),s.searchParams.set("response_mode","fragment"),bt(),window.location.href=s.toString()}static async processCallback(){try{if(Ka.hasAllTokens()){if(!Ka.getValidSupabaseToken()){Ka.getAccessToken();await lt.attemptRegeneration()}return!0}const e=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash),a=new URLSearchParams(window.location.search),t=t=>e.get(t)||a.get(t),s=t("access_token"),r=t("id_token"),n=t("error");if(n)throw new Error(`Erro OAuth: ${n}`);if(!s||!r)throw new Error("Tokens não encontrados na URL de callback");Ka.setAccessToken(s),Ka.setIdToken(r),Pt();const i=this.extractAliasFromAccessToken(s);if(i)Ka.setSelectedAlias(i);else{const e=this.extractCompaniesFromIdToken(r);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ka.setSelectedAlias(e[0].alias)}if(!await lt.attemptRegeneration())throw new Error("Falha ao gerar token Supabase");return Ka.clearOAuthState(),Ka.clearOAuthNonce(),!0}catch(e){throw e}}static logout(){Ka.setManualLogout(),Ka.clearAll(),window.location.href="/login"}static decodeToken(e){return Ua.parseJwtPayload(e)}static extractUserFromIdToken(e){const a=this.decodeToken(e);return a?{id:a.subNewId,email:a.email,name:a.name,identifier:a.identifier}:null}static extractCompaniesFromIdToken(e){const a=this.decodeToken(e);if(!a)return[];const t=[];return Object.keys(a).forEach(e=>{if(e.match(/^co(\d+)$/)&&"string"==typeof a[e]){const s=a[e].split(";");if(s.length>=4)t.push({id:s.length>7?s[7].trim():"",alias:s[0].trim(),name:s[3].trim()});else{const[s,r]=a[e].split("|");s&&r&&t.push({id:"",alias:s.trim(),name:r.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}};lt.setLogoutCallback(()=>{Dt.logout()});let Mt=Dt;const Lt=a.createContext(void 0),zt=()=>{const e=a.useContext(Lt);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Ot({queryKey:e,service:t,entityName:s,searchFields:r,additionalFilters:n={},onSuccess:i}){const[l,d]=b.useSearchParams(),c=g.useQueryClient(),{alias:u,userId:m}=zt(),p=a.useCallback(a=>{const t=`${e}_${a}`,s=l.get(t);return s||(l.get(a)||"")},[l,e]),h=p("search"),x=p("sortField")||ft.sorting.defaultField,f=p("sortDirection")||ft.sorting.defaultDirection,v=parseInt(p("page")||"1"),N=parseInt(p("limit")||String(ft.pagination.defaultPageSize)),j=h,y=a.useMemo(()=>({search:j,sortField:x,sortDirection:f,page:v,limit:N,...n}),[j,x,f,v,N,n]),w=a.useCallback(()=>t.getAll(y),[t,y]),C=g.useQuery({queryKey:[e,u,m,y],queryFn:w});if(!C)throw new Error(`useCrud: Query initialization failed for "${s}". Ensure QueryClientProvider is configured in your app root.`);const k=g.useMutation({mutationFn:t.create,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(jt.success.created(s)),i?.()},onError:e=>{o.toast.error(`${jt.error.create(s)}: ${e.message}`)}}),S=g.useMutation({mutationFn:({id:e,data:a})=>t.update(e,a),onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(jt.success.updated(s)),i?.()},onError:e=>{o.toast.error(`${jt.error.update(s)}: ${e.message}`)}}),E=g.useMutation({mutationFn:t.delete,onSuccess:()=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(jt.success.deleted(s))},onError:e=>{o.toast.error(`${jt.error.delete(s)}: ${e.message}`)}}),A=a.useCallback(a=>{const t={...Object.fromEntries(l)};Object.entries(a).forEach(([a,s])=>{const r=`${e}_${a}`;""===s||0===s?delete t[r]:t[r]=String(s)}),delete t.sortField,delete t.sortDirection,d(t)},[l,d,e]),T=a.useCallback(e=>{A({search:e,page:1})},[A]),I=a.useCallback(e=>{A({sortField:e,sortDirection:x===e&&"asc"===f?"desc":"asc",page:1})},[x,f,A]),P=a.useCallback(e=>{A({page:e})},[A]),_=a.useCallback(e=>{A({limit:e,page:1})},[A]),R=a.useCallback(()=>{const a=Object.fromEntries(l),t=`${e}_`,s=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));d(s)},[d,l,e]),[F,D]=a.useState([]),M=a.useCallback(e=>{D(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),L=a.useCallback(()=>{const e=C?.data?.data.map(e=>e.id)||[];D(a=>a.length===e.length?[]:e)},[C?.data?.data]),z=a.useCallback(()=>{D([])},[]),O=a.useMemo(()=>{const e=C?.data?.data.map(e=>e.id)||[];return e.length>0&&F.length===e.length},[F,C?.data?.data]),U=g.useMutation({mutationFn:async e=>{await Promise.all(e.map(e=>t.delete(e)))},onSuccess:(a,t)=>{c.invalidateQueries({queryKey:[e]}),o.toast.success(`${t.length} ${s}(s) deletado(s) com sucesso`),z()},onError:e=>{o.toast.error(`Erro ao deletar itens: ${e.message}`)}}),$=a.useCallback((e,a)=>{const t=a?a(e):e;e.id?S.mutate({id:e.id,data:t}):k.mutate({...t,alias:u})},[u,k,S]);return{entities:C?.data?.data||[],pagination:{currentPage:C?.data?.currentPage||1,totalPages:C?.data?.totalPages||1,totalItems:C?.data?.totalItems||0,itemsPerPage:C?.data?.itemsPerPage||ft.pagination.defaultPageSize,hasNextPage:C?.data?.hasNextPage||!1,hasPreviousPage:C?.data?.hasPreviousPage||!1},isLoading:C?.isLoading??!0,isCreating:k?.isPending??!1,isUpdating:S?.isPending??!1,isDeleting:E?.isPending??!1,error:C?.error||null,searchTerm:h,sortField:x,sortDirection:f,currentPage:v,itemsPerPage:N,queryKey:e,createEntity:k.mutate,updateEntity:(e,a)=>S.mutate({id:e,data:a}),deleteEntity:E.mutate,save:$,handleSearch:T,handleSort:I,handlePageChange:P,handleItemsPerPageChange:_,clearFilters:R,refetch:C.refetch,selectedIds:F,selectItem:M,selectAll:L,clearSelection:z,isAllSelected:O,bulkDelete:U.mutate,isBulkDeleting:U.isPending}}const Ut=G.Root,$t=G.Trigger,qt=G.Portal,Vt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Overlay,{className:me("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",a),...t,ref:s}));Vt.displayName=G.Overlay.displayName;const Bt=q.forwardRef(({className:a,...t},s)=>e.jsxs(qt,{children:[e.jsx(Vt,{}),e.jsx(G.Content,{ref:s,className:me("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...t})]}));Bt.displayName=G.Content.displayName;const Wt=({className:a,...t})=>e.jsx("div",{className:me("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",a),...t});Wt.displayName="AlertDialogHeader";const Ht=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});Ht.displayName="AlertDialogFooter";const Qt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Title,{ref:s,className:me("text-lg font-semibold",a),...t}));Qt.displayName=G.Title.displayName;const Kt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Description,{ref:s,className:me("text-sm text-muted-foreground",a),...t}));Kt.displayName=G.Description.displayName;const Gt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Action,{ref:s,className:me(he(),a),...t}));Gt.displayName=G.Action.displayName;const Xt=q.forwardRef(({className:a,...t},s)=>e.jsx(G.Cancel,{ref:s,className:me(he({variant:"outline"}),"mt-2 sm:mt-0",a),...t}));Xt.displayName=G.Cancel.displayName;const Jt=({open:t,onOpenChange:s,item:r,onConfirm:n,entityName:i="item",isDeleting:o=!1,isBulk:l=!1,bulkCount:d})=>{const[c,u]=a.useState("");a.useEffect(()=>{t||u("")},[t]);const m=()=>{u(""),s(!1)},p=l?c===d?.toString():c===r?.title;return r?e.jsx(Ut,{open:t,onOpenChange:m,children:e.jsxs(Bt,{className:"sm:max-w-[500px]",children:[e.jsx(Wt,{children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx("div",{className:"flex-shrink-0 w-8 h-8 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx("span",{className:"text-destructive font-semibold text-sm",children:"!"})}),e.jsx("div",{className:"flex-1",children:e.jsx(Qt,{className:"text-lg font-semibold",children:"Confirmar Exclusão"})})]})}),e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"mb-2",children:l?e.jsx(e.Fragment,{children:"Você está prestes a excluir permanentemente:"}):e.jsxs(e.Fragment,{children:["Você está prestes a excluir permanentemente o ",i,":"]})}),e.jsx("div",{className:"p-3 bg-muted rounded-md border-l-4 border-l-destructive",children:e.jsx("p",{className:"font-medium text-foreground",children:l?`${r.title}`:r.title})})]}),e.jsx("div",{className:"bg-orange-50 border border-orange-200 rounded-md p-3",children:e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx("div",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-orange-500 flex items-center justify-center mt-0.5",children:e.jsx("span",{className:"text-white font-bold text-xs",children:"!"})}),e.jsxs("div",{className:"text-sm text-orange-800",children:[e.jsx("p",{className:"font-medium mb-1",children:"Atenção!"}),e.jsx("p",{children:l?e.jsx(e.Fragment,{children:"Esta ação não pode ser desfeita. Os itens serão removidos permanentemente do sistema."}):e.jsxs(e.Fragment,{children:["Esta ação não pode ser desfeita. O ",i," será removido permanentemente do sistema."]})})]})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"confirmation",className:"text-sm font-medium",children:l?e.jsxs(e.Fragment,{children:["Para confirmar, digite o número de itens que serão removidos: ",e.jsx("strong",{children:d})]}):e.jsxs(e.Fragment,{children:["Para confirmar, digite ",e.jsxs("strong",{children:['"',r.title,'"']})," abaixo:"]})}),e.jsx(ge,{id:"confirmation",type:l?"number":"text",value:c,onChange:e=>u(e.target.value),placeholder:l?`Digite: ${d}`:`Digite: ${r.title}`,className:"w-full"})]})]})}),e.jsxs(Ht,{children:[e.jsx(Xt,{onClick:m,children:"Cancelar"}),e.jsx(Gt,{onClick:()=>{if(!r)return;(l?c===d?.toString():c===r.title)&&(n(r),u(""),s(!1))},disabled:!p||o,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground",children:o?"Removendo...":`Excluir ${i}`})]})]})}):null},Yt=q.forwardRef(({className:a,...t},s)=>e.jsx("table",{ref:s,className:me("w-full caption-bottom text-sm",a),...t}));Yt.displayName="Table";const Zt=q.forwardRef(({className:a,...t},s)=>e.jsx("thead",{ref:s,className:me("[&_tr]:border-b sticky top-0 z-[1] bg-background",a),...t}));Zt.displayName="TableHeader";const es=q.forwardRef(({className:a,...t},s)=>e.jsx("tbody",{ref:s,className:me("[&_tr:last-child]:border-0",a),...t}));es.displayName="TableBody";const as=q.forwardRef(({className:a,...t},s)=>e.jsx("tfoot",{ref:s,className:me("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...t}));as.displayName="TableFooter";const ts=q.forwardRef(({className:a,...t},s)=>e.jsx("tr",{ref:s,className:me("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted odd:bg-muted/50",a),...t}));ts.displayName="TableRow";const ss=q.forwardRef(({className:a,...t},s)=>e.jsx("th",{ref:s,className:me("h-12 px-4 py-3 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",a),...t}));ss.displayName="TableHead";const rs=q.forwardRef(({className:a,...t},s)=>e.jsx("td",{ref:s,className:me("px-4 py-3 align-middle [&:has([role=checkbox])]:pr-0",a),...t}));rs.displayName="TableCell";const ns=q.forwardRef(({className:a,...t},s)=>e.jsx("caption",{ref:s,className:me("mt-4 text-sm text-muted-foreground",a),...t}));function is({rows:a=5,columns:t=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:t}).map((a,t)=>e.jsx(Da,{className:"h-4 w-24"},t))})}),e.jsx("div",{children:Array.from({length:a}).map((a,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:t}).map((a,t)=>e.jsx(Da,{className:"h-4 w-20"},t))})},s))})]})})}function os({count:a=3}){return e.jsx("div",{className:"space-y-4",children:Array.from({length:a}).map((a,t)=>e.jsxs(Ne,{children:[e.jsxs(je,{children:[e.jsx(Da,{className:"h-4 w-3/4"}),e.jsx(Da,{className:"h-3 w-1/2"})]}),e.jsx(Ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Da,{className:"h-3 w-full"}),e.jsx(Da,{className:"h-3 w-2/3"})]})})]},t))})}ns.displayName="TableCaption";const ls={default:l.FileX,search:l.Search,error:l.AlertCircle};function ds({icon:a,title:t,description:s,action:r,className:n,variant:i="default"}){const o=a?()=>a:ls[i];return e.jsxs("div",{className:me("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:t}),s&&e.jsx("p",{className:"text-muted-foreground mb-6 max-w-sm",children:s}),r&&e.jsx(xe,{onClick:r.onClick,variant:"outline",children:r.label})]})}const cs=X.Root,us=X.Trigger,ms=X.Group,ps=X.Portal,hs=X.Sub,xs=X.RadioGroup,fs=q.forwardRef(({className:a,inset:t,children:s,...r},n)=>e.jsxs(X.SubTrigger,{ref:n,className:me("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",t&&"pl-8",a),...r,children:[s,e.jsx(l.ChevronRight,{className:"ml-auto h-4 w-4"})]}));fs.displayName=X.SubTrigger.displayName;const gs=q.forwardRef(({className:a,...t},s)=>e.jsx(X.SubContent,{ref:s,className:me("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",a),...t}));gs.displayName=X.SubContent.displayName;const bs=q.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(X.Portal,{children:e.jsx(X.Content,{ref:r,sideOffset:t,className:me("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",a),...s})}));bs.displayName=X.Content.displayName;const vs=q.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(X.Item,{ref:r,className:me("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",t&&"pl-8",a),...s}));vs.displayName=X.Item.displayName;const Ns=q.forwardRef(({className:a,children:t,checked:s,...r},n)=>e.jsxs(X.CheckboxItem,{ref:n,className:me("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:s,...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"})})}),t]}));Ns.displayName=X.CheckboxItem.displayName;const js=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(X.RadioItem,{ref:r,className:me("relative flex cursor-default select-none items-center py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...s,children:[e.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"})})}),t]}));js.displayName=X.RadioItem.displayName;const ys=q.forwardRef(({className:a,inset:t,...s},r)=>e.jsx(X.Label,{ref:r,className:me("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",a),...s}));ys.displayName=X.Label.displayName;const ws=q.forwardRef(({className:a,...t},s)=>e.jsx(X.Separator,{ref:s,className:me("-mx-1 my-1 h-px bg-muted",a),...t}));ws.displayName=X.Separator.displayName;const Cs=({className:a,...t})=>e.jsx("span",{className:me("ml-auto text-xs tracking-widest opacity-60",a),...t});Cs.displayName="DropdownMenuShortcut";const ks=({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canDelete:n=!0,customActions:i=[],renderAs:o})=>{const d=[];if(a){const e={icon:l.Edit,label:"Editar",onClick:a};d.push(e)}if(i.forEach(e=>{d.push(e)}),s){const e={icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s};d.push(e)}if(n&&t){const e={icon:l.Trash2,label:"Remover",onClick:t,destructive:!0};d.push(e)}return"dropdown"===o?e.jsx(e.Fragment,{children:d.map((a,t)=>e.jsxs(vs,{onClick:a.onClick,className:a.destructive?"text-destructive":"",children:[e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},t))}):e.jsx(e.Fragment,{children:d.map((a,t)=>e.jsxs(xe,{variant:"ghost",size:"sm",onClick:a.onClick,className:"w-full justify-start px-2 py-1.5 text-sm font-normal h-7 "+(a.destructive?"text-destructive hover:text-destructive":""),children:[e.jsx(a.icon,{className:"h-4 w-4 mr-2"}),a.label]},t))})},Ss=({onEdit:a,onDelete:t,canDelete:s=!0,onToggleStatus:r,isActive:n=!0,customActions:i=[]})=>e.jsxs(cs,{children:[e.jsx(us,{asChild:!0,children:e.jsx(xe,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:e.jsx(l.EllipsisVertical,{size:12})})}),e.jsx(bs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:e.jsx(ks,{onEdit:e=>{e?.stopPropagation(),a?.()},onDelete:e=>{e?.stopPropagation(),t?.()},onToggleStatus:e=>{e?.stopPropagation(),r?.()},isActive:n,canDelete:s,customActions:i,renderAs:"dropdown"})})]}),Es=({contextMenu:t,onClose:s,onEdit:r,onDelete:n,onToggleStatus:i,customActions:o})=>(a.useEffect(()=>{const e=()=>s();if(t)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[t,s]),t?e.jsx("div",{className:"fixed bg-background border border-border rounded-md shadow-lg py-1 z-50 min-w-[120px]",style:{left:t.x,top:t.y},onClick:e=>e.stopPropagation(),children:e.jsx(ks,{onEdit:r?()=>{r(t.item),s()}:void 0,onDelete:n?()=>{n(t.item),s()}:void 0,onToggleStatus:i?()=>{i(t.item),s()}:void 0,isActive:t.item.is_actived,canDelete:!!n,customActions:o?o(t.item):[],renderAs:"context"})}):null),As=a.memo(({checked:a,onCheckedChange:t})=>e.jsx(aa,{checked:a,onCheckedChange:t}),(e,a)=>e.checked===a.checked),Ts=({manager:t,columns:s,onEdit:r,onView:n,onToggleStatus:i,onDelete:o,renderActions:d,customRowActions:c,enableBulkActions:u=!1})=>{const[m,p]=a.useState(!1),[h,x]=a.useState(null);a.useEffect(()=>{const e=()=>p(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),a.useEffect(()=>{const e=()=>x(null);if(h)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[h]);const f=a.useMemo(()=>(()=>{s.length;let e=0;const a=s.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,s=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:s,isFixed:!1}}});return e+=50,a.map(e=>e.isFixed?{...e,style:{width:`${e.calculatedWidth}px`}}:{...e,style:{minWidth:`${e.calculatedWidth}px`,width:`${e.calculatedWidth}px`}})})(),[s]);return m?t.isLoading?e.jsx(os,{count:3}):0===t.entities.length?e.jsx(ds,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"}):e.jsxs("div",{className:"space-y-4",children:[t.entities.map(a=>e.jsx(Ne,{className:me("overflow-hidden cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),x({x:e.clientX,y:e.clientY,item:a})},children:e.jsx(Ce,{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(As,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),e.jsxs("div",{className:"flex-1",children:[s.map(t=>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:[t.header,":"]}),e.jsx("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:t.render?t.render(a):String(a[t.key]??"")})]},String(t.key))),(r||n||d)&&e.jsx("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:d?d(a):e.jsx(Ss,{onEdit:r?()=>{r(a)}:void 0,onDelete:o?()=>o(a):void 0,onToggleStatus:i?()=>i(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]})]})})},a.id)),e.jsx(Es,{contextMenu:h,onClose:()=>x(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:c})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[t.isLoading?e.jsx(is,{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(Yt,{className:"table-auto",children:[e.jsxs("colgroup",{children:[u&&e.jsx("col",{style:{width:"50px"}}),f.map((a,t)=>e.jsx("col",{style:a.style},t)),e.jsx("col",{style:{width:"50px"}})]}),e.jsx(Zt,{children:e.jsxs(ts,{children:[u&&e.jsx(ss,{className:"w-[50px]",children:e.jsx(As,{checked:t.isAllSelected,onCheckedChange:t.selectAll})}),s.map(a=>{return e.jsx(ss,{className:`${a.className||""} ${a.sortable?"cursor-pointer hover:bg-muted/50":""}`,onClick:a.sortable?()=>t.handleSort(String(a.key)):void 0,children:e.jsxs("div",{className:"flex items-center "+(a.className?.includes("text-center")?"justify-center":""),children:[a.header,a.sortable&&(s=String(a.key),t.sortField!==s?e.jsx(l.ArrowUpDown,{size:14,className:"ml-1 opacity-50"}):"asc"===t.sortDirection?e.jsx(l.ArrowUp,{size:14,className:"ml-1"}):e.jsx(l.ArrowDown,{size:14,className:"ml-1"}))]})},String(a.key));var s}),e.jsx(ss,{className:"w-[50px] text-center",children:"Ações"})]})}),e.jsx(es,{children:0===t.entities.length?e.jsx(ts,{children:e.jsx(rs,{colSpan:u?s.length+2:s.length+1,className:"h-32",children:e.jsx(ds,{title:"Nenhum item encontrado",description:"Não há dados para exibir no momento.",variant:"search"})})}):t.entities.map(a=>e.jsxs(ts,{className:me("cursor-pointer hover:bg-muted/50",u&&t.selectedIds.includes(a.id)&&"bg-muted"),onClick:e=>{e.stopPropagation(),u?t.selectItem(a.id):r?.(a)},onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),x({x:e.clientX,y:e.clientY,item:a})},children:[u&&e.jsx(rs,{onClick:e=>e.stopPropagation(),children:e.jsx(As,{checked:t.selectedIds.includes(a.id),onCheckedChange:()=>t.selectItem(a.id)})}),s.map(t=>e.jsx(rs,{className:t.className,children:t.render?t.render(a):String(a[t.key]??"")},String(t.key))),e.jsx(rs,{className:"text-center",children:d?d(a):e.jsx(Ss,{onEdit:r?()=>r(a):void 0,onDelete:o?()=>o(a):void 0,onToggleStatus:i?()=>i(a):void 0,isActive:a.is_actived,customActions:c?c(a):[]})})]},a.id))})]})})}),e.jsx(Es,{contextMenu:h,onClose:()=>x(null),onEdit:r,onDelete:o,onToggleStatus:i,customActions:c})]})};function Is(e,t,s,r){const[n,i]=a.useState({}),[o,l]=a.useState({}),d=a.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,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return u(e)}},p=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.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(a,t);if(e)return e}catch(s){}}};a.useEffect(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},a=e(d),n={};a.forEach(e=>{let a;if(t&&void 0!==t[e.name]){if(a=t[e.name],null==a&&(a=""),"date"===e.type&&a)if("string"==typeof a){const e=new Date(a);c(e)&&(a=e.toISOString().split("T")[0])}else c(a)&&(a=a.toISOString().split("T")[0])}else a=u(e);n[e.name]=a}),a.forEach(e=>{const a=m(e,n);void 0!==a&&(n[e.name]=a)}),t&&Object.keys(t).forEach(e=>{a.find(a=>a.name===e)||void 0===t[e]||(n[e]=t[e])}),i(n),l({}),s&&s(n)},[d,t,s,r]);const h=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...h(e.fields))}),a},x=()=>{const e=h(d),a={};return e.forEach(e=>{const t=p(e,n[e.name],n);t&&(a[e.name]=t)}),l(a),0===Object.keys(a).length};return{formData:n,errors:o,updateField:(e,a)=>{i(t=>{const r={...t,[e]:a},n=((e,a)=>{let t={...a};const s=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...s(e.fields))}),a};return s(d).filter(a=>a.dependsOn===e).forEach(e=>{const a=m(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,r);return s&&s(n),n}),o[e]&&l(a=>{const t={...a};return delete t[e],t});const t=h(d).find(a=>a.name===e);if(t){const s=p(t,a,n);s&&l(a=>({...a,[e]:s}))}},validateForm:x,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),x()&&e(n)}}}const Ps=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],_s=({value:a="#3b82f6",onChange:t,label:s})=>e.jsxs("div",{className:"space-y-2",children:[s&&e.jsx(ve,{children:s}),e.jsxs(Ca,{children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{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:a}}),a]})}),e.jsx(Sa,{className:"w-64",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ve,{htmlFor:"color-input",children:"Cor personalizada"}),e.jsx(ge,{id:"color-input",type:"color",value:a,onChange:e=>t?.(e.target.value),className:"h-10 w-full"})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Cores predefinidas"}),e.jsx("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ps.map(a=>e.jsx("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:a},onClick:()=>t?.(a),"aria-label":`Selecionar cor ${a}`},a))})]})]})})]})]}),Rs=q.forwardRef(({className:a,children:t,...s},r)=>e.jsxs(J.Root,{ref:r,className:me("relative overflow-hidden",a),...s,children:[e.jsx(J.Viewport,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Fs,{}),e.jsx(J.Corner,{})]}));Rs.displayName=J.Root.displayName;const Fs=q.forwardRef(({className:a,orientation:t="vertical",...s},r)=>e.jsx(J.ScrollAreaScrollbar,{ref:r,orientation:t,className:me("flex touch-none select-none transition-colors","vertical"===t&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===t&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...s,children:e.jsx(J.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Fs.displayName=J.ScrollAreaScrollbar.displayName;const Ds={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},Ms=({value:t="Star",onChange:s,label:r})=>{const[n,i]=a.useState(""),o=Object.entries(Ds).filter(([e])=>e.toLowerCase().includes(n.toLowerCase())),d=Ds[t]||l.Star;return e.jsxs("div",{className:"space-y-2",children:[r&&e.jsx(ve,{children:r}),e.jsxs(Ca,{children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[e.jsx(d,{className:"h-4 w-4 mr-2"}),t]})}),e.jsx(Sa,{className:"w-80",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ve,{htmlFor:"icon-search",children:"Buscar ícone"}),e.jsx(ge,{id:"icon-search",placeholder:"Digite o nome do ícone...",value:n,onChange:e=>i(e.target.value)})]}),e.jsx(Rs,{className:"h-48",children:e.jsx("div",{className:"grid grid-cols-6 gap-2",children:o.map(([a,r])=>e.jsx("button",{className:"p-2 rounded border-2 hover:border-primary "+(t===a?"border-primary bg-primary/10":"border-border"),onClick:()=>s?.(a),title:a,children:e.jsx(r,{className:"h-4 w-4"})},a))})})]})})]})]})};function Ls({items:a,getItemValue:t,getItemLabel:s,...r}){const n=r.error?"string"==typeof r.error?r.error:!(r.error instanceof Error)||r.error.message:void 0,i={...r,multiple:!1,options:a,getOptionValue:t,getOptionLabel:s,error:n};return e.jsx(za,{...i})}const zs=(e={})=>{const{user:a,alias:t}=zt(),{enabled:s=!1}=e;return g.useQuery({queryKey:["qualiex-users",t],queryFn:()=>ht.getUsers(t),enabled:s&&!!t&&!!a,retry:2,retryDelay:1e3})},Os=({value:a="",onChange:t,placeholder:s="Selecionar usuário",disabled:r,className:n,enabled:i})=>{const{data:o=[],isLoading:l,error:d}=zs({enabled:i});return e.jsx(Ls,{value:a,onChange:t,items:o,isLoading:l,error:d,getItemValue:e=>e.userId,getItemLabel:e=>e.userName,placeholder:s,searchPlaceholder:"Buscar usuário...",emptyMessage:"Nenhum usuário disponível",disabled:r,className:n})};function Us({title:t,sections:s,initialData:r,onSubmit:n,onCancel:i,open:o,submitButtonText:l="Salvar",isLoading:d=!1,usersData:c}){const[u,m]=a.useState(s?.[0]?.id||""),p=a.useRef(null),[h,x]=a.useState(null),f=a.useCallback(e=>{p.current=e,x(e)},[]),g=a.useMemo(()=>s&&Array.isArray(s)?s.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[s]),{formData:b,errors:v,updateField:N,handleSubmit:j}=Is(g,r,void 0,o),y=a.useMemo(()=>s&&Array.isArray(s)?s.map(e=>({...e,disabled:e.condition?!e.condition(b):e.disabled||!1})):[],[s,b]),w=a.useMemo(()=>{const e=y.find(e=>e.id===u);if(e&&!e.disabled)return u;const a=y.find(e=>!e.disabled);return a?.id||u},[y,u]);a.useEffect(()=>{w!==u&&m(w)},[w,u]);const C=y.find(e=>e.id===w),k=a=>{const t=(a.computedValue,b[a.name]),s=void 0!==t?t:"",r=v[a.name];switch(a.type){case"group":return e.jsxs("div",{className:"space-y-2",children:[a.label,e.jsx("div",{className:a.className||("horizontal"===a.layout?"flex gap-3":"space-y-3"),children:a.fields?.map(e=>k(e))})]},a.name);case"user-select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(Os,{value:s||"",onChange:e=>N(a.name,e),placeholder:a.placeholder,disabled:a.disabled,className:r?"border-red-500":""}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"textarea":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ta,{id:a.name,value:s||"",onChange:e=>{N(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"select":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsxs(We,{value:String(s),onValueChange:e=>{N(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,children:[e.jsx(Ke,{className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,children:e.jsx(Qe,{placeholder:a.placeholder})}),e.jsx(Je,{children:a.options?.map(a=>e.jsx(Ze,{value:a.value,children:a.label},a.value))})]}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"multiselect":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsxs(ve,{htmlFor:a.name,children:[a.label,a.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx(za,{options:a.options||[],value:Array.isArray(s)?s:[],onChange:e=>N(a.name,e),placeholder:a.placeholder,disabled:a.disabled,error:r,popoverContainer:h,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"date":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"date",value:String(s),onChange:e=>N(a.name,e.target.value),placeholder:a.placeholder,disabled:a.disabled,className:me("w-full",r?"border-red-500":"",a.disabled?"bg-gray-100 cursor-not-allowed":"")}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"color":return e.jsxs("div",{children:[e.jsxs(ve,{htmlFor:a.name,children:[a.label," ",a.required&&e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(ge,{id:a.name,type:"color",value:s||a.defaultValue||"#000000",onChange:e=>N(a.name,e.target.value),className:"h-10"}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"color-picker":return e.jsxs("div",{children:[e.jsx(_s,{label:`${a.label} ${a.required?"*":""}`,value:s||a.defaultValue||"#3b82f6",onChange:e=>N(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"icon-picker":return e.jsxs("div",{children:[e.jsx(Ms,{label:`${a.label} ${a.required?"*":""}`,value:s||a.defaultValue||"Star",onChange:e=>N(a.name,e)}),r&&e.jsx("p",{className:"text-sm text-destructive mt-1",children:r})]},a.name);case"custom":if(!a.component)return null;const t=a.component;return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[a.label&&e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(t,{value:s,onChange:e=>{N(a.name,e),a.onValueChange&&a.onValueChange(e)},disabled:a.disabled,error:r,popoverContainer:h,...a.componentProps||{}}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);case"number":return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"number",value:null!=s?String(s):"",onChange:e=>{const t=e.target.value,s=""===t?null:Number(t);N(a.name,s)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,min:a.min,step:a.step||"1"}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name);default:return e.jsxs("div",{className:`space-y-2 ${a.className||""}`,children:[e.jsx(ve,{htmlFor:a.name,children:a.label}),e.jsx(ge,{id:a.name,type:"text",value:s||"",onChange:e=>{N(a.name,e.target.value)},placeholder:a.placeholder,disabled:a.disabled,className:`${r?"border-red-500":""} ${a.disabled?"bg-gray-100 cursor-not-allowed":""}`,readOnly:a.disabled}),r&&e.jsx("p",{className:"text-sm text-red-500",children:r})]},a.name)}},S=a.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 a=C.component;return e.jsx(a,{formData:b,updateField:N,errors:v,users:c,disabled:C.disabled})}return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:C.fields.map(k)})},[C,b,N,v,c,k]),E=e.jsxs("div",{className:"flex flex-col max-h-[80vh]",children:[y.length>1&&e.jsx("div",{className:"flex-shrink-0 p-4 border-b",children:e.jsx("div",{className:"flex space-x-2",children:y.map(a=>e.jsx(xe,{variant:w===a.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=y.find(a=>a.id===e);a&&!a.disabled&&m(e)})(a.id),disabled:a.disabled,className:a.disabled?"opacity-50 cursor-not-allowed":"",children:a.title},a.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:"Carregando dados..."})}):e.jsxs("form",{onSubmit:j(n),className:"space-y-3 md:space-y-4",children:[S(),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(xe,{type:"button",variant:"outline",onClick:i,children:"Cancelar"}),e.jsx(xe,{type:"submit",disabled:d,children:l})]})]})})]});return e.jsx(Se,{open:o,onOpenChange:e=>{!1===e&&!0===o&&i()},children:e.jsxs(Pe,{ref:f,className:"max-w-4xl max-h-[90vh] overflow-visible",children:[e.jsxs(_e,{className:"bg-primary text-primary-foreground px-6 py-4 -mx-6 -mt-6 mb-4",children:[e.jsx(Fe,{className:"text-white",children:t}),e.jsx(De,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),E]})})}function $s({currentPage:a,totalPages:t,totalItems:s,itemsPerPage:r,onPageChange:n,onItemsPerPageChange:i,variant:o="full"}){const d=(a-1)*r+1,c=Math.min(a*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(We,{value:String(r),onValueChange:e=>i(Number(e)),children:[e.jsx(Ke,{className:"h-8 w-[70px]",children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"10",children:"10"}),e.jsx(Ze,{value:"25",children:"25"}),e.jsx(Ze,{value:"50",children:"50"}),e.jsx(Ze,{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(xe,{variant:"outline",size:"sm",onClick:()=>n(1),disabled:1===a,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsLeft,{size:16})}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(a-1),disabled:1===a,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:a}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"de"}),e.jsx("span",{className:"text-sm font-medium",children:t})]}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(a+1),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronRight,{size:16})}),e.jsx(xe,{variant:"outline",size:"sm",onClick:()=>n(t),disabled:a===t,className:"h-8 w-8 p-0",children:e.jsx(l.ChevronsRight,{size:16})})]})]})}function qs({manager:a}){return e.jsx($s,{currentPage:a.pagination.currentPage,totalPages:a.pagination.totalPages,totalItems:a.pagination.totalItems,itemsPerPage:a.pagination.itemsPerPage,onPageChange:a.handlePageChange,onItemsPerPageChange:a.handleItemsPerPageChange,variant:"full"})}const Vs=({selectedCount:a,onClearSelection:t,onBulkDelete:s,customActions:r=[],isLoading:n=!1})=>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.jsxs("span",{className:"text-sm font-medium",children:[a," ",1===a?"item selecionado":"itens selecionados"]}),e.jsxs(xe,{variant:"ghost",size:"sm",onClick:t,className:"h-7 px-2",children:[e.jsx(l.X,{size:14,className:"mr-1"}),"Limpar"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.map((a,t)=>{const s=a.icon;return e.jsxs(xe,{variant:a.variant||"outline",size:"sm",onClick:()=>a.action([]),disabled:n,className:"h-7",children:[s&&e.jsx(s,{size:14,className:"mr-1"}),a.label]},t)}),s&&e.jsxs(xe,{variant:"destructive",size:"sm",onClick:s,disabled:n,className:"h-7",children:[e.jsx(l.Trash2,{size:14,className:"mr-1"}),"Remover"]})]})]}),Bs={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Ws={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Hs={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Qs({children:a,direction:t="column",gap:s="md",align:r="stretch",justify:n="start",wrap:i=!1,className:o}){return e.jsx("div",{className:me("flex","column"===t?"flex-col":"flex-row",Bs[s],Ws[r],Hs[n],i&&"flex-wrap",o),children:a})}function Ks({manager:a,filters:t,inline:s=!1}){const{isSearchVisible:r}=zt(),n=a.searchTerm,i=e.jsxs(e.Fragment,{children:[t.some(e=>"search"===e.type)&&!r&&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(ge,{placeholder:"Buscar...",value:a.searchTerm,onChange:e=>a.handleSearch(e.target.value),className:"pl-10"})]}),t.filter(e=>"select"===e.type&&e.options).map((a,t)=>e.jsxs("select",{value:a.value||"",onChange:e=>a.onChange?.(e.target.value),className:"h-10 px-3 rounded-md border border-input bg-background text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",children:[a.placeholder&&e.jsx("option",{value:"",children:a.placeholder}),a.options.map(a=>e.jsx("option",{value:a.value,children:a.label},a.value))]},`select-${t}`)),t.filter(e=>"custom"===e.type&&e.component).map((a,t)=>{const r=a.component;return e.jsx("div",{className:s?"":"w-full sm:w-auto",children:e.jsx(r,{...a.props})},`custom-${t}`)}),n&&e.jsxs(xe,{variant:"outline",onClick:a.clearFilters,className:"whitespace-nowrap",children:[e.jsx(l.X,{className:"h-4 w-4 mr-2"}),"Limpar Filtros"]})]});return s?e.jsx("div",{className:"flex items-center gap-2",children:i}):e.jsx(Qs,{direction:"column",gap:"md",className:"mb-6",children:e.jsx(Qs,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:i})})}function Gs({manager:t,config:s,formSections:r,onSave:n,onToggleStatus:i,defaultSort:o}){t&&t.queryKey;const{setSearchVisible:d}=zt(),[c,u]=b.useSearchParams(),[m,p]=a.useState(!1),[h,x]=a.useState(null),[f,g]=a.useState({isOpen:!1,entityId:null,entityName:""}),[v,N]=a.useState({isOpen:!1,count:0});a.useEffect(()=>(d(!0),()=>{d(!1)}),[d]),a.useEffect(()=>{if(o&&t){const e=`${t.queryKey}_sortField`,a=`${t.queryKey}_sortDirection`;if(!c.has(e)&&!c.has(a)){const t=Object.fromEntries(c);t[e]=o.column,t[a]=o.direction,u(t)}}},[]);return e.jsxs("div",{className:"flex-1 flex flex-col h-full",children:[s.enableBulkActions&&t.selectedIds.length>0&&e.jsx(Vs,{selectedCount:t.selectedIds.length,onClearSelection:t.clearSelection,onBulkDelete:s.bulkActions&&s.bulkActions.length>0?void 0:()=>{N({isOpen:!0,count:t.selectedIds.length})},customActions:s.bulkActions,isLoading:t.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(xe,{onClick:()=>{s.onNew?s.onNew():(x(null),p(!0))},children:[e.jsx(l.Plus,{size:16,className:"mr-2"}),"Novo"]}),s.customActions?.map((a,t)=>e.jsxs(xe,{onClick:a.action,variant:a.variant||"outline",children:[a.icon&&e.jsx(a.icon,{size:16,className:"mr-2"}),a.label]},t))]}),s.filters&&s.filters.length>0&&e.jsx("div",{className:"flex items-center gap-2 flex-1 justify-end",children:e.jsx(Ks,{manager:t,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(t.entities,t)}):e.jsx(Ts,{manager:t,columns:s.columns,onEdit:e=>{s.onEdit?s.onEdit(e):(x(e),p(!0))},onDelete:e=>{g({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(qs,{manager:t})}),!s.useCustomRouting&&e.jsx(Us,{open:m,title:h?`Editar ${s.entityName}`:`Novo ${s.entityName}`,sections:r,initialData:h||void 0,onSubmit:e=>{n(e),p(!1),x(null)},onCancel:()=>{p(!1),x(null)},isLoading:t.isLoading,submitButtonText:h?"Atualizar":"Criar"}),e.jsx(Jt,{open:f.isOpen,onOpenChange:()=>{g({isOpen:!1,entityId:null,entityName:""})},onConfirm:e=>{f.entityId&&(t.deleteEntity(f.entityId),g({isOpen:!1,entityId:null,entityName:""}))},item:f.entityId?{id:f.entityId,title:f.entityName}:void 0,entityName:s.entityName,isDeleting:t.isDeleting}),e.jsx(Jt,{open:v.isOpen,onOpenChange:()=>N({isOpen:!1,count:0}),onConfirm:()=>(t.bulkDelete?.(t.selectedIds),void N({isOpen:!1,count:0})),item:{id:"bulk",title:`${v.count} ${1===v.count?s.entityName:s.entityNamePlural}`},entityName:s.entityNamePlural,isDeleting:t.isBulkDeleting,isBulk:!0,bulkCount:v.count})]})}function Xs(e,a,t={}){const s=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],r={key:e,header:Ys(e),label:Ys(e),...Js(e,t),sortable:!0,searchable:"string"==typeof t};s.push(r)}}),{title:e,columns:s,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Js(e,a){const t=e.toLowerCase();return t.includes("email")?{type:"email",required:!0}:t.includes("phone")||t.includes("tel")?{type:"tel"}:t.includes("description")||t.includes("content")||t.includes("notes")?{type:"textarea"}:t.includes("status")||t.includes("type")||t.includes("category")?{type:"select",options:[]}:"boolean"==typeof a?{type:"boolean"}:"number"==typeof a?{type:"number"}:a instanceof Date?{type:"date"}:{type:"text"}}function Ys(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Zs={user:{title:"Usuários",searchPlaceholder:"Buscar usuários...",enableDelete:!1},product:{title:"Produtos",searchPlaceholder:"Buscar produtos...",enableFilters:!0},order:{title:"Pedidos",searchPlaceholder:"Buscar pedidos...",enableCreate:!1},category:{title:"Categorias",searchPlaceholder:"Buscar categorias...",itemsPerPage:20}};const er=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"}}),ar=q.forwardRef(({className:a,variant:t,...s},r)=>e.jsx("div",{ref:r,role:"alert",className:me(er({variant:t}),a),...s}));ar.displayName="Alert";const tr=q.forwardRef(({className:a,...t},s)=>e.jsx("h5",{ref:s,className:me("mb-1 font-medium leading-none tracking-tight",a),...t}));tr.displayName="AlertTitle";const sr=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,className:me("text-sm [&_p]:leading-relaxed",a),...t}));sr.displayName="AlertDescription";const rr=a.createContext(void 0);function nr({children:t}){const[s,r]=a.useState({});return e.jsx(rr.Provider,{value:{metadata:s,setMetadata:r,clearMetadata:()=>r({})},children:t})}function ir(){const e=a.useContext(rr);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}const or=Y.Root,lr=q.forwardRef(({className:a,...t},s)=>e.jsx(Y.Item,{ref:s,className:me("border-b",a),...t}));lr.displayName="AccordionItem";const dr=q.forwardRef(({className:a,children:t,...s},r)=>e.jsx(Y.Header,{className:"flex",children:e.jsxs(Y.Trigger,{ref:r,className:me("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",a),...s,children:[t,e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));dr.displayName=Y.Trigger.displayName;const cr=q.forwardRef(({className:a,children:t,...s},r)=>e.jsx(Y.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:me("pb-4 pt-0",a),children:t})}));cr.displayName=Y.Content.displayName;const ur=Z.Root,mr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Root,{ref:s,className:me("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",a),...t}));mr.displayName=ee.Root.displayName;const pr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Image,{ref:s,className:me("aspect-square h-full w-full",a),...t}));pr.displayName=ee.Image.displayName;const hr=q.forwardRef(({className:a,...t},s)=>e.jsx(ee.Fallback,{ref:s,className:me("flex h-full w-full items-center justify-center rounded-full bg-muted",a),...t}));hr.displayName=ee.Fallback.displayName;const xr=q.forwardRef(({...a},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...a}));xr.displayName="Breadcrumb";const fr=q.forwardRef(({className:a,...t},s)=>e.jsx("ol",{ref:s,className:me("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",a),...t}));fr.displayName="BreadcrumbList";const gr=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:me("inline-flex items-center gap-1.5",a),...t}));gr.displayName="BreadcrumbItem";const br=q.forwardRef(({asChild:a,className:t,...s},r)=>{const n=a?q.Fragment:"a";return e.jsx(n,{ref:r,className:me("transition-colors hover:text-foreground",t),...s})});br.displayName="BreadcrumbLink";const vr=q.forwardRef(({className:a,...t},s)=>e.jsx("span",{ref:s,role:"link","aria-disabled":"true","aria-current":"page",className:me("font-normal text-foreground",a),...t}));vr.displayName="BreadcrumbPage";const Nr=({children:a,className:t,...s})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:me("[&>svg]:size-3.5",t),...s,children:a??e.jsx(l.ChevronRight,{})});Nr.displayName="BreadcrumbSeparator";const jr=({className:a,...t})=>e.jsxs("span",{role:"presentation","aria-hidden":"true",className:me("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More"})]});function yr(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}function wr(e){return(a,t)=>{let s;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,r=t?.width?String(t.width):a;s=e.formattingValues[r]||e.formattingValues[a]}else{const a=e.defaultWidth,r=t?.width?String(t.width):e.defaultWidth;s=e.values[r]||e.values[a]}return s[e.argumentCallback?e.argumentCallback(a):a]}}function Cr(e){return(a,t={})=>{const s=t.width,r=s&&e.matchPatterns[s]||e.matchPatterns[e.defaultMatchWidth],n=a.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,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(i)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(i));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(i.length)}}}jr.displayName="BreadcrumbEllipsis";const kr={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"}},Sr={date:yr({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:yr({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:yr({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Er={lastWeek:e=>{const a=e.getDay();return"'"+(0===a||6===a?"último":"última")+"' eeee 'às' p"},yesterday:"'ontem às' p",today:"'hoje às' p",tomorrow:"'amanhã às' p",nextWeek:"eeee 'às' p",other:"P"},Ar={ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:wr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:wr({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:wr({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:wr({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:wr({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"})},Tr={ordinalNumber:(Ir={matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)},(e,a={})=>{const t=e.match(Ir.matchPattern);if(!t)return null;const s=t[0],r=e.match(Ir.parsePattern);if(!r)return null;let n=Ir.valueCallback?Ir.valueCallback(r[0]):r[0];return n=a.valueCallback?a.valueCallback(n):n,{value:n,rest:e.slice(s.length)}}),era:Cr({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:Cr({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:Cr({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:Cr({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:Cr({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"})};var Ir;const Pr={code:"pt-BR",formatDistance:(e,a,t)=>{let s;const r=kr[e];return s="string"==typeof r?r:1===a?r.one:r.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+s:"há "+s:s},formatLong:Sr,formatRelative:(e,a,t,s)=>{const r=Er[e];return"function"==typeof r?r(a):r},localize:Ar,match:Tr,options:{weekStartsOn:0,firstWeekContainsDate:1}};function _r({className:a,classNames:t,showOutsideDays:s=!0,...r}){return e.jsx(k.DayPicker,{showOutsideDays:s,className:me("p-3",a),locale:Pr,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:me(he({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:me(he({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",...t},components:{IconLeft:({...a})=>e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(l.ChevronRight,{className:"h-4 w-4"})},...r})}_r.displayName="Calendar";const Rr=ae.Root,Fr=ae.CollapsibleTrigger,Dr=ae.CollapsibleContent;const Mr={Root:function({children:a,className:t}){return e.jsx("div",{className:me("space-y-4",t),children:a})},Item:function({children:a,onClick:t,className:s}){return e.jsx(Ne,{className:me("transition-colors",t&&"cursor-pointer hover:bg-muted/50",s),onClick:t,children:e.jsx(Ce,{className:"p-4",children:a})})},Field:function({label:a,value:t,className:s}){return e.jsxs("div",{className:me("flex justify-between items-center text-sm",s),children:[e.jsxs("span",{className:"text-muted-foreground font-medium",children:[a,":"]}),e.jsx("span",{className:"text-foreground",children:t})]})}};const Lr={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))]"},zr={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Or({children:a,cols:t="auto-fit",gap:s="md",className:r}){return e.jsx("div",{className:me("grid",Lr[t],zr[s],r),children:a})}const Ur=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function $r({multiple:t,options:s,value:r,onChange:n,getOptionValue:i,getOptionLabel:o,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h,required:x,className:f,sortOptions:g,maxDisplayedBadges:b,popoverContainer:v,onOpen:N,onClose:j}){const[y,w]=a.useState(!1),[C,k]=a.useState(""),S=a.useMemo(()=>r?Array.isArray(r)?r:[r]:[],[r]),E=a.useMemo(()=>{if(!v)return;let e=v,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),s=t.overflowY||t.overflow;if(!s||"visible"===s||"unset"===s)break;e=e.parentElement,a++}}catch{}return e??void 0},[v]),A=a.useMemo(()=>{const e=s.map(e=>({original:e,value:i(e),label:o(e)}));return g?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[s,i,o,g]),T=a.useMemo(()=>{if(!C)return A;const e=Ur(C);return A.filter(a=>Ur(a.label).includes(e))},[A,C]),I=a.useMemo(()=>A.filter(e=>S.includes(e.value)),[A,S]),P=(e,a)=>{a.preventDefault(),a.stopPropagation(),n&&n(t?S.filter(a=>a!==e):"")},_=b?I.slice(0,b):I,R=b&&I.length>b?I.length-b:0;return e.jsxs("div",{className:me("space-y-2",f),children:[c&&e.jsxs(ve,{children:[c,x&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(Ca,{open:y,onOpenChange:e=>{w(e),e?N?.():(k(""),j?.())},modal:!1,children:[e.jsx(ka,{asChild:!0,children:e.jsxs(xe,{variant:"outline",role:"combobox","aria-expanded":y,disabled:h,className:me("w-full justify-between min-h-10 h-auto",0===I.length&&"text-muted-foreground"),children:[0===I.length?e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),d]}):t?e.jsxs("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[_.map(a=>e.jsxs(ra,{variant:"secondary",className:"gap-1 pr-1",children:[a.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&&P(a.value,e)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>P(a.value,e),children:e.jsx(l.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},a.value)),R>0&&e.jsxs(ra,{variant:"outline",className:"gap-1",children:["+",R]})]}):e.jsxs("span",{className:"flex items-center gap-2",children:[u&&e.jsx(u,{className:"h-4 w-4"}),I[0]?.label]}),e.jsx(l.ChevronDown,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Sa,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:E,collisionBoundary:E,children:e.jsxs(Ea,{children:[e.jsx(Aa,{placeholder:p,value:C,onChange:e=>k(e.target.value)}),e.jsx(Ta,{children:0===s.length?e.jsx(Ia,{children:m}):0===T.length?e.jsx(Ia,{children:"Nenhum item encontrado."}):e.jsx(Pa,{children:T.map(a=>e.jsxs(Ra,{value:a.value,onSelect:()=>(e=>{if(n)if(t){const a=S.includes(e)?S.filter(a=>a!==e):[...S,e];n(a)}else n(e),w(!1)})(a.value),className:"cursor-pointer",children:[e.jsx(l.Check,{className:me("mr-2 h-4 w-4",S.includes(a.value)?"opacity-100":"opacity-0")}),a.label]},a.value))})})]})})]})]})}const qr=({className:a,...t})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:me("mx-auto flex w-full justify-center",a),...t});qr.displayName="Pagination";const Vr=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,className:me("flex flex-row items-center gap-1",a),...t}));Vr.displayName="PaginationContent";const Br=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,className:me("",a),...t}));Br.displayName="PaginationItem";const Wr=({className:a,isActive:t,size:s="icon",...r})=>e.jsx("a",{"aria-current":t?"page":void 0,className:me(he({variant:t?"outline":"ghost",size:s}),a),...r});Wr.displayName="PaginationLink";const Hr=({className:a,...t})=>e.jsxs(Wr,{"aria-label":"Go to previous page",size:"default",className:me("gap-1 pl-2.5",a),...t,children:[e.jsx(l.ChevronLeft,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});Hr.displayName="PaginationPrevious";const Qr=({className:a,...t})=>e.jsxs(Wr,{"aria-label":"Go to next page",size:"default",className:me("gap-1 pr-2.5",a),...t,children:[e.jsx("span",{children:"Next"}),e.jsx(l.ChevronRight,{className:"h-4 w-4"})]});Qr.displayName="PaginationNext";const Kr=({className:a,...t})=>e.jsxs("span",{"aria-hidden":!0,className:me("flex h-9 w-9 items-center justify-center",a),...t,children:[e.jsx(l.MoreHorizontal,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More pages"})]});Kr.displayName="PaginationEllipsis";const Gr=q.forwardRef(({className:a,value:t,...s},r)=>e.jsx(te.Root,{ref:r,className:me("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",a),...s,children:e.jsx(te.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Gr.displayName=te.Root.displayName;const Xr=q.forwardRef(({className:a,...t},s)=>e.jsx(se.Root,{className:me("grid gap-2",a),...t,ref:s}));Xr.displayName=se.Root.displayName;const Jr=q.forwardRef(({className:a,...t},s)=>e.jsx(se.Item,{ref:s,className:me("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",a),...t,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"})})}));Jr.displayName=se.Item.displayName;const Yr=q.forwardRef(({className:a,orientation:t="horizontal",decorative:s=!0,...r},n)=>e.jsx(re.Root,{ref:n,decorative:s,orientation:t,className:me("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",a),...r}));Yr.displayName=re.Root.displayName;const Zr=B.Root,en=B.Trigger,an=B.Close,tn=B.Portal,sn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Overlay,{className:me("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",a),...t,ref:s}));sn.displayName=B.Overlay.displayName;const rn=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"}}),nn=q.forwardRef(({side:a="right",className:t,children:s,...r},n)=>e.jsxs(tn,{children:[e.jsx(sn,{}),e.jsxs(B.Content,{ref:n,className:me(rn({side:a}),t),...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"})]})]})]}));nn.displayName=B.Content.displayName;const on=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col space-y-2 text-center sm:text-left",a),...t});on.displayName="SheetHeader";const ln=({className:a,...t})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",a),...t});ln.displayName="SheetFooter";const dn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Title,{ref:s,className:me("text-lg font-semibold text-foreground",a),...t}));dn.displayName=B.Title.displayName;const cn=q.forwardRef(({className:a,...t},s)=>e.jsx(B.Description,{ref:s,className:me("text-sm text-muted-foreground",a),...t}));cn.displayName=B.Description.displayName;const un=ne.Provider,mn=ne.Root,pn=ne.Trigger,hn=q.forwardRef(({className:a,sideOffset:t=4,...s},r)=>e.jsx(ne.Content,{ref:r,sideOffset:t,className:me("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",a),...s}));hn.displayName=ne.Content.displayName;const xn="sidebar:state",fn=q.createContext(null);function gn(){const e=q.useContext(fn);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const bn=q.forwardRef(({defaultOpen:a=!0,open:t,onOpenChange:s,className:r,style:n,children:i,...o},l)=>{const[d,c]=q.useState(!1);q.useEffect(()=>{const e=()=>c(window.innerWidth<768);return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const[u,m]=q.useState(!1),[p,h]=q.useState(()=>{if("undefined"!=typeof window){const e=localStorage.getItem(xn);return null!==e?"true"===e:a}return a}),x=t??p,f=q.useCallback(e=>{const a="function"==typeof e?e(x):e;s?s(a):h(a),"undefined"!=typeof window&&localStorage.setItem(xn,String(a))},[s,x]),g=q.useCallback(()=>d?m(e=>!e):f(e=>!e),[d,f,m]);q.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=x?"expanded":"collapsed",v=q.useMemo(()=>({state:b,open:x,setOpen:f,isMobile:d,openMobile:u,setOpenMobile:m,toggleSidebar:g}),[b,x,f,d,u,m,g]);return e.jsx(fn.Provider,{value:v,children:e.jsx(un,{delayDuration:0,children:e.jsx("div",{className:me("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})})})});bn.displayName="SidebarProvider";const vn=q.forwardRef(({side:a="left",variant:t="sidebar",collapsible:s="offcanvas",className:r,children:n,...i},o)=>{const{isMobile:l,state:d,openMobile:c,setOpenMobile:u}=gn();return"none"===s?e.jsx("div",{className:me("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",r),ref:o,...i,children:n}):l?e.jsx(Zr,{open:c,onOpenChange:u,...i,children:e.jsxs(nn,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden sidebar-mobile",style:{"--sidebar-width":"18rem"},side:a,children:[e.jsx(dn,{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":t,"data-side":a,children:[e.jsx("div",{className:me("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"===t||"inset"===t?"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:me("duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex","left"===a?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]","floating"===t||"inset"===t?"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})})]})});vn.displayName="Sidebar";const Nn=q.forwardRef(({className:a,onClick:t,...s},r)=>{const{toggleSidebar:n}=gn();return e.jsxs(xe,{ref:r,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:me("h-7 w-7",a),onClick:e=>{t?.(e),n()},...s,children:[e.jsx(l.PanelLeft,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Nn.displayName="SidebarTrigger";const jn=q.forwardRef(({className:a,...t},s)=>{const{toggleSidebar:r}=gn();return e.jsx("button",{ref:s,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:r,title:"Toggle Sidebar",className:me("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",a),...t})});jn.displayName="SidebarRail";const yn=q.forwardRef(({className:a,...t},s)=>e.jsx("main",{ref:s,className:me("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",a),...t}));yn.displayName="SidebarInset";const wn=q.forwardRef(({className:a,...t},s)=>e.jsx(ge,{ref:s,"data-sidebar":"input",className:me("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",a),...t}));wn.displayName="SidebarInput";const Cn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"header",className:me("flex flex-col gap-2 p-2",a),...t}));Cn.displayName="SidebarHeader";const kn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"footer",className:me("flex flex-col gap-2 p-2",a),...t}));kn.displayName="SidebarFooter";const Sn=q.forwardRef(({className:a,...t},s)=>e.jsx(Yr,{ref:s,"data-sidebar":"separator",className:me("mx-2 w-auto bg-sidebar-border",a),...t}));Sn.displayName="SidebarSeparator";const En=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"content",className:me("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",a),...t}));En.displayName="SidebarContent";const An=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group",className:me("relative flex w-full min-w-0 flex-col p-2",a),...t}));An.displayName="SidebarGroup";const Tn=q.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const i=s?t.Slot:"div";return e.jsx(i,{ref:n,"data-sidebar":"group-label",className:me("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",a),...r})});Tn.displayName="SidebarGroupLabel";const In=q.forwardRef(({className:a,asChild:s=!1,...r},n)=>{const i=s?t.Slot:"button";return e.jsx(i,{ref:n,"data-sidebar":"group-action",className:me("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",a),...r})});In.displayName="SidebarGroupAction";const Pn=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"group-content",className:me("w-full text-sm",a),...t}));Pn.displayName="SidebarGroupContent";const _n=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu",className:me("flex w-full min-w-0 flex-col gap-1",a),...t}));_n.displayName="SidebarMenu";const Rn=q.forwardRef(({className:a,...t},s)=>e.jsx("li",{ref:s,"data-sidebar":"menu-item",className:me("group/menu-item relative",a),...t}));Rn.displayName="SidebarMenuItem";const Fn=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"}}),Dn=q.forwardRef(({asChild:a=!1,isActive:s=!1,variant:r="default",size:n="default",tooltip:i,className:o,...l},d)=>{const c=a?t.Slot:"button",{isMobile:u,state:m}=gn(),p=e.jsx(c,{ref:d,"data-sidebar":"menu-button","data-size":n,"data-active":s,className:me(Fn({variant:r,size:n}),o),...l});return i?("string"==typeof i&&(i={children:i}),e.jsxs(mn,{children:[e.jsx(pn,{asChild:!0,children:p}),e.jsx(hn,{side:"right",align:"center",hidden:"collapsed"!==m||u,...i})]})):p});Dn.displayName="SidebarMenuButton";const Mn=q.forwardRef(({className:a,asChild:s=!1,showOnHover:r=!1,...n},i)=>{const o=s?t.Slot:"button";return e.jsx(o,{ref:i,"data-sidebar":"menu-action",className:me("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",a),...n})});Mn.displayName="SidebarMenuAction";const Ln=q.forwardRef(({className:a,...t},s)=>e.jsx("div",{ref:s,"data-sidebar":"menu-badge",className:me("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",a),...t}));Ln.displayName="SidebarMenuBadge";const zn=q.forwardRef(({className:a,showIcon:t=!1,...s},r)=>{const n=q.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return e.jsxs("div",{ref:r,"data-sidebar":"menu-skeleton",className:me("rounded-md h-8 flex gap-2 px-2 items-center",a),...s,children:[t&&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}})]})});zn.displayName="SidebarMenuSkeleton";const On=q.forwardRef(({className:a,...t},s)=>e.jsx("ul",{ref:s,"data-sidebar":"menu-sub",className:me("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",a),...t}));On.displayName="SidebarMenuSub";const Un=q.forwardRef(({...a},t)=>e.jsx("li",{ref:t,...a}));Un.displayName="SidebarMenuSubItem";const $n=q.forwardRef(({asChild:a=!1,size:s="md",isActive:r,className:n,...i},o)=>{const l=a?t.Slot:"a";return e.jsx(l,{ref:o,"data-sidebar":"menu-sub-button","data-size":s,"data-active":r,className:me("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})});$n.displayName="SidebarMenuSubButton";const qn=q.forwardRef(({className:a,...t},s)=>e.jsxs(ie.Root,{ref:s,className:me("relative flex w-full touch-none select-none items-center",a),...t,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"})]}));qn.displayName=ie.Root.displayName;const Vn=q.forwardRef(({className:a,...t},s)=>e.jsx(oe.Root,{className:me("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",a),...t,ref:s,children:e.jsx(oe.Thumb,{className:me("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")})}));Vn.displayName=oe.Root.displayName;const Bn=le.Root,Wn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.List,{ref:s,className:me("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",a),...t}));Wn.displayName=le.List.displayName;const Hn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.Trigger,{ref:s,className:me("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",a),...t}));Hn.displayName=le.Trigger.displayName;const Qn=q.forwardRef(({className:a,...t},s)=>e.jsx(le.Content,{ref:s,className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",a),...t}));Qn.displayName=le.Content.displayName;const Kn=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"}}),Gn=q.forwardRef(({className:a,variant:t,size:s,...r},n)=>e.jsx(de.Root,{ref:n,className:me(Kn({variant:t,size:s,className:a})),...r}));Gn.displayName=de.Root.displayName;const Xn=q.createContext({size:"default",variant:"default"}),Jn=q.forwardRef(({className:a,variant:t,size:s,children:r,...n},i)=>e.jsx(ce.Root,{ref:i,className:me("flex items-center justify-center gap-1",a),...n,children:e.jsx(Xn.Provider,{value:{variant:t,size:s},children:r})}));Jn.displayName=ce.Root.displayName;const Yn=q.forwardRef(({className:a,children:t,variant:s,size:r,...n},i)=>{const o=q.useContext(Xn);return e.jsx(ce.Item,{ref:i,className:me(Kn({variant:o.variant||s,size:o.size||r}),a),...n,children:t})});function Zn({onEdit:a,onDelete:t,onToggleStatus:s,isActive:r=!0,canEdit:n=!0,canDelete:i=!0,customActions:o=[],renderAs:d="dropdown",variant:c="default"}){const u=[];return a&&n&&u.push({icon:l.Edit,label:"Editar",onClick:a,variant:"default"}),s&&u.push({icon:r?l.PowerOff:l.Power,label:r?"Inativar":"Ativar",onClick:s,variant:"default"}),o.forEach(e=>{!1!==e.show&&u.push({icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default"})}),t&&i&&u.push({icon:l.Trash2,label:"Remover",onClick:t,variant:"destructive"}),0===u.length?null:"dropdown"===d?e.jsxs(cs,{children:[e.jsx(us,{asChild:!0,children:e.jsx(xe,{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(bs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:u.map((a,t)=>e.jsxs(vs,{onClick:a.onClick,className:"destructive"===a.variant?"text-destructive":"",children:[a.icon&&e.jsx(a.icon,{className:"mr-2 h-4 w-4"}),a.label]},t))})]}):e.jsx("div",{className:"flex items-center gap-1",children:u.map((a,t)=>e.jsxs(xe,{variant:"destructive"===a.variant?"destructive":"ghost",size:"compact"===c?"sm":"default",onClick:a.onClick,className:"compact"===c?"h-7 px-2":"",children:[a.icon&&e.jsx(a.icon,{size:"compact"===c?14:16}),"compact"!==c&&e.jsx("span",{className:"ml-1",children:a.label})]},t))})}function ei(e){const a=b.useNavigate();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const s=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(s)}}}Yn.displayName=ce.Item.displayName;const ai=a.memo(({variant:t="card",className:s="",selectedUnit:r,onUnitChange:n})=>{const{user:i,companies:o,alias:d,isAuthenticated:c,logout:u,switchUnit:m}=zt(),p=o?.[0]||null,h=d?o?.find(e=>e.alias===d):p,x=o||[],f=r||h||p||p,g=a.useCallback(e=>{n?n(e):m(e)},[n,m]),b=a.useMemo(()=>{if(!x?.length)return[];const e=new Map;x.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===f?.alias),s=a.filter(e=>e.alias!==f?.alias);return s.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...s]:s},[x,f?.alias]);if(!c||!i)return null;const v=()=>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: ",f?.name||"N/A"]})]})]}),f&&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:f.name})]})}),b.length>1&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",b.length]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[b.slice(0,3).map(a=>e.jsx(ra,{variant:a.alias===f?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>g(a),children:a.name},a.alias)),b.length>3&&e.jsxs(ra,{variant:"outline",className:"text-xs",children:["+",b.length-3]})]})]})]});return"dropdown"===t?e.jsxs(cs,{children:[e.jsx(us,{asChild:!0,children:e.jsx(xe,{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:f?.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(bs,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[e.jsxs(hs,{children:[e.jsxs(fs,{children:[e.jsx(l.RefreshCw,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),e.jsx(gs,{children:b.map(a=>e.jsxs(vs,{onClick:()=>g(a),className:a.alias===f?.alias?"bg-muted":"",children:[e.jsx(l.Building2,{className:"mr-2 h-4 w-4"}),a.name,a.alias===f?.alias&&e.jsx(ra,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},a.alias))})]}),e.jsx(ws,{}),e.jsxs(vs,{onClick:u,children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}):e.jsxs(Ne,{className:s,children:[e.jsx(je,{children:e.jsx(ye,{className:"text-lg",children:"Informações do Usuário"})}),e.jsxs(Ce,{className:"space-y-4",children:[e.jsx(v,{}),e.jsx(Yr,{}),e.jsxs(xe,{variant:"outline",onClick:u,size:"sm",className:"w-full",children:[e.jsx(l.LogOut,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),ti=a.createContext({});function si({children:t,config:s}){const r=a.useMemo(()=>({navigation:s?.navigation,appName:s?.appName}),[s?.navigation,s?.appName]);return e.jsx(ti.Provider,{value:r,children:t})}function ri(){return a.useContext(ti)}function ni(){const e=b.useLocation(),{navigation:a}=ri();if(!a)return"Página";const t=a.find(a=>a.path===e.pathname);if(t)return t.label;const s=a.find(a=>e.pathname.startsWith(a.path+"/"));return s?.label||"Página"}function ii(e,t){const[s,r]=a.useState(e),n=a.useRef(),i=a.useCallback(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return a.useEffect(()=>(i(),n.current=setTimeout(()=>{r(e)},t),i),[e,t,i]),[s,i]}const oi=a.memo(function({actions:t}){const s=b.useLocation(),r=ni(),{navigation:n,appName:i}=ri(),{metadata:o}=ir(),{companies:d,alias:c,isSearchVisible:u,clearSearch:m,refreshData:p,switchUnit:h}=zt(),x=c?d?.find(e=>e.alias===c)||d?.[0]||null:d?.[0]||null,[f,g]=b.useSearchParams(),[v,N]=a.useState(()=>f.get("search")||""),[j,y]=ii(v,gt.debounceDelay);a.useEffect(()=>{if(!u)return;const e=new URLSearchParams(f);j?(e.set("search",j),e.set("page","1")):e.delete("search"),g(e)},[j,g,u]);const w=n?.find(e=>e.path===s.pathname)||n?.find(e=>s.pathname.startsWith(e.path+"/")),C=o.title||r,k=o.subtitle||w?.complementaryText||"Detalhes do item";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(ra,{variant:"default",className:"bg-primary hover:bg-primary/90 text-primary-foreground text-xs px-2 py-1",children:i||"Módulo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:k})]}),u&&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(ge,{placeholder:"/wiki"===s.pathname?"Buscar artigos...":"Buscar...",value:v,onChange:e=>(e=>{N(e)})(e.target.value),className:"w-full pl-10 pr-8"}),v&&e.jsx(xe,{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:()=>{y(),N("");const e=new URLSearchParams(f);e.delete("search"),e.delete("page"),g(e)},title:"Limpar busca",children:e.jsx(l.X,{size:14})})]}),e.jsx(xe,{variant:"outline",size:"sm",onClick:p,className:"flex-shrink-0 h-10 w-10 p-0",title:"Atualizar dados",children:e.jsx(l.RefreshCw,{size:14})})]}),e.jsxs("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[t&&e.jsx("div",{className:"flex items-center gap-2",children:t}),(void 0).VITE_WIKI_URL&&e.jsx(xe,{variant:"secondary",size:"sm",className:"h-8 px-3",onClick:e=>ue((void 0).VITE_WIKI_URL,e),title:"Abrir Wiki",children:"Wiki"}),e.jsx("div",{className:"text-sm",children:e.jsx(ai,{variant:"dropdown",selectedUnit:x,onUnitChange:h})})]})]})})}),li=({key:e,enabled:a,checkFn:t,staleTime:s=3e5,gcTime:r=6e5})=>g.useQuery({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:s,gcTime:r,retry:0,refetchOnWindowFocus:!1}),di=(e={})=>{const{enabled:a=!0}=e,{alias:t}=zt();return g.useQuery({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=rt(),{data:a,error:s}=await e.schema("central").from("modules").select("\n id, name, url,\n modules_alias!inner(alias)\n ").eq("modules_alias.alias",t).eq("status","active").order("name");if(s){if(!dt.handleError(s))throw s;return[]}return a||[]},enabled:a&&!!t})},ci="forlogic-sidebar-pinned",ui=()=>{try{const e=localStorage.getItem(ci);return!!e&&JSON.parse(e)}catch{return!1}},mi=e=>{const a=["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 a[e%a.length]},pi=(void 0).VITE_SUPABASE_PROJECT_ID,hi={logo:`https://${pi}.supabase.co/storage/v1/object/public/library-assets/logo.svg`,smallLogo:`https://${pi}.supabase.co/storage/v1/object/public/library-assets/small.svg`},xi=hi.logo,fi=hi.smallLogo;function gi({appName:a,isPinned:t,onPinToggle:s,open:r,dropdownOpen:n,onDropdownChange:i}){const{data:o,isLoading:d,error:c}=di({enabled:n}),u=e=>{((e,a)=>{const t=e?.find(e=>e.url===a);t?.url&&window.open(t.url,"_blank")})(o,e)};return e.jsxs(Cn,{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:hi.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 "+(t?"bg-primary text-primary-foreground":"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:hi.smallLogo,alt:"Logo",className:"h-[34px] w-[34px] object-contain"})})}),e.jsx("div",{className:"mt-2 pt-0",children:e.jsxs(cs,{onOpenChange:i,children:[e.jsx(us,{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:a})]}),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(bs,{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:"Carregando módulos..."})]}):c?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:"Erro ao carregar módulos"})]}):o&&0!==o.length?e.jsx("div",{className:"space-y-2",children:o.map((a,t)=>e.jsx("div",{onClick:()=>u(a.url||""),className:`\n bg-muted/50 hover:bg-muted rounded-md p-3 cursor-pointer \n border-l-4 ${mi(t)} 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:a.name}),a.url&&e.jsx(l.ExternalLink,{className:"h-4 w-4 text-muted-foreground"})]})},a.id))}):e.jsx("div",{className:"py-3 px-3 text-muted-foreground text-sm",children:"Nenhum módulo disponível"})})]})})]})}function bi({direction:e="right",minWidth:t=224,maxWidth:s=384,defaultWidth:r=240,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[l,d]=a.useState(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[c,u]=a.useState(!1),m=a.useRef(null);a.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=a.useCallback(e=>{e.preventDefault(),u(!0)},[]);return a.useEffect(()=>{if(!c)return;const a=a=>{let r;r="left"===e?window.innerWidth-a.clientX:a.clientX,r=Math.max(t,Math.min(s,r)),d(r),i?.(r)},r=()=>{u(!1),localStorage.setItem(n,l.toString())};return document.addEventListener("mousemove",a),document.addEventListener("mouseup",r),()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",r)}},[c,e,t,s,l,n,i]),a.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 vi=a.forwardRef(({className:a,onMouseDown:t,isDragging:s,...r},n)=>e.jsx("div",{ref:n,onMouseDown:t,className:me("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",a),...r}));function Ni({config:t,customContent:s,resizable:r=!1,minWidth:n=224,maxWidth:i=384}={}){const{open:o,setOpen:d}=gn(),c=b.useLocation(),{alias:u,user:m}=zt(),[p,h]=a.useState(!1),[x,f]=a.useState(ui),[g,v]=a.useState(!1),N=r?bi({minWidth:n,maxWidth:i,storageKey:"app-sidebar-width",isOpen:o}):null;a.useEffect(()=>{d(!!x||!(!g&&!p))},[x,g,p,d]);return e.jsxs(vn,{collapsible:"icon",onMouseEnter:()=>{x||v(!0)},onMouseLeave:()=>{x||v(!1)},className:"app-sidebar bg-white border-r border-gray-200 py-6 px-3",style:N&&o?{width:`${N.width}px`,transition:"none"}:{transition:"all 300ms ease-in-out"},children:[e.jsx(gi,{appName:t?.appName||"Título do módulo",isPinned:x,onPinToggle:()=>{const e=!x;f(e),(e=>{try{localStorage.setItem(ci,JSON.stringify(e))}catch{}})(e)},open:o,dropdownOpen:p,onDropdownChange:h}),e.jsx(En,{children:s||e.jsx(An,{className:"p-0 mt-6",children:e.jsx(Pn,{children:e.jsx(_n,{className:"space-y-2",children:e.jsx(un,{children:t?.navigation?.map((a,t)=>{const s=({item:a,index:t})=>{const r=`${a.path}-${t}-${u??"noalias"}-${m?.id??"nouser"}`,{data:n=!0,isLoading:i}=li({key:r,enabled:Boolean(a.permissionCheck&&u&&m?.id),checkFn:a.permissionCheck||(()=>Promise.resolve(!0))}),o=a.permissionCheck&&!n,d=i?l.Loader2:o?l.Lock:a.icon;o||a.complementaryText;return a.children&&a.children.length>0?e.jsx(Rr,{defaultOpen:!0,className:"group/collapsible",children:e.jsxs(Rn,{children:[e.jsx(Fr,{asChild:!0,children:e.jsx(Dn,{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:a.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(Dr,{children:e.jsx(On,{children:a.children.map((a,t)=>e.jsx(s,{item:a,index:t},a.path))})})]})},a.path):e.jsx(Rn,{children:o||i?e.jsxs(mn,{children:[e.jsx(pn,{asChild:!0,children:e.jsx(Dn,{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:a.label})]})})}),e.jsx(hn,{children:e.jsx("p",{children:i?"Verificando acesso...":"Acesso restrito"})})]}):e.jsx(Dn,{asChild:!0,isActive:(p=a.path,c.pathname===p||c.pathname.startsWith(p+"/")),size:"lg",className:"h-10",children:e.jsxs(b.Link,{to:a.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:a.label})]})})},a.path);var p};return e.jsx(s,{item:a,index:t},a.path)})})})})})}),r&&N&&o&&e.jsx(vi,{ref:N.dragRef,onMouseDown:N.handleMouseDown,isDragging:N.isDragging})]})}vi.displayName="ResizableRail";const ji=a.memo(function({children:t,sidebar:s,sidebarConfig:r,showHeader:n=!0}){const i=a.useMemo(()=>s||e.jsx(Ni,{config:r}),[s,r]),o=a.useMemo(()=>({"--sidebar-width":"240px","--sidebar-width-icon":"58px"}),[]);return e.jsx(si,{config:r,children:e.jsx(nr,{children:e.jsx(bn,{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(oi,{})}),e.jsx("div",{className:"flex-1 overflow-y-auto bg-gray-50",children:t})]})]})})})})});var yi=Object.defineProperty,wi=(e,a,t)=>((e,a,t)=>a in e?yi(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);class Ci extends a.Component{constructor(e){super(e),wi(this,"copyErrorDetails",()=>{const e=Ja.getErrors().slice(0,2),a=`\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,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||"Nenhum erro registrado"}\n `.trim();navigator.clipboard.writeText(a),ha({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,a){if((void 0).DEV)throw e;Ja.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const a=Ja.getErrors().slice(0,2);return e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Ne,{className:"w-full max-w-2xl",children:[e.jsxs(je,{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(ye,{children:"Algo deu errado"})]}),e.jsxs(Ce,{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(Rr,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[e.jsx(Fr,{asChild:!0,children:e.jsxs(xe,{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(Dr,{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(Rs,{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})})]})]}),a.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:a.map((a,t)=>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:[t+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(a.timestamp).toLocaleTimeString(),"]"]})}),e.jsx("p",{className:"text-sm break-words",children:a.message})]})]})},a.id))})]})]}),e.jsxs(xe,{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(xe,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}class ki{static async sendEmail(e){const a=rt(),{data:t,error:s}=await a.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 t}}const Si=ki;function Ei(){const[e,t]=a.useState([]),[s,r]=a.useState(!1),[n,i]=a.useState(null),[l,d]=a.useState(null);a.useEffect(()=>{c()},[]);const c=async()=>{try{const e=rt(),{data:a,error:s}=await e.functions.invoke("openai-chat",{body:{action:"createThread"}});if(s)throw s;i(a.threadId),t([{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:a.useCallback(async e=>{if(!n||!e.trim())return;const a={id:`user-${Date.now()}`,role:"user",content:e,timestamp:new Date};t(e=>[...e,a]),r(!0),d(null);try{const a=rt(),{data:s,error:r}=await a.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 t=0;t<60;t++)try{const a=rt(),{data:t,error:s}=await a.functions.invoke("openai-chat",{body:{action:"checkRunStatus",threadId:n,runId:e}});if(s)throw s;const{status:r}=t;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(a){throw a}throw new Error("Tempo limite excedido")})(i);o&&await(async()=>{if(n)try{const e=rt(),{data:a,error:s}=await e.functions.invoke("openai-chat",{body:{action:"getMessages",threadId:n}});if(s)throw s;const r=a.messages.map(e=>({id:e.id,role:e.role,content:e.content,timestamp:new Date(1e3*e.created_at)}));t(r)}catch(e){throw e}})()}catch(s){const e=s instanceof Error?s.message:"Erro ao enviar mensagem";d(e),o.toast.error(e),t(e=>e.filter(e=>e.id!==a.id))}finally{r(!1)}},[n]),threadId:n}}function Ai({content:a,className:t}){return e.jsx("div",{className:me("prose prose-sm max-w-none",t),children:e.jsx(L,{remarkPlugins:[z],components:{h1:({children:a})=>e.jsx("h1",{className:"text-lg font-bold mt-4 mb-2 text-foreground",children:a}),h2:({children:a})=>e.jsx("h2",{className:"text-base font-bold mt-3 mb-2 text-foreground",children:a}),h3:({children:a})=>e.jsx("h3",{className:"text-sm font-semibold mt-2 mb-1 text-foreground",children:a}),p:({children:a})=>e.jsx("p",{className:"text-sm mb-2 last:mb-0 text-foreground",children:a}),ul:({children:a})=>e.jsx("ul",{className:"list-disc list-inside mb-2 space-y-1",children:a}),ol:({children:a})=>e.jsx("ol",{className:"list-decimal list-inside mb-2 space-y-1",children:a}),li:({children:a})=>e.jsx("li",{className:"text-sm text-foreground",children:a}),code:({inline:a,children:t,...s})=>a?e.jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-xs font-mono text-foreground",...s,children:t}):e.jsx("code",{className:"block bg-muted p-2 rounded text-xs font-mono overflow-x-auto mb-2 text-foreground",...s,children:t}),pre:({children:a})=>e.jsx("pre",{className:"bg-muted p-2 rounded overflow-x-auto mb-2",children:a}),a:({children:a,href:t})=>e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:a}),blockquote:({children:a})=>e.jsx("blockquote",{className:"border-l-4 border-primary pl-3 italic my-2 text-muted-foreground",children:a}),strong:({children:a})=>e.jsx("strong",{className:"font-bold text-foreground",children:a}),em:({children:a})=>e.jsx("em",{className:"italic text-foreground",children:a})},children:a})})}function Ti({open:t,onOpenChange:s,placeId:r,placeName:n,onMakeManager:i,onMakeMembers:o,currentManagerId:d,currentMemberIds:c=[]}){const[u,m]=a.useState([]),[p,h]=a.useState(!1),[x,f]=a.useState(""),{data:g=[],isLoading:b}=zs({enabled:t}),v=a.useMemo(()=>{let e=[...g];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",s=a.userName?.toLowerCase()||"";return t.localeCompare(s)}),x){const a=x.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[g,x]),N=e=>{m(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},j=1===u.length,y=u.length>0;return e.jsx(Se,{open:t,onOpenChange:s,children:e.jsxs(Pe,{className:"max-w-2xl",children:[e.jsx(_e,{children:e.jsxs(Fe,{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(ge,{placeholder:"Buscar por nome ou email...",value:x,onChange:e=>f(e.target.value),className:"pl-9"})]}),e.jsx(Rs,{className:"h-[400px] pr-4",children:b?e.jsx("div",{className:"space-y-2",children:[...Array(5)].map((a,t)=>e.jsx(Da,{className:"h-16 w-full"},t))}):0===v.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:v.map(a=>{const t=a.userId===d,s=c.includes(a.userId||""),r=u.includes(a.userId||"");return e.jsxs("div",{className:me("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(a.userId||""),children:[e.jsx(aa,{checked:r,onCheckedChange:()=>N(a.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:a.userName}),t&&e.jsx(l.Crown,{className:"h-4 w-4 text-yellow-500"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.userEmail})]}),(t||s)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:t?"Gestor":"Membro"})]},a.userId)})})}),e.jsxs(Re,{className:"flex gap-2 sm:gap-2",children:[e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:u.length>0&&e.jsxs("span",{children:[u.length," selecionado(s)"]})}),j&&i&&e.jsxs(xe,{onClick:async()=>{if(i&&1===u.length){h(!0);try{await i(u[0],r),m([])}finally{h(!1)}}},disabled:p,variant:"outline",children:[e.jsx(l.Crown,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),y&&o&&e.jsxs(xe,{onClick:async()=>{if(o&&0!==u.length){h(!0);try{await o(u,r),m([])}finally{h(!1)}}},disabled:p,children:[e.jsx(l.UserPlus,{className:"h-4 w-4 mr-2"}),"Tornar ",u.length>1?"Membros":"Membro"]})]})]})})}function Ii({place:t,level:s=0,manageAccessConfig:r}){const[n,i]=a.useState(!1),[o,d]=a.useState(!1),c=t.subPlaces&&t.subPlaces.length>0,u=t.isActive??!0,m=t.usersCount??0;return e.jsxs("div",{children:[e.jsxs(Rr,{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(Fr,{className:"flex items-center gap-2 flex-1",children:[e.jsx(l.ChevronRight,{className:me("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:t.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",t.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:t.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(ra,{variant:u?"default":"secondary",className:"text-xs",children:u?"Ativo":"Inativo"}),r&&e.jsx(Zn,{customActions:[{label:"Gerenciar Acessos",icon:l.Settings,onClick:()=>d(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),c&&e.jsx(Dr,{children:t.subPlaces.map(a=>e.jsx(Ii,{place:a,level:s+1,manageAccessConfig:r},a.id))})]}),0===s&&e.jsx(Yr,{}),r&&e.jsx(Ti,{open:o,onOpenChange:d,placeId:t.id,placeName:t.name,onMakeManager:r.onMakeManager,onMakeMembers:r.onMakeMembers,currentManagerId:r.getCurrentManagerId?.(t.id),currentMemberIds:r.getCurrentMemberIds?.(t.id)})]})}var Pi=Object.defineProperty,_i=(e,a,t)=>((e,a,t)=>a in e?Pi(e,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[a]=t)(e,a+"",t);const Ri=new class{constructor(){_i(this,"baseUrl",(void 0).VITE_QUALIEX_API_URL)}async makeApiCall(e,a,t){const s=ut.validateToken();if(!s.valid)throw new Error(s.message||"Token inválido");const r=Ka.getAccessToken();if(!r)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const n=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{n.searchParams.append(e,a)});const i=await fetch(n.toString(),{method:"GET",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!i.ok){const e=new Error(`API call failed: ${i.status}`);throw e.status=i.status,e}return i.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const s=a.get(e.id);if(e.parentId){const r=a.get(e.parentId);r?(r.subPlaces=r.subPlaces||[],r.subPlaces.push(s)):t.push(s)}else t.push(s)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(t){if(await ut.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),s=t.data||t||[];return this.buildHierarchy(s)}catch(s){return Ja.handleError(s instanceof Error?s:"Erro ao buscar locais após renovação de token",!0),[]}return Ja.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Fi(e){const a=new Map,t=new Map,s=[];e.forEach(e=>{const s={...e,children:[],level:0};a.set(e.id,s),t.set(e.id_user,s)}),e.forEach(e=>{const r=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(r)}s.push(r)});const r=(e,a)=>{e.level=a,e.children.forEach(e=>r(e,a+1))};s.forEach(e=>r(e,0));const n=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",s=a.name||a.id_user||a.email||"";return t.localeCompare(s)}),e.forEach(e=>e.children.length>0&&n(e.children))};return n(s),s}function Di(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Mi(){const{alias:e,isAuthenticated:a}=zt(),t=Ka.getAccessToken(),{data:s=[]}=zs({enabled:!0});return g.useQuery({queryKey:["leadership",e,s.length],queryFn:async()=>{if(!t||!e)throw new Error("Usuário não autenticado ou unidade não selecionada");const a=rt(),{data:r,error:n}=await a.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(a=>a.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 a=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:a?.name||e,email:a?.email||"",subordinatesCount:r.filter(a=>a.id_leader===e).length})}),Fi(o)},enabled:!!t&&!!e&&a&&s.length>0})}function Li(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await qi(s,a,e,t.id_user,t.id_leader);const{data:r,error:n}=await s.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success("Líder virtual promovido com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao criar líder")}})}function zi(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(!t.users.length)throw new Error("Selecione pelo menos um liderado");const r=t.users.map(e=>e.id_user),{data:n}=await s.schema(e).from("leaders").select("id_user").eq("alias",a).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 t.users){if(d.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");await qi(s,a,e,d.id_user,t.id_leader)}const i=t.users.map(e=>({alias:a,id_user:e.id_user,id_leader:t.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=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success(`${e?.length||0} liderado(s) adicionado(s) com sucesso`)},onError:e=>{o.toast.error(e.message||"Erro ao adicionar liderados")}})}function Oi(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");const{data:r}=await s.schema(e).from("leaders").select("id_user").eq("id",t.id).eq("alias",a).single();if(!r)throw new Error("Líder não encontrado");if(r.id_user===t.id_leader)throw new Error("Usuário não pode ser seu próprio líder");t.id_leader&&await qi(s,a,e,r.id_user,t.id_leader,t.id);const{data:n,error:i}=await s.schema(e).from("leaders").update({id_leader:t.id_leader}).eq("id",t.id).eq("alias",a).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success("Líder atualizado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao atualizar líder")}})}function Ui(){const{alias:e}=zt(),a=g.useQueryClient(),t=rt();return g.useMutation({mutationFn:async a=>{if(!e)throw new Error("Unidade não selecionada");const{error:s}=await t.schema("common").from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(s)throw s},onSuccess:()=>{a.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 $i(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async({leaderUserId:t,selectedUsers:r})=>{if(!a)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",a).eq("is_removed",!1).eq("id_leader",t),s.schema(e).from("leaders").select("id, id_user, id_leader").eq("alias",a).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)),x=m.filter(e=>e.id_leader!==t),f=new Set(m.map(e=>e.id_user)),g=r.filter(e=>!f.has(e.id_user));for(const N of x)await qi(s,a,e,N.id_user,t,N.id);for(const N of g){if(N.id_user===t)throw new Error("Usuário não pode ser seu próprio líder");await qi(s,a,e,N.id_user,t)}const b=[];if(h.length){const t=h.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:null}).in("id",t).eq("alias",a))}if(x.length){const r=x.map(e=>e.id);b.push(s.schema(e).from("leaders").update({id_leader:t}).in("id",r).eq("alias",a))}if(g.length){const r=g.map(e=>({alias:a,id_user:e.id_user,id_leader:t,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:x.length,created:g.length}},onSuccess:e=>{t.invalidateQueries({queryKey:["leadership",a]}),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 qi(e,a,t,s,r,n){const{data:i,error:o}=await e.schema(t).from("leaders").select("id, id_user, id_leader").eq("alias",a).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 Vi({leader:a,expandedIds:t,onToggleExpand:s,onEdit:r}){const n=t.has(a.id),i=a.children.length>0,o=32*a.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(a.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(a)},className:"font-medium hover:text-primary hover:underline text-left",children:a.name||a.id_user||a.email})]})}),e.jsx("td",{className:"py-3 px-4 text-center",children:e.jsx("span",{className:"text-sm",children:a.subordinatesCount||0})})]}),i&&n&&a.children.map(a=>e.jsx(Vi,{leader:a,expandedIds:t,onToggleExpand:s,onEdit:r},a.id))]})}var Bi=function(e,a){for(var t={};e.length;){var s=e[0],r=s.code,n=s.message,i=s.path.join(".");if(!t[i])if("unionErrors"in s){var o=s.unionErrors[0].errors[0];t[i]={message:o.message,type:o.code}}else t[i]={message:n,type:r};if("unionErrors"in s&&s.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[i].types,d=l&&l[s.code];t[i]=u.appendErrors(i,a,t,r,d?[].concat(d,s.message):s.message)}e.shift()}return t},Wi=function(e,a,t){return void 0===t&&(t={}),function(s,r,n){try{return Promise.resolve(function(r,i){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](s,a)).then(function(e){return n.shouldUseNativeValidation&&U.validateFieldsNatively({},n),{errors:{},values:t.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:U.toNestErrors(Bi(e.errors,!n.shouldUseNativeValidation&&"all"===n.criteriaMode),n)};throw e}))}catch(i){return Promise.reject(i)}}};const Hi=O.z.object({id_leader:O.z.string().nullable(),id_users:O.z.array(O.z.string()).min(1,"Selecione pelo menos um liderado")}),Qi=O.z.object({id_leader:O.z.string().nullable(),id_users:O.z.array(O.z.string())});function Ki({value:t,onChange:s,excludeUserIds:r=[],error:n}){const{data:i=[],isLoading:o}=zs(),[d,c]=a.useState(""),u=a.useRef(null),m=a.useRef(0),p=i.filter(e=>!r.includes(e.userId||"")).filter(e=>{const a=d.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const s=t.includes(e.userId),r=t.includes(a.userId);if(s&&!r)return-1;if(!s&&r)return 1;const n=e.userName||e.userEmail||"",i=a.userName||a.userEmail||"";return n.localeCompare(i)});return a.useEffect(()=>{u.current&&m.current>0&&(u.current.scrollTop=m.current)},[p]),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:"Carregando usuários..."})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ge,{placeholder:"Buscar usuário...",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===p.length?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum usuário encontrado"}):e.jsx("div",{className:"space-y-2",children:p.map(a=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(aa,{id:a.userId,checked:t.includes(a.userId),onCheckedChange:()=>{return e=a.userId,u.current&&(m.current=u.current.scrollTop),void(t.includes(e)?s(t.filter(a=>a!==e)):s([...t,e]));var e}}),e.jsx(ve,{htmlFor:a.userId,className:"flex-1 cursor-pointer",children:a.userName||a.userEmail})]},a.userId))})}),t.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[t.length," usuário(s) selecionado(s)"]}),n&&e.jsx("p",{className:"text-sm text-destructive",children:n})]})}function Gi({leader:t,prefilledLeaderId:s,onSuccess:r}){const{alias:n}=zt(),i=!!t,o=t?.id.startsWith("virtual-"),d=zi(),c=Li(),m=Oi(),p=$i(),h=Ui(),{data:x=[]}=Mi(),{data:f=[]}=zs(),[g,b]=a.useState(""),v=Di(x).map(e=>e.id_user),N=i?Di(x).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user):[],j=u.useForm({resolver:Wi(i?Qi:Hi),defaultValues:{id_leader:s||(i?t?.id_leader:null)||null,id_users:i?N:[]}});a.useEffect(()=>{if(t){const e=Di(x).filter(e=>e.id_leader===t.id_user).map(e=>e.id_user);j.reset({id_leader:t.id_leader||null,id_users:e})}else s?j.reset({id_leader:s,id_users:[]}):j.reset({id_leader:null,id_users:[]})},[n,t?.id,t?.id_user,t?.id_leader,s,x]);const y=d.isPending||c.isPending||m.isPending||p.isPending||h.isPending,w=j.watch("id_leader"),C=j.watch("id_users"),k=i?[t.id_user,...v.filter(e=>e!==t.id_user&&!C.includes(e)&&!N.includes(e))]:[w,...v.filter(e=>!C.includes(e))].filter(Boolean);return e.jsxs("form",{onSubmit:j.handleSubmit(async e=>{try{if(i)if(o){await c.mutateAsync({id_user:t.id_user,id_leader:e.id_leader});const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{await m.mutateAsync({id:t.id,id_leader:e.id_leader});const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({leaderUserId:t.id_user,selectedUsers:a})}else{const a=f.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await d.mutateAsync({id_leader:e.id_leader,users:a})}r?.()}catch(a){}}),className:"space-y-4",children:[i&&e.jsxs("div",{children:[e.jsx(ve,{children:"Líder"}),e.jsx(ge,{value:f.find(e=>e.userId===t.id_user)?.userName||t.name||t.id_user,disabled:!0,className:"bg-muted"})]}),e.jsxs("div",{children:[e.jsx(ve,{children:"Líder Superior"}),e.jsxs(We,{value:w||"none",onValueChange:e=>j.setValue("id_leader","none"===e?null:e),children:[e.jsx(Ke,{children:e.jsx(Qe,{placeholder:"Nenhum (líder raiz)"})}),e.jsxs(Je,{children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:e.jsx(ge,{placeholder:"Buscar líder...",value:g,onChange:e=>b(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),e.jsxs(Rs,{className:"h-[200px]",children:[e.jsx(Ze,{value:"none",children:"Nenhum (líder raiz)"}),f.filter(e=>{const a=i?e.userId!==t.id_user:!C.includes(e.userId),s=!g||e.userName?.toLowerCase().includes(g.toLowerCase());return a&&s}).sort((e,a)=>{const t=e.userName||e.userEmail||"",s=a.userName||a.userEmail||"";return t.localeCompare(s)}).map(a=>e.jsx(Ze,{value:a.userId,children:a.userName},a.userId))]})]})]},`superior-select-${n}`),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.jsx(ve,{children:"Liderados *"}),e.jsx(Ki,{value:C,onChange:e=>j.setValue("id_users",e),excludeUserIds:k,error:j.formState.errors.id_users?.message},`users-multiselect-${n}`)]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(xe,{type:"submit",disabled:y||!i&&0===C.length,children:y&&!h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),i?"Atualizando...":"Salvando..."]}):i?C.length>0?`Atualizar (${C.length})`:"Atualizar":`Adicionar (${C.length})`}),i&&!w&&0===C.length&&e.jsx(xe,{type:"button",variant:"destructive",disabled:y,onClick:async()=>{if(t&&window.confirm("Tem certeza que deseja remover esta liderança?"))try{await h.mutateAsync(t.id),r?.()}catch(e){}},className:"ml-auto",children:h.isPending?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Trash2,{className:"mr-2 h-4 w-4"}),"Remover"]})})]})]})}function Xi({open:a,onOpenChange:t,leader:s,prefilledLeaderId:r,title:n}){return e.jsx(Se,{open:a,onOpenChange:t,children:e.jsxs(Pe,{className:"sm:max-w-[500px]",children:[e.jsx(_e,{children:e.jsx(Fe,{children:n})}),e.jsx(Gi,{leader:s,prefilledLeaderId:r,onSuccess:()=>t(!1)})]})})}const Ji="leadership-expanded-nodes",Yi=(e,a)=>{try{localStorage.setItem(`${Ji}-${e}`,JSON.stringify(Array.from(a)))}catch(t){}};function Zi(e){const[t,s]=a.useState(!1),[r,n]=a.useState(0),{uploadFunction:i,deleteFunction:o,defaultOptions:l,onSuccess:d,onError:c}=e||{};return{upload:async(e,a)=>{if(!i){const e=new Error("uploadFunction não fornecida");throw ha({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 t={...l,...a};if(t.maxSize&&e.size>t.maxSize)throw new Error(`Arquivo muito grande. Tamanho máximo: ${Math.round(t.maxSize/1024/1024)}MB`);if(t.allowedTypes){if(!t.allowedTypes.some(a=>a.endsWith("/*")?e.type.startsWith(a.replace("/*","")):e.type===a))throw new Error(`Tipo de arquivo não permitido. Tipos aceitos: ${t.allowedTypes.join(", ")}`)}const s=await i(e,t);return n(100),ha({title:"Sucesso",description:"Arquivo enviado com sucesso"}),d?.(s),s}catch(t){const e=t instanceof Error?t:new Error("Erro ao fazer upload");throw ha({title:"Erro",description:e.message,variant:"destructive"}),c?.(e),e}finally{s(!1)}},deleteMedia:async(e,a)=>{if(!o){const e=new Error("deleteFunction não fornecida");throw ha({title:"Erro de configuração",description:"Função de delete não configurada.",variant:"destructive"}),e}try{await o(e,a),ha({title:"Sucesso",description:"Arquivo removido com sucesso"})}catch(t){throw ha({title:"Erro",description:"Erro ao remover o arquivo",variant:"destructive"}),t}},uploading:t,progress:r}}function eo(e){const a=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/,/^([a-zA-Z0-9_-]{11})$/];for(const t of a){const a=e.match(t);if(a)return a[1]}return null}function ao(e,a){const t=eo(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function to(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function so(e,a){const t=to(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ro(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function no(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function io(e,a){return e/a}Object.defineProperty(exports,"sonnerToast",{enumerable:!0,get:function(){return o.toast}}),exports.AUTH_CONFIG=xt,exports.Accordion=or,exports.AccordionContent=cr,exports.AccordionItem=lr,exports.AccordionTrigger=dr,exports.ActionButton=fe,exports.ActionMenu=Zn,exports.ActionMenuItems=ks,exports.Alert=ar,exports.AlertDescription=sr,exports.AlertDialog=Ut,exports.AlertDialogAction=Gt,exports.AlertDialogCancel=Xt,exports.AlertDialogContent=Bt,exports.AlertDialogDescription=Kt,exports.AlertDialogFooter=Ht,exports.AlertDialogHeader=Wt,exports.AlertDialogOverlay=Vt,exports.AlertDialogPortal=qt,exports.AlertDialogTitle=Qt,exports.AlertDialogTrigger=$t,exports.AlertTitle=tr,exports.AppHeader=oi,exports.AppLayout=ji,exports.AppSidebar=Ni,exports.AspectRatio=ur,exports.AuthErrorInterceptor=dt,exports.AuthProvider=({children:t})=>{const[s,r]=a.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]=a.useState(!1),[l,d]=a.useState(0),c=a.useCallback(e=>{r(a=>({...a,...e}))},[]),u=a.useCallback(e=>{r(a=>({...a,isLoading:e}))},[]),m=a.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=a.useCallback(async e=>{try{u(!0);const t=Ka.getAccessToken();if(!t)return;const r=await nt.generateToken(t,e.alias,void 0,!0);if(!r)return;Ka.setSupabaseToken(r),Ka.setSelectedAlias(e.alias);const i=Ka.extractTokenData(),o=i?.alias||e.alias,l=i?.companyId||Ka.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 ht.fetchActiveUsersMap(o,l)).get(s.user.id);if(e){const a=Ft(e);m=a.placeId,p=a.placeName}}catch(a){}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(a){}finally{u(!1)}},[c,n,u,s.user]),h=a.useCallback(async()=>await Mt.processCallback(),[]),x=a.useCallback(async()=>{Mt.logout(),m(),n&&await n.clear()},[m,n]),f=a.useCallback(e=>{o(e)},[]),b=a.useCallback(()=>{d(e=>e+1)},[]),v=a.useCallback(()=>{d(e=>e+1)},[]);a.useEffect(()=>{if(!s.isAuthenticated)return;let e=!0;const a=setInterval(()=>{e&&(Ka.areAllTokensValid()||e&&x())},6e5);return()=>{e=!1,clearInterval(a)}},[s.isAuthenticated,x]),a.useEffect(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await Mt.initialize();if(!e)return;a&&a.isAuthenticated?c({user:a.user,companies:a.companies,alias:a.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:a.selectedUnit,userId:a.userId,userAlias:a.userAlias,placeId:a.placeId,placeName:a.placeName,activePlaceId:a.activePlaceId,activePlaceName:a.activePlaceName}):e&&u(!1)}catch(a){e&&(dt.handleError(a),u(!1))}})(),()=>{e=!1}},[c,u,x]);const N=a.useMemo(()=>({...s,logout:x,processCallback:h,switchUnit:p,availableUnits:s.companies,isSearchVisible:i,setSearchVisible:f,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,x,h,p,i,f,b,v]);return e.jsx(Lt.Provider,{value:N,children:t})},exports.AuthService=Mt,exports.Avatar=mr,exports.AvatarFallback=hr,exports.AvatarImage=pr,exports.Badge=ra,exports.BaseForm=Us,exports.Breadcrumb=xr,exports.BreadcrumbEllipsis=jr,exports.BreadcrumbItem=gr,exports.BreadcrumbLink=br,exports.BreadcrumbList=fr,exports.BreadcrumbPage=vr,exports.BreadcrumbSeparator=Nr,exports.BulkActionBar=Vs,exports.Button=xe,exports.CRUD_CONFIG=ft,exports.Calendar=_r,exports.CallbackPage=()=>{const{processCallback:t}=zt(),[s,r]=a.useState(null),[n,i]=a.useState(!1);a.useEffect(()=>{(async()=>{try{if(await t()){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.")}})()},[t]);const o=async()=>{i(!0),r(null);try{await t()||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(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsxs(ye,{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(Ce,{className:"space-y-4",children:[e.jsx(ar,{variant:"destructive",children:e.jsx(sr,{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(xe,{onClick:o,disabled:n,className:"flex-1",children:n?e.jsxs(e.Fragment,{children:[e.jsx(ia,{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(xe,{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(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),e.jsxs(Ce,{className:"text-center",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx(ia,{size:"lg"})}),e.jsx("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},exports.Card=Ne,exports.CardContent=Ce,exports.CardDescription=we,exports.CardFooter=ke,exports.CardHeader=je,exports.CardSkeleton=os,exports.CardTitle=ye,exports.Cards=function({data:a,renderCard:t,isLoading:s=!1,emptyMessage:r="Nenhum item encontrado",columns:n,gap:i="md",className:o}){return s?e.jsx(Or,{cols:n?String(n):"auto-fit",gap:i,className:o,children:[...Array(6)].map((a,t)=>e.jsx(Da,{className:"h-48 w-full"},t))}):0===a.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(Or,{cols:n?String(n):"auto-fit",gap:i,className:o,children:a.map(t)})},exports.ChatbotPage=function(){const[t,s]=a.useState(!1),[r,n]=a.useState(""),{messages:i,isLoading:o,error:d,sendMessage:c}=Ei(),u=a.useRef(null),m=a.useRef(null);a.useEffect(()=>{if(u.current){const e=u.current.querySelector("[data-radix-scroll-area-viewport]");e&&(e.scrollTop=e.scrollHeight)}},[i]),a.useEffect(()=>{t&&m.current&&m.current.focus()},[t]),a.useEffect(()=>{const e=e=>{"Escape"===e.key&&t&&s(!1)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t]);const p=()=>{r.trim()&&!o&&(c(r),n(""))};return e.jsxs(e.Fragment,{children:[e.jsx(xe,{onClick:()=>s(!t),className:"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg z-50",size:"icon",children:t?e.jsx(l.X,{className:"h-6 w-6"}):e.jsx(l.MessageCircle,{className:"h-6 w-6"})}),t&&e.jsxs(Ne,{className:"fixed bottom-24 right-6 w-96 h-[600px] shadow-xl z-50 flex flex-col",children:[e.jsxs(je,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsx(ye,{className:"text-lg font-semibold",children:"Chat Assistant"}),e.jsx(xe,{variant:"ghost",size:"icon",onClick:()=>s(!1),className:"h-8 w-8",children:e.jsx(l.X,{className:"h-4 w-4"})})]}),e.jsxs(Ce,{className:"flex-1 flex flex-col p-0 overflow-hidden",children:[e.jsx(Rs,{ref:u,className:"flex-1 px-4",children:e.jsxs("div",{className:"space-y-4 py-4",children:[i.map(a=>e.jsx("div",{className:"flex "+("user"===a.role?"justify-end":"justify-start"),children:e.jsx("div",{className:"max-w-[80%] rounded-lg px-4 py-2 "+("user"===a.role?"bg-primary text-primary-foreground":"bg-muted"),children:"assistant"===a.role?e.jsx(Ai,{content:a.content}):e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.content})})},a.id)),o&&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(ge,{ref:m,value:r,onChange:e=>n(e.target.value),onKeyPress:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),p())},placeholder:"Digite sua mensagem...",disabled:o,className:"flex-1"}),e.jsx(xe,{onClick:p,disabled:o||!r.trim(),size:"icon",children:e.jsx(l.Send,{className:"h-4 w-4"})})]})})]})]})]})},exports.Checkbox=aa,exports.Collapsible=Rr,exports.CollapsibleContent=Dr,exports.CollapsibleTrigger=Fr,exports.ColorPicker=_s,exports.Command=Ea,exports.CommandDialog=({children:a,...t})=>e.jsx("div",{...t,children:e.jsx(Ea,{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:a})}),exports.CommandEmpty=Ia,exports.CommandGroup=Pa,exports.CommandInput=Aa,exports.CommandItem=Ra,exports.CommandList=Ta,exports.CommandSeparator=_a,exports.CommandShortcut=Fa,exports.CrudCards=function({manager:a,config:t,onEdit:s,onDelete:r}){return a.isLoading?e.jsx(Or,{children:Array.from({length:3}).map((a,t)=>e.jsxs(Ne,{children:[e.jsxs(je,{children:[e.jsx(Da,{className:"h-4 w-3/4"}),e.jsx(Da,{className:"h-3 w-1/2"})]}),e.jsx(Ce,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Da,{className:"h-3 w-full"}),e.jsx(Da,{className:"h-3 w-2/3"})]})})]},t))}):e.jsx(Mr.Root,{children:a.entities.map(a=>e.jsxs(Mr.Item,{onClick:()=>s(a),children:[e.jsx(je,{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(ye,{className:"text-base leading-6 truncate",children:a.title||a.name||"Sem título"}),e.jsx(we,{className:"text-sm",children:i.format(new Date(a.created_at),"dd/MM/yyyy HH:mm",{locale:Pr})})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-2",children:[a.link&&e.jsx(xe,{variant:"external-link",size:"icon-xs",onClick:e=>{e.stopPropagation(),(e=>{try{const a=window.open(e,"_blank");a&&!a.closed&&void 0!==a.closed||(navigator.clipboard.writeText(e),o.toast.info("Link copiado para a área de transferência"))}catch(a){window.location.href=e}})(a.link)},title:"Abrir link externo",children:e.jsx(l.ExternalLink,{className:"h-4 w-4"})}),e.jsx("div",{onClick:e=>e.stopPropagation(),children:e.jsx(Ss,{onEdit:()=>s(a),onDelete:r?()=>r(a):void 0,canDelete:!!r})})]})]})}),e.jsx(Ce,{className:"pt-0",children:e.jsx("div",{className:"space-y-2",children:t.cardFields?.map(t=>{const s=a[t.key];return s?e.jsx(Mr.Field,{label:t.label,value:t.render?t.render(s,a):String(s)},String(t.key)):null})})})]},a.id))})},exports.CrudPageInternal=Gs,exports.CrudPagination=qs,exports.CrudPrimitiveFilterBar=function({searchValue:a="",onSearchChange:t,customFilters:s=[],onClearFilters:r,showClearButton:n=!0,layout:i="horizontal"}){const o=a||s.length>0;return e.jsxs("div",{className:`flex ${"vertical"===i?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[t&&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(ge,{type:"text",placeholder:"Buscar...",value:a,onChange:e=>t(e.target.value),className:"pl-9 h-9"})]}),s.map((a,t)=>e.jsx("div",{className:"vertical"===i?"w-full":"",children:a},t)),n&&o&&r&&e.jsxs(xe,{variant:"ghost",size:"sm",onClick:r,className:"h-9 px-3 whitespace-nowrap",children:[e.jsx(l.X,{size:14,className:"mr-1"}),"Limpar"]})]})},exports.CrudPrimitivePagination=$s,exports.CrudPrimitiveTable=function({data:t,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:x,onSelectAll:f,isAllSelected:g=!1}){const b=a.useMemo(()=>{const e=s.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return s.map(a=>{if(a.width)return`${a.width}px`;if(a.minWidth&&!a.weight)return`${a.minWidth}px`;const t=(a.weight??1)/e*100;return a.minWidth?`minmax(${a.minWidth}px, ${t}%)`:`${t}%`})},[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((a,t)=>e.jsx(Da,{className:"h-12 w-full"},t))})}):0===t.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(Yt,{className:m,children:[e.jsx(Zt,{className:"sticky top-0 bg-background z-10",children:e.jsxs(ts,{children:[p&&e.jsx(ss,{className:"w-[40px]",children:e.jsx(aa,{checked:g,onCheckedChange:f,"aria-label":"Selecionar todos"})}),s.map((a,t)=>{return e.jsx(ss,{className:a.className,style:{width:b[t]},children:a.sortable&&i?e.jsxs("button",{onClick:()=>i(String(a.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[a.header,(s=String(a.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:a.header})},String(a.key));var s}),d&&e.jsx(ss,{className:"w-[80px] text-right",children:"Ações"})]})}),e.jsx(es,{children:t.map(a=>e.jsxs(ts,{onClick:()=>o?.(a),className:o?"cursor-pointer":"",children:[p&&e.jsx(rs,{children:e.jsx(aa,{checked:h.includes(a.id),onCheckedChange:()=>x?.(a.id),onClick:e=>e.stopPropagation(),"aria-label":`Selecionar item ${a.id}`})}),s.map(t=>e.jsx(rs,{className:t.className,children:t.render?t.render(a):String(a[t.key]??"-")},String(t.key))),d&&e.jsx(rs,{className:"text-right",onClick:e=>e.stopPropagation(),children:d(a)})]},a.id))})]})})},exports.CrudTable=Ts,exports.DataList=Mr,exports.DeleteConfirmationDialog=Jt,exports.Dialog=Se,exports.DialogClose=Te,exports.DialogContent=Pe,exports.DialogDescription=De,exports.DialogFooter=Re,exports.DialogHeader=_e,exports.DialogOverlay=Ie,exports.DialogPortal=Ae,exports.DialogTitle=Fe,exports.DialogTrigger=Ee,exports.DropdownMenu=cs,exports.DropdownMenuCheckboxItem=Ns,exports.DropdownMenuContent=bs,exports.DropdownMenuGroup=ms,exports.DropdownMenuItem=vs,exports.DropdownMenuLabel=ys,exports.DropdownMenuPortal=ps,exports.DropdownMenuRadioGroup=xs,exports.DropdownMenuRadioItem=js,exports.DropdownMenuSeparator=ws,exports.DropdownMenuShortcut=Cs,exports.DropdownMenuSub=hs,exports.DropdownMenuSubContent=gs,exports.DropdownMenuSubTrigger=fs,exports.DropdownMenuTrigger=us,exports.EmailService=ki,exports.EmptyState=ds,exports.EntitySelect=Ls,exports.ErrorBoundary=Ci,exports.FilterBar=Ks,exports.Form=Me,exports.FormControl=qe,exports.FormDescription=Ve,exports.FormField=({...a})=>e.jsx(Le.Provider,{value:{name:a.name},children:e.jsx(u.Controller,{...a})}),exports.FormItem=Ue,exports.FormLabel=$e,exports.FormMessage=Be,exports.FormSkeleton=function({fields:a=4}){return e.jsxs("div",{className:"space-y-4",children:[Array.from({length:a}).map((a,t)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(Da,{className:"h-4 w-24"}),e.jsx(Da,{className:"h-10 w-full"})]},t)),e.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[e.jsx(Da,{className:"h-10 w-20"}),e.jsx(Da,{className:"h-10 w-20"})]})]})},exports.Grid=Or,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(Da,{className:"h-8 w-8 rounded-full"}),e.jsx(Da,{className:"h-6 w-32"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Da,{className:"h-8 w-8"}),e.jsx(Da,{className:"h-8 w-24"})]})]})},exports.IconPicker=Ms,exports.ImageEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const[c,u]=a.useState(t||{alignment:"center",allowDownload:!1}),m=a.useRef(null),{upload:p,uploading:h}=Zi({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),x=(e,a)=>{const t={...c,[e]:a};u(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"URL da imagem"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:c.imageUrl||"",onChange:e=>x("imageUrl",e.target.value),className:"flex-1"}),i&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:m,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await p(a),t={...c,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};u(t),s(t)}catch(t){}finally{m.current&&(m.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>m.current?.click(),disabled:h,children:h?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),c.imageFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.imageFile," (",Math.round((c.imageSize||0)/1024)," KB)"]})]}),c.imageUrl&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:e.jsx("div",{className:"flex "+("left"===c.alignment?"justify-start":"right"===c.alignment?"justify-end":"justify-center"),children:e.jsx("img",{src:c.imageUrl,alt:c.alt||"Preview",style:{width:c.width?`${c.width}px`:"auto",height:c.height?`${c.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"caption",children:"Legenda (opcional)"}),e.jsx(ta,{id:"caption",placeholder:"Descrição da imagem",value:c.caption||"",onChange:e=>x("caption",e.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"alt",children:"Texto alternativo (acessibilidade)"}),e.jsx(ge,{id:"alt",placeholder:"Descrição para leitores de tela",value:c.alt||"",onChange:e=>x("alt",e.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Alinhamento"}),e.jsxs(We,{value:c.alignment||"center",onValueChange:e=>x("alignment",e),children:[e.jsx(Ke,{children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"left",children:"Esquerda"}),e.jsx(Ze,{value:"center",children:"Centro"}),e.jsx(Ze,{value:"right",children:"Direita"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"width",children:"Largura (px, opcional)"}),e.jsx(ge,{id:"width",type:"number",placeholder:"Auto",value:c.width||"",onChange:e=>x("width",e.target.value?Number(e.target.value):void 0)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"height",children:"Altura (px, opcional)"}),e.jsx(ge,{id:"height",type:"number",placeholder:"Auto",value:c.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:c.allowDownload||!1,onChange:e=>x("allowDownload",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download da imagem"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(xe,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(xe,{onClick:()=>{c.imageUrl?r(c):ha({title:"Erro",description:"Adicione uma URL ou faça upload de uma imagem",variant:"destructive"})},disabled:!c.imageUrl,children:"Salvar"})]})]})},exports.ImageRenderer=function({content:a,className:t="",style:s}){if(!a.imageUrl)return null;const r={left:"justify-start",center:"justify-center",right:"justify-end"}[a.alignment||"center"];return e.jsx("div",{className:`flex ${r} my-4 ${t}`,style:s,children:e.jsxs("div",{className:"space-y-2 max-w-full",children:[e.jsx("img",{src:a.imageUrl,alt:a.alt||"",style:{width:a.width?`${a.width}px`:"auto",height:a.height?`${a.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"}),a.caption&&e.jsx("p",{className:"text-sm text-muted-foreground text-center italic",children:a.caption}),a.allowDownload&&a.imageUrl&&e.jsxs("a",{href:a.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.Input=ge,exports.Label=ve,exports.LeaderRow=Vi,exports.LeadershipDialog=Xi,exports.LeadershipForm=Gi,exports.LeadershipPage=function(){const{alias:t}=zt(),{data:s,isLoading:r,error:n,refetch:i}=Mi(),{data:o=[]}=zs(),[d,c]=a.useState(()=>t?(e=>{try{const a=localStorage.getItem(`${Ji}-${e}`);if(a)return new Set(JSON.parse(a))}catch(n){}return new Set})(t):new Set),[u,m]=a.useState(!1),[p,h]=a.useState(),[x,f]=a.useState(null),g=o.length-(s?new Set(Di(s).map(e=>e.id_user)).size:0);a.useEffect(()=>{if(s&&s.length>0&&t){if(!localStorage.getItem(`${Ji}-${t}`)){const e=s.map(e=>e.id),a=new Set(e);c(a),Yi(t,a)}}},[s,t]);const b=e=>{c(a=>{const s=new Set(a);return s.has(e)?s.delete(e):s.add(e),t&&Yi(t,s),s})},v=e=>{h(e),f(null),m(!0)};return r?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:"Carregando hierarquia de liderança..."})]})}):n?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(xe,{onClick:()=>i(),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(xe,{size:"sm",onClick:()=>{h(void 0),f(null),m(!0)},children:[e.jsx(l.Plus,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),e.jsxs(xe,{variant:"outline",size:"sm",onClick:()=>{if(!s)return;const e=Di(s).filter(e=>e.children.length>0).map(e=>e.id),a=new Set(e);c(a),t&&Yi(t,a)},disabled:!s||0===s.length,children:[e.jsx(l.ChevronDown,{className:"h-4 w-4 mr-2"}),"Expandir todos"]}),e.jsxs(xe,{variant:"outline",size:"sm",onClick:()=>{const e=new Set;c(e),t&&Yi(t,e)},disabled:!s||0===s.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:[g," usuário",1!==g?"s":""," não associado",1!==g?"s":""]})]})})]})}),s&&0!==s.length?e.jsx(Rs,{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:s.map(a=>e.jsx(Vi,{leader:a,expandedIds:d,onToggleExpand:b,onEdit:v},a.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(Xi,{open:u,onOpenChange:()=>{m(!1),h(void 0),f(null)},leader:p,prefilledLeaderId:x,title:p?"Editar Líder":x?"Adicionar Liderado":"Adicionar Líder Raiz"},`leadership-dialog-${t}`)]})},exports.LoadingState=function({isLoading:a,children:t,className:s,type:r="spinner",size:n="md"}){return a?"overlay"===r?e.jsxs("div",{className:me("relative",s),children:[t,e.jsx("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsx(ia,{size:n})})]}):"skeleton"===r?e.jsx("div",{className:me("animate-pulse",s),children:e.jsx("div",{className:"bg-muted rounded-md h-full w-full"})}):e.jsx("div",{className:me("flex items-center justify-center py-8",s),children:e.jsx(ia,{size:n})}):e.jsx(e.Fragment,{children:t})},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(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),e.jsxs(Ce,{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),e.jsx(xe,{onClick:async()=>{bt()?await Mt.loginDev():Mt.loginProd()},className:"w-full",size:"lg",children:bt()?"Login Desenvolvimento":"Entrar com Qualiex"})]})]})}),exports.MESSAGES=jt,exports.ManageAccessModal=Ti,exports.MarkdownMessage=Ai,exports.MultiSelect=za,exports.NavigationProvider=si,exports.PageBreadcrumb=function({items:a,maxItems:t=3,className:s}){return a.length>t&&(a[0],a.slice(-(t-1))),a.length,e.jsx(xr,{className:s})},exports.PageMetadataProvider=nr,exports.Pagination=qr,exports.PaginationContent=Vr,exports.PaginationEllipsis=Kr,exports.PaginationItem=Br,exports.PaginationLink=Wr,exports.PaginationNext=Qr,exports.PaginationPrevious=Hr,exports.PlaceCard=Ii,exports.PlacesList=function({places:a,isLoading:t,manageAccessConfig:s}){return t?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:"Carregando locais..."})]})}):a&&0!==a.length?e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),a.map(a=>e.jsx(Ii,{place:a,manageAccessConfig:s},a.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=Ca,exports.PopoverContent=Sa,exports.PopoverTrigger=ka,exports.Progress=Gr,exports.ProtectedRoute=({children:t})=>{const{isAuthenticated:s,isLoading:r}=zt();if(a.useEffect(()=>{if(!s)return;const e=()=>{Ka.areAllTokensValid()||Mt.logout()};e();const a=setInterval(e,3e5);return()=>clearInterval(a)},[s]),a.useEffect(()=>{if(r)return;if(s)return;if(Ka.isManualLogout())return void(window.location.href="/login");const e=new URLSearchParams(window.location.search),a=window.location.hash.startsWith("#")?window.location.hash.substring(1):window.location.hash,t=new URLSearchParams(a);if(e.has("access_token")||t.has("access_token"))return;const n=bt();(async()=>{n?await Mt.loginDev():Mt.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(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Carregando..."})}),e.jsxs(Ce,{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(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Processando..."})}),e.jsxs(Ce,{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(Ka.areAllTokensValid())return e.jsx(e.Fragment,{children:t})}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(Ne,{className:"w-full max-w-md",children:[e.jsx(je,{className:"text-center",children:e.jsx(ye,{className:"text-xl font-semibold",children:"Iniciando..."})}),e.jsxs(Ce,{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:bt()?"Fazendo login automático...":"Redirecionando para autenticação..."})]})]})})}return e.jsx(e.Fragment,{children:t})},exports.QUALIEX_CONFIG=vt,exports.QUERY_KEYS={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},exports.QualiexEnrichmentService=Et,exports.QualiexErrorInterceptor=ut,exports.QualiexUserField=Os,exports.RadioGroup=Xr,exports.RadioGroupItem=Jr,exports.ResizableRail=vi,exports.SEARCH_CONFIG=gt,exports.ScrollArea=Rs,exports.ScrollBar=Fs,exports.Select=We,exports.SelectContent=Je,exports.SelectGroup=He,exports.SelectItem=Ze,exports.SelectLabel=Ye,exports.SelectScrollDownButton=Xe,exports.SelectScrollUpButton=Ge,exports.SelectSearch=function({multiple:a=!1,options:t=[],value:s,onChange:r,getOptionValue:n=e=>e.value,getOptionLabel:i=e=>e.label,placeholder:o="Selecione...",label:d,icon:c,emptyMessage:u="Nenhum item disponível.",searchPlaceholder:m="Buscar...",disabled:p=!1,required:h=!1,isLoading:x=!1,error:f,className:g,sortOptions:b=!0,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y}){if(x)return e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx(Da,{className:"h-10 w-full"})]});const w="string"==typeof f?f:f?"Erro ao carregar dados":void 0;return w?e.jsxs("div",{className:me("space-y-2",g),children:[d&&e.jsxs(ve,{children:[d,h&&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:w})]})]}):e.jsx($r,{multiple:a,options:t,value:s||(a?[]:""),onChange:r,getOptionValue:n,getOptionLabel:i,placeholder:o,label:d,icon:c,emptyMessage:u,searchPlaceholder:m,disabled:p,required:h,className:g,sortOptions:b,maxDisplayedBadges:v,popoverContainer:N,onOpen:j,onClose:y})},exports.SelectSeparator=ea,exports.SelectTrigger=Ke,exports.SelectValue=Qe,exports.Separator=Yr,exports.Sheet=Zr,exports.SheetClose=an,exports.SheetContent=nn,exports.SheetDescription=cn,exports.SheetFooter=ln,exports.SheetHeader=on,exports.SheetOverlay=sn,exports.SheetPortal=tn,exports.SheetTitle=dn,exports.SheetTrigger=en,exports.Sidebar=vn,exports.SidebarContent=En,exports.SidebarFooter=kn,exports.SidebarGroup=An,exports.SidebarGroupAction=In,exports.SidebarGroupContent=Pn,exports.SidebarGroupLabel=Tn,exports.SidebarHeader=gi,exports.SidebarInput=wn,exports.SidebarInset=yn,exports.SidebarMenu=_n,exports.SidebarMenuAction=Mn,exports.SidebarMenuBadge=Ln,exports.SidebarMenuButton=Dn,exports.SidebarMenuItem=Rn,exports.SidebarMenuSkeleton=zn,exports.SidebarMenuSub=On,exports.SidebarMenuSubButton=$n,exports.SidebarMenuSubItem=Un,exports.SidebarProvider=bn,exports.SidebarRail=jn,exports.SidebarSeparator=Sn,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(Da,{className:"h-8 w-32 mb-6"}),e.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((a,t)=>e.jsxs("div",{className:"flex items-center space-x-3 p-2",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx(Da,{className:"h-4 w-20"})]},t))})]})})},exports.SidebarTrigger=Nn,exports.Skeleton=Da,exports.Slider=qn,exports.SonnerToaster=({...a})=>{const{theme:t="system"}=_.useTheme();return e.jsx(o.Toaster,{theme:t,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"}},...a})},exports.Spinner=ia,exports.Stack=Qs,exports.StatusSelect=function({value:a,onChange:t,activeLabel:s="Ativo",inactiveLabel:r="Inativo",allLabel:n="[Todos]",placeholder:i="Status",className:o="w-full sm:w-[180px]"}){const l=[{id:"active",name:s},{id:"inactive",name:r},{id:"all",name:n}];return e.jsx(Ls,{value:a,onChange:e=>t(e),items:l,getItemValue:e=>e.id,getItemLabel:e=>e.name,placeholder:i,className:o})},exports.Switch=Vn,exports.TabPageContent=function({children:a,className:t}){return e.jsx("div",{className:me("space-y-6",t),children:a})},exports.TabPageHeader=function({title:a,description:t,actions:s,className:r}){return e.jsxs("div",{className:me("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:a}),t&&e.jsx("p",{className:"text-muted-foreground text-sm",children:t})]}),s&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s})]}),e.jsx(Yr,{})]})},exports.TabPageLayout=function({children:a,className:t}){return e.jsx("div",{className:me("flex flex-col h-full",t),children:e.jsx(Rs,{className:"flex-1",children:e.jsx("div",{className:"space-y-6 p-6",children:a})})})},exports.Table=Yt,exports.TableBody=es,exports.TableCaption=ns,exports.TableCell=rs,exports.TableFooter=as,exports.TableHead=ss,exports.TableHeader=Zt,exports.TableRow=ts,exports.TableRowActions=Ss,exports.TableSkeleton=is,exports.Tabs=Bn,exports.TabsContent=Qn,exports.TabsList=Wn,exports.TabsTrigger=Hn,exports.Textarea=ta,exports.Toast=va,exports.ToastAction=Na,exports.ToastClose=ja,exports.ToastDescription=wa,exports.ToastProvider=fa,exports.ToastTitle=ya,exports.ToastViewport=ga,exports.Toaster=function(){const{toasts:a}=xa();return e.jsxs(fa,{children:[a.map(function({id:a,title:t,description:s,action:r,...n}){return e.jsxs(va,{...n,children:[e.jsxs("div",{className:"grid gap-1",children:[t&&e.jsx(ya,{children:t}),s&&e.jsx(wa,{children:s})]}),r,e.jsx(ja,{})]},a)}),e.jsx(ga,{})]})},exports.Toggle=Gn,exports.ToggleGroup=Jn,exports.ToggleGroupItem=Yn,exports.TokenManager=Ka,exports.TokenService=Ua,exports.Tooltip=mn,exports.TooltipContent=hn,exports.TooltipProvider=un,exports.TooltipTrigger=pn,exports.VideoEditor=function({value:t,onChange:s,onSubmit:r,onCancel:n,uploadFunction:i,deleteFunction:o,uploadOptions:d}){const[c,u]=a.useState(t||{inputType:"url",controls:!0}),m=a.useRef(null),p=a.useRef(null),{upload:h,uploading:x}=Zi({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["video/*"],maxSize:104857600}}),{upload:f,uploading:g}=Zi({uploadFunction:i,deleteFunction:o,defaultOptions:{...d,allowedTypes:["image/*"],maxSize:5242880}}),b=a.useMemo(()=>no(c.videoUrl||ro(c.embedCode)||""),[c.videoUrl,c.embedCode]),v=(e,a)=>{const t={...c,[e]:a};u(t),s(t)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Tipo de entrada"}),e.jsxs(We,{value:c.inputType||"url",onValueChange:e=>v("inputType",e),children:[e.jsx(Ke,{children:e.jsx(Qe,{})}),e.jsxs(Je,{children:[e.jsx(Ze,{value:"url",children:"URL (YouTube/Vimeo/arquivo)"}),e.jsx(Ze,{value:"upload",children:"Upload de arquivo"}),e.jsx(Ze,{value:"embed",children:"Código de incorporação (iframe)"})]})]})]}),"embed"!==c.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"URL do vídeo"}),e.jsx(ge,{type:"url",placeholder:"https://www.youtube.com/watch?v=... ou arquivo direto",value:c.videoUrl||"",onChange:e=>v("videoUrl",e.target.value)})]}),"upload"===c.inputType&&i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Arquivo de vídeo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:m,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await h(a),t={...c,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:c.title||a.name.replace(/\.[^/.]+$/,"")};u(t),s(t)}catch(t){}finally{m.current&&(m.current.value="")}},className:"hidden"}),e.jsx(xe,{type:"button",variant:"outline",onClick:()=>m.current?.click(),disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(l.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),c.videoFile&&e.jsxs("span",{className:"text-xs text-muted-foreground truncate self-center",children:[c.videoFile," (",Math.round((c.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===c.inputType&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Código embed (iframe)"}),e.jsx(ta,{placeholder:'<iframe src="https://www.youtube.com/embed/..." ...></iframe>',value:c.embedCode||"",onChange:e=>v("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),i&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Thumbnail/Poster (opcional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ge,{type:"url",placeholder:"https://exemplo.com/thumbnail.jpg",value:c.thumbnail||"",onChange:e=>v("thumbnail",e.target.value),className:"flex-1"}),e.jsx("input",{ref:p,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await f(a),t={...c,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};u(t),s(t)}catch(t){}finally{p.current&&(p.current.value="")}},className:"hidden"}),e.jsx(xe,{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"}),"Enviando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(l.Upload,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),c.thumbnailFile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",c.thumbnailFile]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{htmlFor:"title",children:"Título (opcional)"}),e.jsx(ge,{id:"title",placeholder:"Título do vídeo",value:c.title||"",onChange:e=>v("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:c.autoplay||!1,onChange:e=>v("autoplay",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay (mudo em embeds)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"controls",type:"checkbox",checked:!1!==c.controls,onChange:e=>v("controls",e.target.checked),className:"h-4 w-4"}),e.jsx(ve,{htmlFor:"controls",className:"cursor-pointer",children:"Mostrar controles"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ve,{children:"Preview"}),e.jsx("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const a=c.videoUrl||ro(c.embedCode)||"";if(!a)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Adicione uma URL, faça upload ou insira um código embed para visualizar"});if("file"===b)return e.jsxs("video",{controls:!1!==c.controls,autoPlay:c.autoplay,poster:c.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[e.jsx("source",{src:a}),"Seu navegador não suporta vídeos HTML5."]});const t="youtube"===b?ao(a,c.autoplay):so(a,c.autoplay);return e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{title:c.title||"Vídeo",src:t,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(xe,{variant:"outline",onClick:n,children:"Cancelar"}),e.jsx(xe,{onClick:()=>{c.videoUrl||c.embedCode?r(c):ha({title:"Erro",description:"Adicione uma URL, faça upload de um vídeo ou insira um código embed",variant:"destructive"})},disabled:!(c.videoUrl||c.embedCode),children:"Salvar"})]})]})},exports.VideoRenderer=function({content:a,className:t="",style:s}){const r=a.videoUrl||ro(a.embedCode)||"";if(!r)return null;const n=no(r);return e.jsx(Ne,{className:`overflow-hidden my-4 ${t}`,style:s,children:e.jsxs(Ce,{className:"p-0",children:["file"===n?e.jsxs("video",{controls:!1!==a.controls,autoPlay:a.autoplay,poster:a.thumbnail,className:"w-full h-auto",playsInline:!0,muted:a.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:a.title||"Vídeo",src:"youtube"===n?ao(r,a.autoplay):so(r,a.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),a.title&&e.jsx("div",{className:"p-4",children:e.jsx("p",{className:"text-sm font-medium",children:a.title})})]})})},exports.assets=hi,exports.badgeVariants=sa,exports.buildHierarchy=Fi,exports.buttonVariants=he,exports.calculateAspectRatio=io,exports.cn=me,exports.createCrudPage=function(a){return({manager:t})=>{const{manager:s,config:r,onSave:n,onEdit:i,onToggleStatus:o}=a,l=t??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(Gs,{manager:l,config:d,formSections:r.formSections,onSave:n,onToggleStatus:o,defaultSort:r.defaultSort})}},exports.createCrudRoutingConfig=function(e,a){const t=ei({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}},exports.createRoutingHandlers=ei,exports.createService=It,exports.createSimpleSaveHandler=function(e,a,t){return s=>{if(s.id){const a=t(s);e.updateEntity(s.id,a)}else{const t=a(s);e.createEntity(t)}}},exports.createSimpleService=function(e){const a=It({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:a,useCrudHook:(t,s)=>Ot({queryKey:e.tableName,service:{...a,getAll:async(e={})=>await a.getAll({...e})},entityName:e.entityName,additionalFilters:t,onSuccess:s})}},exports.crudPresets=Zs,exports.debounce=(e,a)=>{let t;return(...s)=>{clearTimeout(t),t=setTimeout(()=>e(...s),a)}},exports.deriveEmailField=wt,exports.deriveNameField=yt,exports.deriveUsernameField=Ct,exports.detectVideoProvider=no,exports.emailService=Si,exports.errorService=Ja,exports.extractImageFileName=function(e){try{const a=new URL(e),t=a.pathname.split("/");return t[t.length-1]||"image"}catch{const a=e.split("/");return a[a.length-1]||"image"}},exports.extractVimeoId=to,exports.extractYouTubeId=eo,exports.flattenTree=Di,exports.formatCurrency=e=>null==e?"R$ 0,00":new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL",minimumFractionDigits:2,maximumFractionDigits:2}).format(e),exports.formatDatetime=e=>{if(!e)return"";const a=i.parseISO(e);if(!i.isValid(a))return"Data inválida";return`${a.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"})} ${a.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`},exports.formatFileSize=function(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`},exports.generateCrudConfig=Xs,exports.getQualiexConfig=Nt,exports.getSupabaseClient=rt,exports.handleExternalLink=ue,exports.isDevEnvironment=bt,exports.isImageUrl=function(e){const a=e.toLowerCase();return[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"].some(e=>a.includes(e))},exports.logoSrc=xi,exports.normalizeVideoUrl=function(e,a,t){switch(a||no(e)){case"youtube":return ao(e,t);case"vimeo":return so(e,t);default:return e}},exports.normalizeVimeoUrl=so,exports.normalizeYouTubeUrl=ao,exports.parseIframeSrc=ro,exports.placeService=Ri,exports.qualiexApi=ht,exports.resizeKeepingAspect=function(e,a,t,s){const r=io(e,a);return t&&!s?{width:t,height:Math.round(t/r)}:s&&!t?{width:Math.round(s*r),height:s}:{width:e,height:a}},exports.resolveFieldMappings=kt,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=fi,exports.toast=ha,exports.toggleVariants=Kn,exports.trimTextFields=pe,exports.useActiveModules=di,exports.useAuth=zt,exports.useBaseForm=Is,exports.useCreateLeaderMutation=function(){const e="common",{alias:a}=zt(),t=g.useQueryClient(),s=rt();return g.useMutation({mutationFn:async t=>{if(!a)throw new Error("Unidade não selecionada");if(t.id_user===t.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",a).eq("id_user",t.id_user).eq("is_removed",!1).maybeSingle()).data)throw new Error("Este usuário já está cadastrado como líder");t.id_leader&&await qi(s,a,e,t.id_user,t.id_leader);const{data:r,error:n}=await s.schema(e).from("leaders").insert({alias:a,id_user:t.id_user,id_leader:t.id_leader,is_active:!0,is_removed:!1}).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["leadership",a]}),o.toast.success("Líder adicionado com sucesso")},onError:e=>{o.toast.error(e.message||"Erro ao adicionar líder")}})},exports.useCreateMultipleLeadersMutation=zi,exports.useCreateSingleLeaderMutation=Li,exports.useCrud=Ot,exports.useDebounce=ii,exports.useFormField=ze,exports.useLeadershipApi=Mi,exports.useMediaUpload=Zi,exports.useNavigation=ri,exports.useOpenAIChat=Ei,exports.usePageMetadata=function(e){const{setMetadata:t,clearMetadata:s}=ir();a.useEffect(()=>(t(e),()=>s()),[e.title,e.subtitle,t,s])},exports.usePageTitle=ni,exports.usePermissionQuery=li,exports.useQualiexUsers=zs,exports.useRemoveLeaderMutation=Ui,exports.useRouteBreadcrumbs=function(){const e=b.useLocation();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let s="";return a.forEach((e,r)=>{s+=`/${e}`;const n=r===a.length-1,i=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:i,href:n?void 0:s,isCurrentPage:n})}),t})()},exports.useSidebar=gn,exports.useSidebarResize=bi,exports.useSyncSubordinatesMutation=$i,exports.useToast=xa,exports.useUpdateLeaderMutation=Oi,exports.withPreset=function(e,a,t={}){const s=Zs[e];return Xs(s.title,a,{...s,...t})};
|