forlogic-core 2.2.4 → 2.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"i18next";export{default as i18n}from"i18next";import{jsx as a,jsxs as t,Fragment as r}from"react/jsx-runtime";import*as n from"react";import i,{useState as o,useMemo as s,useCallback as l,createContext as d,useContext as c,useRef as u,useEffect as m,memo as p,Component as h,forwardRef as f}from"react";import{Slot as g}from"@radix-ui/react-slot";import{cva as v}from"class-variance-authority";import{clsx as b}from"clsx";import{twMerge as x}from"tailwind-merge";import{getDefaultOptions as y,parseISO as N,isValid as w,format as _}from"date-fns";import{toast as C,Toaster as k}from"sonner";export{toast as sonnerToast,toast}from"sonner";import*as S from"lucide-react";import{EllipsisVertical as A,X as E,ChevronDown as D,ChevronUp as P,Check as I,Loader2 as T,Loader2Icon as R,OctagonXIcon as M,TriangleAlertIcon as L,InfoIcon as z,CircleCheckIcon as F,ChevronRight as U,Circle as j,AlertCircle as O,Search as B,FileX as $,Edit as V,PowerOff as q,Power as W,Trash2 as H,Pencil as G,ToggleRight as K,ToggleLeft as Y,Plus as Q,LayoutGrid as X,List as J,Table2 as Z,Columns3 as ee,GripVertical as ae,Group as te,ArrowUp as re,ArrowDown as ne,ChevronsLeft as ie,ChevronLeft as oe,ChevronsRight as se,CheckCircle as le,AlertTriangle as de,Info as ce,RefreshCw as ue,Copy as me,ExternalLink as pe,NotebookText as he,Building2 as fe,User as ge,LogOut as ve,Sparkles as be,MoreHorizontal as xe,Calendar as ye,PanelLeft as Ne,Edit3 as we,Code as _e,Eye as Ce,Heading1 as ke,Heading2 as Se,Heading3 as Ae,Bold as Ee,Italic as De,Underline as Pe,Strikethrough as Ie,ListOrdered as Te,Highlighter as Re,Link as Me,RemoveFormatting as Le,Undo as ze,Redo as Fe,ImageIcon as Ue,ArrowLeft as je,ArrowRight as Oe,FileText as Be,FileSpreadsheet as $e,Image as Ve,FileImage as qe,Clock as We,Lock as He,ShieldCheck as Ge,Mail as Ke,Coffee as Ye,CheckCheck as Qe,Star as Xe,Download as Je,Users as Ze,TriangleAlert as ea,CheckCircle2 as aa,Hourglass as ta,MoreVertical as ra,Minus as na,CornerDownRight as ia,ChevronsUpDown as oa,ChevronsDownUp as sa,ZoomOut as la,ZoomIn as da,Maximize2 as ca,Undo2 as ua,Redo2 as ma,ArrowUpToLine as pa,Camera as ha,UserPen as fa,Menu as ga,Crown as va,UserPlus as ba,Settings as xa,Upload as ya,Pause as Na,Play as wa,MessageSquare as _a,Smartphone as Ca,Paperclip as ka,CloudUpload as Sa,RotateCcw as Aa,Filter as Ea,Layers as Da,MapPin as Pa,XCircle as Ia,Shield as Ta}from"lucide-react";import*as Ra from"@radix-ui/react-label";import*as Ma from"@radix-ui/react-dialog";import*as La from"@radix-ui/react-separator";import*as za from"@radix-ui/react-alert-dialog";import{useFormContext as Fa,FormProvider as Ua,Controller as ja,appendErrors as Oa,useForm as Ba}from"react-hook-form";import*as $a from"@radix-ui/react-select";import*as Va from"@radix-ui/react-checkbox";import*as qa from"@radix-ui/react-dropdown-menu";import*as Wa from"@radix-ui/react-tooltip";import*as Ha from"@radix-ui/react-popover";import{useTranslation as Ga,initReactI18next as Ka,I18nextProvider as Ya}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import{createClient as Qa}from"@supabase/supabase-js";import{useQueryClient as Xa,useQuery as Ja,useMutation as Za,QueryClient as et,QueryClientProvider as at}from"@tanstack/react-query";import{useSearchParams as tt,useParams as rt,useNavigate as nt,useLocation as it,Navigate as ot,Link as st}from"react-router-dom";import*as lt from"@radix-ui/react-context-menu";import*as dt from"@radix-ui/react-toggle-group";import*as ct from"@radix-ui/react-toggle";import*as ut from"@radix-ui/react-scroll-area";import*as mt from"@radix-ui/react-switch";import*as pt from"@radix-ui/react-collapsible";import*as ht from"@radix-ui/react-tabs";import*as ft from"@radix-ui/react-accordion";import*as gt from"@radix-ui/react-avatar";import{DayPicker as vt}from"react-day-picker";import{Drawer as bt}from"vaul";import*as xt from"@radix-ui/react-hover-card";import*as yt from"@radix-ui/react-navigation-menu";import*as Nt from"@radix-ui/react-progress";import*as wt from"@radix-ui/react-radio-group";import*as _t from"react-resizable-panels";import*as Ct from"@radix-ui/react-slider";import*as kt from"@radix-ui/react-menubar";import*as St from"recharts";import{ResponsiveContainer as At,XAxis as Et,YAxis as Dt,CartesianGrid as Pt,Tooltip as It,Legend as Tt,BarChart as Rt,Bar as Mt,AreaChart as Lt,Area as zt,LineChart as Ft,Line as Ut,PieChart as jt,Pie as Ot,Cell as Bt,ComposedChart as $t}from"recharts";import{useEditor as Vt,EditorContent as qt}from"@tiptap/react";import Wt from"@tiptap/starter-kit";import Ht from"@tiptap/extension-underline";import Gt from"@tiptap/extension-link";import{TextStyle as Kt}from"@tiptap/extension-text-style";import{Color as Yt}from"@tiptap/extension-color";import Qt from"@tiptap/extension-highlight";import{useSensors as Xt,useSensor as Jt,PointerSensor as Zt,DndContext as er,closestCenter as ar}from"@dnd-kit/core";import{SortableContext as tr,rectSortingStrategy as rr,useSortable as nr}from"@dnd-kit/sortable";import{z as ir}from"zod";import{validateFieldsNatively as or,toNestErrors as sr}from"@hookform/resolvers";const lr="ccjfvpnndclajkleyqkc",dr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},cr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function ur(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===lr?dr:cr}function mr(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==lr}const pr={get oauth(){const e=ur();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},hr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},fr={debounceDelay:500},gr=()=>{const e=window.location.origin,a=(()=>{try{return window.self!==window.top}catch{return!0}})();return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("lovable.dev")||e.includes("lovable.app")&&a||import.meta.env.DEV},vr=()=>gr(),br=gr,xr=()=>ur().qualiexApiUrl,yr={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Nr={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},wr={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},_r={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}`}},Cr=a=>({success:{created:a=>e.t("msg_created_success",`${a} criado com sucesso`).replace("{{entity}}",a),updated:a=>e.t("msg_updated_success",`${a} atualizado com sucesso`).replace("{{entity}}",a),deleted:a=>e.t("msg_deleted_success",`${a} removido com sucesso`).replace("{{entity}}",a)},error:{create:a=>e.t("msg_create_error",`Erro ao criar ${a}`).replace("{{entity}}",a),update:a=>e.t("msg_update_error",`Erro ao atualizar ${a}`).replace("{{entity}}",a),delete:a=>e.t("msg_delete_error",`Erro ao remover ${a}`).replace("{{entity}}",a),load:a=>e.t("msg_load_error",`Erro ao carregar ${a}`).replace("{{entity}}",a)}}),kr=`https://${ur().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,Sr={logo:wr.isQualiex?`${kr}/logo-qualiex-white.svg`:`${kr}/saber-gestao-white.png`,smallLogo:wr.isQualiex?`${kr}/logo-forlogic-white.svg`:`${kr}/small.svg`,favicon:`${kr}/favicon.png`},Ar=Sr.logo,Er=Sr.smallLogo;if("undefined"!=typeof document){document.querySelectorAll("link[rel='icon'], link[rel='shortcut icon']").forEach(e=>e.remove());const e=document.createElement("link");e.rel="icon",e.type="image/png",e.href=Sr.favicon,document.head.appendChild(e)}const Dr={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}};function Pr(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Ir={date:Pr({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Pr({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:Pr({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Tr={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Rr(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,n=t?.width?String(t.width):a;r=e.formattingValues[n]||e.formattingValues[a]}else{const a=e.defaultWidth,n=t?.width?String(t.width):e.defaultWidth;r=e.values[n]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}function Mr(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=a.match(n);if(!i)return null;const o=i[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(s,e=>e.test(o)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(s,e=>e.test(o));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(o.length)}}}function Lr(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],i=a.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(n.length)}}}const zr={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=Dr[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r},formatLong:Ir,formatRelative:(e,a,t,r)=>Tr[e],localize:{ordinalNumber:(e,a)=>{const t=Number(e),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:Rr({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Rr({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:Rr({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:Rr({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:Rr({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},match:{ordinalNumber:Lr({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mr({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:Mr({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Mr({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:Mr({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Mr({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},options:{weekStartsOn:0,firstWeekContainsDate:1}};let Fr={};function Ur(){return Fr}const jr=6048e5;function Or(e){const a=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===a?new e.constructor(+e):"number"==typeof e||"[object Number]"===a||"string"==typeof e||"[object String]"===a?new Date(e):new Date(NaN)}function Br(e){const a=Or(e);return a.setHours(0,0,0,0),a}function $r(e){const a=Or(e),t=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()));return t.setUTCFullYear(a.getFullYear()),+e-+t}function Vr(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function qr(e){const a=Or(e),t=function(e,a){const t=Br(e),r=Br(a),n=+t-$r(t),i=+r-$r(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Or(e),t=Vr(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Wr(e,a){const t=Ur(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Or(e),i=n.getDay(),o=(i<r?7:0)+i-r;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Hr(e){return Wr(e,{weekStartsOn:1})}function Gr(e){const a=Or(e),t=a.getFullYear(),r=Vr(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Hr(r),i=Vr(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const o=Hr(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function Kr(e){const a=Or(e),t=+Hr(a)-+function(e){const a=Gr(e),t=Vr(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Hr(t)}(a);return Math.round(t/jr)+1}function Yr(e,a){const t=Or(e),r=t.getFullYear(),n=Ur(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=Vr(e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const s=Wr(o,a),l=Vr(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const d=Wr(l,a);return t.getTime()>=s.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function Qr(e,a){const t=Or(e),r=+Wr(t,a)-+function(e,a){const t=Ur(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=Yr(e,a),i=Vr(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),Wr(i,a)}(t,a);return Math.round(r/jr)+1}function Xr(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Jr={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return Xr("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):Xr(t+1,2)},d:(e,a)=>Xr(e.getDate(),a.length),a(e,a){const t=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return"am"===t?"a.m.":"p.m."}},h:(e,a)=>Xr(e.getHours()%12||12,a.length),H:(e,a)=>Xr(e.getHours(),a.length),m:(e,a)=>Xr(e.getMinutes(),a.length),s:(e,a)=>Xr(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return Xr(Math.trunc(r*Math.pow(10,t-3)),a.length)}},Zr="midnight",en="noon",an="morning",tn="afternoon",rn="evening",nn="night",on={G:function(e,a,t){const r=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});default:return t.era(r,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),r=a>0?a:1-a;return t.ordinalNumber(r,{unit:"year"})}return Jr.y(e,a)},Y:function(e,a,t,r){const n=Yr(e,r),i=n>0?n:1-n;if("YY"===a){return Xr(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):Xr(i,a.length)},R:function(e,a){return Xr(Gr(e),a.length)},u:function(e,a){return Xr(e.getFullYear(),a.length)},Q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(r);case"QQ":return Xr(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(r);case"qq":return Xr(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,a,t){const r=e.getMonth();switch(a){case"M":case"MM":return Jr.M(e,a);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(e,a,t){const r=e.getMonth();switch(a){case"L":return String(r+1);case"LL":return Xr(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(e,a,t,r){const n=Qr(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):Xr(n,a.length)},I:function(e,a,t){const r=Kr(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):Xr(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Jr.d(e,a)},D:function(e,a,t){const r=qr(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):Xr(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(i);case"ee":return Xr(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(i);case"cc":return Xr(i,a.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return Xr(n,a.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(e,a,t){const r=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,a,t){const r=e.getHours();let n;switch(n=12===r?en:0===r?Zr:r/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,a,t){const r=e.getHours();let n;switch(n=r>=17?rn:r>=12?tn:r>=4?an:nn,a){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,a,t){if("ho"===a){let a=e.getHours()%12;return 0===a&&(a=12),t.ordinalNumber(a,{unit:"hour"})}return Jr.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Jr.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):Xr(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):Xr(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Jr.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Jr.s(e,a)},S:function(e,a){return Jr.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return ln(r);case"XXXX":case"XX":return dn(r);default:return dn(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return ln(r);case"xxxx":case"xx":return dn(r);default:return dn(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+sn(r,":");default:return"GMT"+dn(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+sn(r,":");default:return"GMT"+dn(r,":")}},t:function(e,a,t){return Xr(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return Xr(e.getTime(),a.length)}};function sn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),i=r%60;return 0===i?t+String(n):t+String(n)+a+Xr(i,2)}function ln(e,a){if(e%60==0){return(e>0?"-":"+")+Xr(Math.abs(e)/60,2)}return dn(e,a)}function dn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Xr(Math.trunc(r/60),2)+a+Xr(r%60,2)}const cn=(e,a)=>{switch(e){case"P":return a.date({width:"short"});case"PP":return a.date({width:"medium"});case"PPP":return a.date({width:"long"});default:return a.date({width:"full"})}},un=(e,a)=>{switch(e){case"p":return a.time({width:"short"});case"pp":return a.time({width:"medium"});case"ppp":return a.time({width:"long"});default:return a.time({width:"full"})}},mn={p:un,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return cn(e,a);let i;switch(r){case"P":i=a.dateTime({width:"short"});break;case"PP":i=a.dateTime({width:"medium"});break;case"PPP":i=a.dateTime({width:"long"});break;default:i=a.dateTime({width:"full"})}return i.replace("{{date}}",cn(r,a)).replace("{{time}}",un(n,a))}},pn=/^D+$/,hn=/^Y+$/,fn=["D","DD","YY","YYYY"];function gn(e){if(!(a=e,a instanceof Date||"object"==typeof a&&"[object Date]"===Object.prototype.toString.call(a)||"number"==typeof e))return!1;var a;const t=Or(e);return!isNaN(Number(t))}const vn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,bn=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,xn=/^'([^]*?)'?$/,yn=/''/g,Nn=/[a-zA-Z]/;function wn(e,a,t){const r=Ur(),n=t?.locale??r.locale??zr,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=Or(e);if(!gn(s))throw new RangeError("Invalid time value");let l=a.match(bn).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,mn[a])(e,n.formatLong)}return e}).join("").match(vn).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:_n(e)};if(on[a])return{isToken:!0,value:e};if(a.match(Nn))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(s,l));const d={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return hn.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return pn.test(e)}(i))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(fn.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,on[i[0]])(s,i,n.localize,d)}).join("")}function _n(e){const a=e.match(xn);return a?a[1].replace(yn,"'"):e}function Cn(e,a,t){const r=y(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function kn(e,a){const t=function(e){An[e]||(An[e]=Dn?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}));return An[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),r=[];for(let e=0;e<t.length;e++){const a=Sn[t[e].type];void 0!==a&&(r[a]=parseInt(t[e].value,10))}return r}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}(t,e)}const Sn={year:0,month:1,day:2,hour:3,minute:4,second:5};const An={},En=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),Dn="06/25/2014, 00:00:00"===En||"06/25/2014 00:00:00"===En;function Pn(e,a,t,r,n,i,o){const s=new Date(0);return s.setUTCFullYear(e,a,t),s.setUTCHours(r,n,i,o),s}const In=36e5,Tn={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Rn(e,a,t){if(!e)return 0;let r,n,i=Tn.timezoneZ.exec(e);if(i)return 0;if(i=Tn.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Ln(r)?-r*In:NaN;if(i=Tn.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Ln(r,e)?(n=Math.abs(r)*In+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(zn[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),zn[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Pn(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Mn(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Mn(new Date(n),t);if(a===i)return a;n-=i-a;const o=Mn(new Date(n),t);if(i===o)return i;return Math.max(i,o)}(a,n,e);return-i}return NaN}function Mn(e,a){const t=kn(e,a),r=Pn(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const i=n%1e3;return n-=i>=0?i:1e3+i,r-n}function Ln(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const zn={};const Fn={X:function(e,a,t){const r=Un(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Bn(r);case"XXXX":case"XX":return On(r);default:return On(r,":")}},x:function(e,a,t){const r=Un(t.timeZone,e);switch(a){case"x":return Bn(r);case"xxxx":case"xx":return On(r);default:return On(r,":")}},O:function(e,a,t){const r=Un(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),i=r%60;if(0===i)return t+String(n);return t+String(n)+a+jn(i,2)}(r,":");default:return"GMT"+On(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Cn("short",e,t);default:return Cn("long",e,t)}}};function Un(e,a){const t=e?Rn(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function jn(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function On(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+jn(Math.floor(r/60),2)+a+jn(Math.floor(r%60),2)}function Bn(e,a){if(e%60==0){return(e>0?"-":"+")+jn(Math.abs(e)/60,2)}return On(e,a)}function $n(e){const a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+e-+a}const Vn=36e5,qn=6e4,Wn={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/};function Hn(e,a={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const t=null==a.additionalDigits?2:Number(a.additionalDigits);if(2!==t&&1!==t&&0!==t)throw new RangeError("additionalDigits must be 0, 1 or 2");if(e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e))return new Date(e.getTime());if("number"==typeof e||"[object Number]"===Object.prototype.toString.call(e))return new Date(e);if("[object String]"!==Object.prototype.toString.call(e))return new Date(NaN);const r=function(e){const a={};let t,r=Wn.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Wn.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Wn.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:i}=function(e,a){if(e){const t=Wn.YYY[a],r=Wn.YYYYY[a];let n=Wn.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Wn.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),o=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let i=Wn.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,Xn(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=Wn.DDD.exec(e),i){t=new Date(0);const e=parseInt(i[1],10);return function(e,a){if(a<1)return!1;const t=Qn(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(i=Wn.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return Xn(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=Wn.Www.exec(e),i)return n=parseInt(i[1],10)-1,Jn(n)?Gn(a,n):new Date(NaN);if(i=Wn.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return Jn(n,e)?Gn(a,n,e):new Date(NaN)}return null}(i,n);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Wn.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),Zn(a)?a%24*Vn:NaN;if(r=Wn.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),Zn(a,t)?a%24*Vn+t*qn:NaN;if(r=Wn.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return Zn(a,t,e)?a%24*Vn+t*qn+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Rn(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=$n(new Date(e+n)),t=$n(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Gn(e,a,t){a=a||0,t=t||0;const r=new Date(0);r.setUTCFullYear(e,0,4);const n=7*a+t+1-(r.getUTCDay()||7);return r.setUTCDate(r.getUTCDate()+n),r}const Kn=[31,28,31,30,31,30,31,31,30,31,30,31],Yn=[31,29,31,30,31,30,31,31,30,31,30,31];function Qn(e){return e%400==0||e%4==0&&e%100!=0}function Xn(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=Qn(e);if(r&&t>Yn[a])return!1;if(!r&&t>Kn[a])return!1}return!0}function Jn(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Zn(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const ei=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function ai(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(ei);if(r){const n=Hn(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],o=e.replace(a,"'"+Fn[a[0]](n,a,t)+"'");return i?o.substring(0,r-1)+o.substring(r+1):o},a)}return wn(e,a,t)}(function(e,a,t){const r=Rn(a,e=Hn(e,t),!0),n=new Date(e.getTime()-r),i=new Date(0);return i.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),i.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const ti={lessThanXSeconds:{one:"menos de un segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"medio minuto",lessThanXMinutes:{one:"menos de un minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"alrededor de 1 hora",other:"alrededor de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 día",other:"{{count}} días"},aboutXWeeks:{one:"alrededor de 1 semana",other:"alrededor de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"alrededor de 1 mes",other:"alrededor de {{count}} meses"},xMonths:{one:"1 mes",other:"{{count}} meses"},aboutXYears:{one:"alrededor de 1 año",other:"alrededor de {{count}} años"},xYears:{one:"1 año",other:"{{count}} años"},overXYears:{one:"más de 1 año",other:"más de {{count}} años"},almostXYears:{one:"casi 1 año",other:"casi {{count}} años"}},ri={date:Pr({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:Pr({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Pr({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},ni={lastWeek:"'el' eeee 'pasado a la' p",yesterday:"'ayer a la' p",today:"'hoy a la' p",tomorrow:"'mañana a la' p",nextWeek:"eeee 'a la' p",other:"P"},ii={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},oi={code:"es",formatDistance:(e,a,t)=>{let r;const n=ti[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+r:"hace "+r:r},formatLong:ri,formatRelative:(e,a,t,r)=>1!==a.getHours()?ii[e]:ni[e],localize:{ordinalNumber:(e,a)=>Number(e)+"º",era:Rr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Rr({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>Number(e)-1}),month:Rr({values:{narrow:["e","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],wide:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},defaultWidth:"wide"}),day:Rr({values:{narrow:["d","l","m","m","j","v","s"],short:["do","lu","ma","mi","ju","vi","sá"],abbreviated:["dom","lun","mar","mié","jue","vie","sáb"],wide:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"]},defaultWidth:"wide"}),dayPeriod:Rr({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"}},defaultFormattingWidth:"wide"})},match:{ordinalNumber:Lr({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Mr({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|a\.?\s?e\.?\s?c\.?|d\.?\s?c\.?|e\.?\s?c\.?)/i,wide:/^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^(antes de cristo|antes de la era com[uú]n)/i,/^(despu[eé]s de cristo|era com[uú]n)/i]},defaultParseWidth:"any"}),quarter:Mr({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:Mr({matchPatterns:{narrow:/^[efmajsond]/i,abbreviated:/^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,wide:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^e/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^en/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i]},defaultParseWidth:"any"}),day:Mr({matchPatterns:{narrow:/^[dlmjvs]/i,short:/^(do|lu|ma|mi|ju|vi|s[áa])/i,abbreviated:/^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,wide:/^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^do/i,/^lu/i,/^ma/i,/^mi/i,/^ju/i,/^vi/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Mr({matchPatterns:{narrow:/^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,any:/^([ap]\.?\s?m\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn/i,noon:/^md/i,morning:/mañana/i,afternoon:/tarde/i,evening:/tarde/i,night:/noche/i}},defaultParseWidth:"any"})},options:{weekStartsOn:1,firstWeekContainsDate:1}},si={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"}},li={date:Pr({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:Pr({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Pr({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},di={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"},ci={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=si[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:li,formatRelative:(e,a,t,r)=>{const n=di[e];return"function"==typeof n?n(a):n},localize:{ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Rr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Rr({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:Rr({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:Rr({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:Rr({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"})},match:{ordinalNumber:Lr({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mr({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:Mr({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:Mr({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:Mr({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:Mr({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"})},options:{weekStartsOn:0,firstWeekContainsDate:1}},ui=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],mi=[{value:"dd/MM/yyyy HH:mm",label:"dd/MM/yyyy HH:mm",example:"28/11/2024 14:30",description:"Padrão Brasileiro"},{value:"MM/dd/yyyy hh:mm a",label:"MM/dd/yyyy hh:mm a",example:"11/28/2024 02:30 PM",description:"Padrão Americano (12h)"},{value:"MM/dd/yyyy HH:mm",label:"MM/dd/yyyy HH:mm",example:"11/28/2024 14:30",description:"Padrão Americano (24h)"},{value:"yyyy-MM-dd HH:mm",label:"yyyy-MM-dd HH:mm",example:"2024-11-28 14:30",description:"ISO 8601"},{value:"dd.MM.yyyy HH:mm",label:"dd.MM.yyyy HH:mm",example:"28.11.2024 14:30",description:"Padrão Europeu"},{value:"d MMM yyyy, HH:mm",label:"d MMM yyyy, HH:mm",example:"28 Nov 2024, 14:30",description:"Formato Longo"}],pi=[{value:"America/Sao_Paulo",label:"Brasília (UTC-3)",offset:"-03:00"},{value:"America/Noronha",label:"Fernando de Noronha (UTC-2)",offset:"-02:00"},{value:"America/Manaus",label:"Manaus (UTC-4)",offset:"-04:00"},{value:"America/Rio_Branco",label:"Rio Branco (UTC-5)",offset:"-05:00"},{value:"America/Buenos_Aires",label:"Buenos Aires (UTC-3)",offset:"-03:00"},{value:"America/Santiago",label:"Santiago (UTC-4)",offset:"-04:00"},{value:"America/Bogota",label:"Bogotá (UTC-5)",offset:"-05:00"},{value:"America/Mexico_City",label:"Cidade do México (UTC-6)",offset:"-06:00"},{value:"America/New_York",label:"New York (UTC-5)",offset:"-05:00"},{value:"America/Chicago",label:"Chicago (UTC-6)",offset:"-06:00"},{value:"America/Denver",label:"Denver (UTC-7)",offset:"-07:00"},{value:"America/Los_Angeles",label:"Los Angeles (UTC-8)",offset:"-08:00"},{value:"America/Toronto",label:"Toronto (UTC-5)",offset:"-05:00"},{value:"America/Vancouver",label:"Vancouver (UTC-8)",offset:"-08:00"},{value:"Europe/London",label:"Londres (UTC+0)",offset:"+00:00"},{value:"Europe/Lisbon",label:"Lisboa (UTC+0)",offset:"+00:00"},{value:"Europe/Paris",label:"Paris (UTC+1)",offset:"+01:00"},{value:"Europe/Berlin",label:"Berlim (UTC+1)",offset:"+01:00"},{value:"Europe/Madrid",label:"Madrid (UTC+1)",offset:"+01:00"},{value:"Europe/Rome",label:"Roma (UTC+1)",offset:"+01:00"},{value:"Europe/Amsterdam",label:"Amsterdã (UTC+1)",offset:"+01:00"},{value:"Europe/Moscow",label:"Moscou (UTC+3)",offset:"+03:00"},{value:"Asia/Dubai",label:"Dubai (UTC+4)",offset:"+04:00"},{value:"Asia/Kolkata",label:"Mumbai (UTC+5:30)",offset:"+05:30"},{value:"Asia/Singapore",label:"Singapura (UTC+8)",offset:"+08:00"},{value:"Asia/Hong_Kong",label:"Hong Kong (UTC+8)",offset:"+08:00"},{value:"Asia/Shanghai",label:"Xangai (UTC+8)",offset:"+08:00"},{value:"Asia/Tokyo",label:"Tóquio (UTC+9)",offset:"+09:00"},{value:"Asia/Seoul",label:"Seul (UTC+9)",offset:"+09:00"},{value:"Australia/Perth",label:"Perth (UTC+8)",offset:"+08:00"},{value:"Australia/Sydney",label:"Sydney (UTC+10)",offset:"+10:00"},{value:"Pacific/Auckland",label:"Auckland (UTC+12)",offset:"+12:00"},{value:"UTC",label:"UTC (UTC+0)",offset:"+00:00"}],hi="pt-BR",fi="dd/MM/yyyy HH:mm",gi="America/Sao_Paulo",vi=e=>ui.find(a=>a.value===e),bi=e=>mi.find(a=>a.value===e),xi=e=>pi.find(a=>a.value===e),yi=e=>ui.some(a=>a.value===e),Ni=e=>mi.some(a=>a.value===e),wi=e=>pi.some(a=>a.value===e),_i=()=>{if("undefined"==typeof navigator)return hi;const e=navigator.language;if(yi(e))return e;const a=e.split("-")[0],t=ui.find(e=>e.value.startsWith(a));return t?.value||hi},Ci=()=>{if("undefined"==typeof Intl)return gi;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return wi(e)?e:gi}catch{return gi}},ki=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||fi),Si=()=>{const e=_i();return{locale:e,timezone:Ci(),datetimeFormat:ki(e)}},Ai={"pt-BR":ci,"en-US":zr,"es-ES":oi},Ei=(e,a=fi,t=gi,r=hi)=>{if(!e)return"";const n=N(e);if(!w(n))return"Data inválida";const i=Ai[r]||ci;try{return ai(n,t,a,{locale:i})}catch(o){return ai(n,gi,a,{locale:i})}},Di=(e,a=hi,t=gi)=>{if(!e)return"";const r=N(e);if(!w(r))return"Data inválida";const n=Ai[a]||ci;try{return ai(r,t,"PP",{locale:n})}catch(i){return ai(r,gi,"PP",{locale:n})}},Pi=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function Ii(e){const a=e.replace("#",""),t=3===a.length?a.split("").map(e=>e+e).join(""):a;return{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function Ti(e,a=.1){const{r:t,g:r,b:n}=Ii(e);return`rgba(${t}, ${r}, ${n}, ${a})`}function Ri(e){const{r:a,g:t,b:r}=Ii(e),[n,i,o]=[a,t,r].map(e=>{const a=e/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)});return.2126*n+.7152*i+.0722*o}function Mi(e,a){const t=Ri(e),r=Ri(a);return(Math.max(t,r)+.05)/(Math.min(t,r)+.05)}function Li(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{C.info("Link copiado para a área de transferência")})}function zi(e,a){return a?e.replace(/\{alias\}/g,a):e}function Fi(...e){return x(b(e))}const Ui=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Ui);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Ui(r);return a}return e},ji=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Oi=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Bi=v("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded-lg",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),$i=n.forwardRef(({className:e,variant:t,size:r,asChild:n=!1,...i},o)=>a(n?g:"button",{className:Fi(Bi({variant:t,size:r,className:e})),ref:o,...i}));$i.displayName="Button";const Vi=i.forwardRef(({className:e,children:t,variant:r="action",...n},i)=>a($i,{ref:i,variant:r,size:"icon",className:Fi("h-8 w-8",e),...n,children:t||a(A,{size:16})}));Vi.displayName="ActionButton";const qi=n.forwardRef(({className:e,type:r,showCharCount:i,maxLength:o,onChange:s,...l},d)=>{const[c,u]=n.useState(0);n.useEffect(()=>{"string"==typeof l.value?u(l.value.length):"string"==typeof l.defaultValue&&u(l.defaultValue.length)},[l.value,l.defaultValue]);return t("div",{className:"w-full",children:[a("input",{type:r,className:Fi("flex h-10 w-full rounded-lg 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 hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors md:text-sm",e),ref:d,maxLength:o,onChange:e=>{u(e.target.value.length),s?.(e)},...l}),i&&o&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[c," / ",o]})]})});qi.displayName="Input";const Wi=v("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Hi=n.forwardRef(({className:e,...t},r)=>a(Ra.Root,{ref:r,className:Fi(Wi(),e),...t}));Hi.displayName=Ra.Root.displayName;const Gi=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Gi.displayName="Card";const Ki=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("flex flex-col space-y-1.5 p-6",e),...t}));Ki.displayName="CardHeader";const Yi=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Fi("text-2xl font-semibold leading-none tracking-tight",e),...t}));Yi.displayName="CardTitle";const Qi=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));Qi.displayName="CardDescription";const Xi=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("p-6 pt-0",e),...t}));Xi.displayName="CardContent";const Ji=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("flex items-center p-6 pt-0",e),...t}));Ji.displayName="CardFooter";const Zi=n.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...n},i)=>a(La.Root,{ref:i,decorative:r,orientation:t,className:Fi("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...n}));Zi.displayName=La.Root.displayName;const eo=za.Root,ao=za.Trigger,to=za.Portal,ro=n.forwardRef(({className:e,...t},r)=>a(za.Overlay,{className:Fi("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:r}));ro.displayName=za.Overlay.displayName;const no=n.forwardRef(({className:e,...r},n)=>t(to,{children:[a(ro,{}),a(za.Content,{ref:n,className:Fi("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),...r})]}));no.displayName=za.Content.displayName;const io=({className:e,...t})=>a("div",{className:Fi("flex flex-col space-y-2 text-center sm:text-left",e),...t});io.displayName="AlertDialogHeader";const oo=({className:e,...t})=>a("div",{className:Fi("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});oo.displayName="AlertDialogFooter";const so=n.forwardRef(({className:e,...t},r)=>a(za.Title,{ref:r,className:Fi("text-lg font-semibold",e),...t}));so.displayName=za.Title.displayName;const lo=n.forwardRef(({className:e,...t},r)=>a(za.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));lo.displayName=za.Description.displayName;const co=n.forwardRef(({className:e,...t},r)=>a(za.Action,{ref:r,className:Fi(Bi(),e),...t}));co.displayName=za.Action.displayName;const uo=n.forwardRef(({className:e,...t},r)=>a(za.Cancel,{ref:r,className:Fi(Bi({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));uo.displayName=za.Cancel.displayName;const mo=Ma.Root,po=Ma.Trigger,ho=Ma.Portal,fo=Ma.Close,go=n.forwardRef(({className:e,...t},r)=>a(Ma.Overlay,{ref:r,className:Fi("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}));go.displayName=Ma.Overlay.displayName;const vo={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},bo=n.forwardRef(({className:r,children:i,size:o,variant:s="informative",isDirty:l,customWidth:d,customMinWidth:c,customMaxWidth:u,customHeight:m,customMinHeight:p,customMaxHeight:h,unsavedChangesTitle:f=e.t("unsaved_changes"),unsavedChangesDescription:g=e.t("unsaved_changes_description"),cancelText:v=e.t("cancel"),leaveWithoutSavingText:b=e.t("leave_without_saving"),style:x,onInteractOutside:y,onEscapeKeyDown:N,...w},_)=>{const[C,k]=n.useState(!1),S=n.useRef(null),A=n.useRef(!1),D=o??(d||c||u||m||p||h?void 0:"md"),P=D?vo[D]:{},I={...d??P.width?{width:d??P.width}:{},...c??P.minWidth?{minWidth:c??P.minWidth}:{},...u??P.maxWidth?{maxWidth:u??P.maxWidth}:{},...m??P.height?{height:m??P.height}:{},...p??P.minHeight?{minHeight:p??P.minHeight}:{},...h??P.maxHeight?{maxHeight:h??P.maxHeight}:{},...x},T=n.useCallback(e=>{"form"===s&&l?(S.current=e,k(!0)):e()},[s,l]),R=n.useRef(null),M="destructive"!==s;if("development"===process.env.NODE_ENV&&i){const e=n.Children.toArray(i);e.some(e=>n.isValidElement(e)&&"DialogFooter"===e.type?.displayName),e.some(e=>n.isValidElement(e)&&"DialogBody"===e.type?.displayName)}return t(ho,{children:[a(go,{}),t(Ma.Content,{ref:_,className:Fi("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border-0 border-l-[10px] border-l-primary 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%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",r),style:I,onInteractOutside:e=>{"form"!==s&&"destructive"!==s?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==s)return"form"===s&&l?(e.preventDefault(),void T(()=>{A.current=!0,R.current?.click()})):void N?.(e);e.preventDefault()},...w,children:[i,M&&t(Ma.Close,{ref:R,onClick:e=>{A.current?A.current=!1:"form"===s&&l&&(e.preventDefault(),T(()=>{A.current=!0,R.current?.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[a(E,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]}),a(eo,{open:C,onOpenChange:k,children:t(no,{children:[t(io,{children:[a(so,{children:f}),a(lo,{children:g})]}),t(oo,{children:[a(uo,{onClick:()=>{k(!1),S.current=null},children:v}),a(co,{onClick:()=>{k(!1),S.current?.(),S.current=null},children:b})]})]})})]})});bo.displayName=Ma.Content.displayName;const xo=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Fi("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(Zi,{className:"mt-2"})]});xo.displayName="DialogHeader";const yo=({className:e,...t})=>a("div",{className:Fi("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",e),...t});yo.displayName="DialogBody";const No=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(Zi,{className:"mb-4"}),a("div",{className:Fi("flex flex-row justify-end gap-2",e),...n,children:r})]});No.displayName="DialogFooter";const wo=n.forwardRef(({className:e,...t},r)=>a(Ma.Title,{ref:r,className:Fi("text-xl font-semibold leading-none tracking-tight",e),...t}));wo.displayName=Ma.Title.displayName;const _o=n.forwardRef(({className:e,...t},r)=>a(Ma.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));_o.displayName=Ma.Description.displayName;const Co=Ua,ko=n.createContext({}),So=({...e})=>a(ko.Provider,{value:{name:e.name},children:a(ja,{...e})}),Ao=()=>{const e=n.useContext(ko),a=n.useContext(Eo),{getFieldState:t,formState:r}=Fa(),i=t(e.name,r);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:o}=a;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},Eo=n.createContext({}),Do=n.forwardRef(({className:e,...t},r)=>{const i=n.useId();return a(Eo.Provider,{value:{id:i},children:a("div",{ref:r,className:Fi("space-y-1.5",e),...t})})});Do.displayName="FormItem";const Po=n.forwardRef(({className:e,...t},r)=>{const{error:n,formItemId:i}=Ao();return a(Hi,{ref:r,className:Fi(n&&"text-destructive",e),htmlFor:i,...t})});Po.displayName="FormLabel";const Io=n.forwardRef(({...e},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=Ao();return a(g,{ref:t,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...e})});Io.displayName="FormControl";const To=n.forwardRef(({className:e,...t},r)=>{const{formDescriptionId:n}=Ao();return a("p",{ref:r,id:n,className:Fi("text-sm text-muted-foreground",e),...t})});To.displayName="FormDescription";const Ro=n.forwardRef(({className:e,children:t,...r},n)=>{const{error:i,formMessageId:o}=Ao(),s=i?String(i?.message):t;return s?a("p",{ref:n,id:o,className:Fi("text-sm font-medium text-destructive",e),...r,children:s}):null});Ro.displayName="FormMessage";const Mo=$a.Root,Lo=$a.Group,zo=$a.Value,Fo=n.forwardRef(({className:e,children:r,...n},i)=>t($a.Trigger,{ref:i,className:Fi("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors [&>span]:line-clamp-1",e),...n,children:[r,a($a.Icon,{asChild:!0,children:a(D,{className:"h-4 w-4 opacity-50"})})]}));Fo.displayName=$a.Trigger.displayName;const Uo=n.forwardRef(({className:e,...t},r)=>a($a.ScrollUpButton,{ref:r,className:Fi("flex cursor-default items-center justify-center py-1",e),...t,children:a(P,{className:"h-4 w-4"})}));Uo.displayName=$a.ScrollUpButton.displayName;const jo=n.forwardRef(({className:e,...t},r)=>a($a.ScrollDownButton,{ref:r,className:Fi("flex cursor-default items-center justify-center py-1",e),...t,children:a(D,{className:"h-4 w-4"})}));jo.displayName=$a.ScrollDownButton.displayName;const Oo=n.forwardRef(({className:e,children:r,position:n="popper",container:i,collisionBoundary:o,...s},l)=>a($a.Portal,{container:i,children:t($a.Content,{ref:l,className:Fi("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:o,...s,children:[a(Uo,{}),a($a.Viewport,{className:Fi("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),a(jo,{})]})}));Oo.displayName=$a.Content.displayName;const Bo=n.forwardRef(({className:e,...t},r)=>a($a.Label,{ref:r,className:Fi("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Bo.displayName=$a.Label.displayName;const $o=n.forwardRef(({className:e,children:r,...n},i)=>t($a.Item,{ref:i,className:Fi("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:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a($a.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),a($a.ItemText,{children:r})]}));$o.displayName=$a.Item.displayName;const Vo=n.forwardRef(({className:e,...t},r)=>a($a.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-muted",e),...t}));Vo.displayName=$a.Separator.displayName;const qo=n.forwardRef(({className:e,...t},r)=>a(Va.Root,{ref:r,className:Fi("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:a(Va.Indicator,{className:Fi("flex items-center justify-center text-current"),children:a(I,{className:"h-4 w-4"})})}));qo.displayName=Va.Root.displayName;const Wo=n.forwardRef(({className:e,showCharCount:r,maxLength:i,onChange:o,...s},l)=>{const[d,c]=n.useState(0);n.useEffect(()=>{"string"==typeof s.value?c(s.value.length):"string"==typeof s.defaultValue&&c(s.defaultValue.length)},[s.value,s.defaultValue]);return t("div",{className:"w-full",children:[a("textarea",{className:Fi("flex min-h-[80px] w-full rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors",e),ref:l,maxLength:i,onChange:e=>{c(e.target.value.length),o?.(e)},...s}),r&&i&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",i]})]})});Wo.displayName="Textarea";const Ho=v("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",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Go=n.forwardRef(({className:e,variant:t,...r},n)=>a("div",{ref:n,className:Fi(Ho({variant:t}),e),...r}));Go.displayName="Badge";const Ko={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Yo({size:e="md",className:t}){return a(T,{className:Fi("animate-spin text-muted-foreground",Ko[e],t)})}function Qo({isLoading:e,children:n,className:i,type:o="spinner",size:s="md"}){return e?"overlay"===o?t("div",{className:Fi("relative",i),children:[n,a("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:a(Yo,{size:s})})]}):a("div","skeleton"===o?{className:Fi("animate-pulse",i),children:a("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Fi("flex items-center justify-center py-8",i),children:a(Yo,{size:s})}):a(r,{children:n})}const Xo=({...e})=>a(k,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:a(F,{className:"h-4 w-4"}),info:a(z,{className:"h-4 w-4"}),warning:a(L,{className:"h-4 w-4"}),error:a(M,{className:"h-4 w-4"}),loading:a(R,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive-light !border-destructive-light",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...e}),Jo=qa.Root,Zo=qa.Trigger,es=qa.Group,as=qa.Portal,ts=qa.Sub,rs=qa.RadioGroup,ns=n.forwardRef(({className:e,inset:r,children:n,...i},o)=>t(qa.SubTrigger,{ref:o,className:Fi("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",e),...i,children:[n,a(U,{className:"ml-auto h-4 w-4"})]}));ns.displayName=qa.SubTrigger.displayName;const is=n.forwardRef(({className:e,...t},r)=>a(qa.SubContent,{ref:r,className:Fi("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}));is.displayName=qa.SubContent.displayName;const os=n.forwardRef(({className:e,sideOffset:t=4,...r},n)=>a(qa.Portal,{children:a(qa.Content,{ref:n,sideOffset:t,className:Fi("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));os.displayName=qa.Content.displayName;const ss=n.forwardRef(({className:e,inset:t,...r},n)=>a(qa.Item,{ref:n,className:Fi("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),...r}));ss.displayName=qa.Item.displayName;const ls=n.forwardRef(({className:e,children:r,checked:n,...i},o)=>t(qa.CheckboxItem,{ref:o,className:Fi("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,...i,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(qa.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),r]}));ls.displayName=qa.CheckboxItem.displayName;const ds=n.forwardRef(({className:e,children:r,...n},i)=>t(qa.RadioItem,{ref:i,className:Fi("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:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(qa.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));ds.displayName=qa.RadioItem.displayName;const cs=n.forwardRef(({className:e,inset:t,...r},n)=>a(qa.Label,{ref:n,className:Fi("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));cs.displayName=qa.Label.displayName;const us=n.forwardRef(({className:e,...t},r)=>a(qa.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-muted",e),...t}));us.displayName=qa.Separator.displayName;const ms=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest opacity-60",e),...t});ms.displayName="DropdownMenuShortcut";const ps=({delayDuration:e=300,...t})=>a(Wa.Provider,{delayDuration:e,...t}),hs=Wa.Root,fs=Wa.Trigger,gs=n.forwardRef(({className:e,sideOffset:t=4,container:r,...n},i)=>a(Wa.Portal,{container:r,children:a(Wa.Content,{ref:i,sideOffset:t,className:Fi("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})}));gs.displayName=Wa.Content.displayName;const vs=n.forwardRef(({children:e,disabledReason:r,className:n},i)=>{const o=a(ss,{ref:i,className:Fi("opacity-50 cursor-not-allowed pointer-events-auto",n),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:e});return r?a(ps,{delayDuration:100,children:t(hs,{children:[a(fs,{asChild:!0,children:a("div",{className:"w-full",children:o})}),a(gs,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):o});vs.displayName="DisabledMenuItem";const bs=Ha.Root,xs=Ha.Trigger,ys=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,container:n,...i},o)=>a(Ha.Portal,{container:n,children:a(Ha.Content,{ref:o,align:t,sideOffset:r,className:Fi("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),...i})}));ys.displayName=Ha.Content.displayName;const Ns=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));Ns.displayName="Command";const ws=({children:e,...t})=>a("div",{...t,children:a(Ns,{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})}),_s=n.forwardRef(({className:e,...t},r)=>a("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:a("input",{ref:r,className:Fi("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})}));_s.displayName="CommandInput";const Cs=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));Cs.displayName="CommandList";const ks=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("py-6 text-center text-sm text-muted-foreground",e),...t}));ks.displayName="CommandEmpty";const Ss=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("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}));Ss.displayName="CommandGroup";const As=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("-mx-1 h-px bg-border",e),...t}));As.displayName="CommandSeparator";const Es=n.forwardRef(({className:e,disabled:t,onSelect:r,value:n,...i},o)=>a("div",{ref:o,className:Fi("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...i}));Es.displayName="CommandItem";const Ds=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});function Ps({className:e,...t}){return a("div",{className:Fi("animate-pulse rounded-md bg-muted",e),...t})}Ds.displayName="CommandShortcut";const Is=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ts({multiple:r,options:n,value:i,onChange:l,getOptionValue:d,getOptionLabel:c,placeholder:u,label:m,icon:p,emptyMessage:h,searchPlaceholder:f,disabled:g,required:v,className:b,sortOptions:x,maxDisplayedBadges:y,popoverContainer:N,onOpen:w,onClose:_,clearable:C}){const[k,S]=o(!1),[A,P]=o(""),T=s(()=>i?Array.isArray(i)?i:[i]:[],[i]),R=s(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),M=s(()=>{const e=n.map(e=>({original:e,value:d(e),label:c(e)}));return x?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[n,d,c,x]),L=s(()=>{if(!A)return M;const e=Is(A);return M.filter(a=>Is(a.label).includes(e))},[M,A]),z=s(()=>M.filter(e=>T.includes(e.value)),[M,T]),F=e=>{S(e),e?w?.():(P(""),_?.())},U=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(r?T.filter(a=>a!==e):"")},j=y?z.slice(0,y):z,O=y&&z.length>y?z.length-y:0;return t("div",{className:Fi("space-y-2",b),children:[m&&t(Hi,{children:[m,v&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(bs,{open:k,onOpenChange:F,modal:!1,children:[r?a(xs,{asChild:!0,children:t("div",{role:"combobox","aria-expanded":k,"aria-disabled":g,tabIndex:g?-1:0,onKeyDown:e=>{g||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),F(!k))},className:Fi("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",g&&"pointer-events-none opacity-50 cursor-not-allowed",0===z.length&&"text-muted-foreground"),children:[0===z.length?t("span",{className:"flex items-center gap-2",children:[p&&a(p,{className:"h-4 w-4"}),u]}):t("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[j.map(e=>t(Go,{variant:"secondary",className:"gap-1 pr-1",children:[e.label,a("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:a=>{"Enter"===a.key&&U(e.value,a)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:a=>U(e.value,a),children:a(E,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),O>0&&t(Go,{variant:"outline",className:"gap-1",children:["+",O]})]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]})}):t("div",{className:"flex items-center gap-1",children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",role:"combobox","aria-expanded":k,disabled:g,className:Fi("flex-1 justify-between min-h-10 h-auto",0===z.length&&"text-muted-foreground"),children:[0===z.length?t("span",{className:"flex items-center gap-2",children:[p&&a(p,{className:"h-4 w-4"}),u]}):t("span",{className:"flex items-center gap-2",children:[p&&a(p,{className:"h-4 w-4"}),z[0]?.label]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),C&&z.length>0&&a($i,{type:"button",variant:"ghost",size:"icon",disabled:g,className:"h-9 w-9 shrink-0 text-muted-foreground hover:text-foreground",onClick:e=>U("",e),title:"Limpar seleção",children:a(E,{className:"h-4 w-4"})})]}),a(ys,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:R,collisionBoundary:R,children:t(Ns,{children:[t("div",{className:"relative",children:[a(_s,{placeholder:f,value:A,onChange:e=>P(e.target.value)}),A&&a("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:a(E,{className:"h-3.5 w-3.5"})})]}),a(Cs,{children:0===n.length?a(ks,{children:h}):0===L.length?a(ks,{children:e.t("no_results")}):a(Ss,{children:L.map(e=>t(Es,{value:e.value,onSelect:()=>(e=>{if(l)if(r){const a=T.includes(e)?T.filter(a=>a!==e):[...T,e];l(a)}else l(e),S(!1)})(e.value),className:"cursor-pointer",children:[a(I,{className:Fi("mr-2 h-4 w-4",T.includes(e.value)?"opacity-100":"opacity-0")}),e.label]},e.value))})})]})})]})]})}function Rs({multiple:e=!1,options:r,items:n,value:i,onChange:o,onValueChange:s,getOptionValue:l=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:p,searchPlaceholder:h,disabled:f=!1,required:g=!1,isLoading:v=!1,error:b,className:x,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:w,onOpen:_,onClose:C,clearable:k=!0}){const{t:S}=Ga(),A=r||n||[],E=s||o,D=c||S("select_placeholder","Selecione..."),P=p||S("no_results",S("no_results")),I=h||S("search_placeholder","Pesquisar...");if(v)return t("div",{className:Fi("space-y-2",x),children:[u&&t(Hi,{children:[u,g&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ps,{className:"h-10 w-full"})]});const T="string"==typeof b?b:b instanceof Error?b.message:b?S("error_loading",S("error_loading")):void 0;return T?t("div",{className:Fi("space-y-2",x),children:[u&&t(Hi,{children:[u,g&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[a(O,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:T})]})]}):a(Ts,{multiple:e,options:A,value:i||(e?[]:""),onChange:E,getOptionValue:l,getOptionLabel:d,placeholder:D,label:u,icon:m,emptyMessage:P,searchPlaceholder:I,disabled:f,required:g,className:x,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:_,onClose:C,clearable:k})}const Ms=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ls(e,a){if(!a)return null;const t=Ms(a),r=[];for(const n of e){const e=Ms(n.label).includes(t),i=n.children?Ls(n.children,a):null,o=i&&i.length>0;(e||o)&&r.push({...n,children:e?n.children:o?i:n.children})}return r}function zs(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=zs(t.children,a);if(e)return e}}}function Fs({node:e,level:r,expanded:n,onToggleExpand:i,selectedValues:o,onSelect:s}){const l=e.children&&e.children.length>0,d=o.includes(e.value);return t("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":d,className:Fi("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[t("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:a=>{a.stopPropagation(),s(e.value)},children:[a(I,{className:Fi("h-4 w-4 shrink-0",d?"opacity-100":"opacity-0")}),(()=>{const t=d?e.iconSelected??(n?e.iconOpen:null)??e.icon:n?e.iconOpen??e.icon:e.icon;return t?a(t,{className:Fi("h-4 w-4 shrink-0",e.iconClassName||"text-muted-foreground")}):null})(),a("span",{className:"truncate",children:e.label})]}),l&&a("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted ml-auto",onClick:a=>{a.stopPropagation(),i(e.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:a(n?D:U,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Us({nodes:e,level:n,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:d}){return a(r,{children:e.map(e=>{const r=o.has(e.value);return t(i.Fragment,{children:[a(Fs,{node:e,level:n,expanded:r,onToggleExpand:s,selectedValues:l,onSelect:d}),r&&e.children&&e.children.length>0&&a(Us,{nodes:e.children,level:n+1,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:d})]},e.value)})})}function js({multiple:e=!1,options:r,value:n,onChange:i,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h=!1,required:f=!1,isLoading:g=!1,error:v,className:b,maxDisplayedBadges:x,popoverContainer:y,onOpen:N,onClose:w,defaultExpanded:_=!0}){const{t:C}=Ga(),[k,S]=o(!1),[A,P]=o(""),[I,T]=o(()=>_?function(e){const a=new Set;return function e(t){for(const r of t)r.children&&r.children.length>0&&(a.add(r.value),e(r.children))}(e),a}(r):new Set),R=d||C("select_placeholder","Selecione..."),M=m||C("no_results",C("no_results")),L=p||C("search_placeholder","Pesquisar..."),z=s(()=>n?Array.isArray(n)?n:[n]:[],[n]),F=s(()=>{if(!y)return;let e=y,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[y]),U=s(()=>Ls(r,A),[r,A])??r,j=s(()=>A?function(e,a){const t=new Set,r=Ms(a);function n(e){if(!e.children||0===e.children.length)return Ms(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||Ms(e.label).includes(r)}for(const i of e)n(i);return t}(r,A):new Set,[r,A]),$=A?j:I,V=l(e=>{A||T(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[A]),q=s(()=>z.map(e=>({value:e,label:zs(r,e)||e})),[z,r]),W=e=>{S(e),e?N?.():(P(""),w?.())},H=l(a=>{if(i)if(e){const e=z.includes(a)?z.filter(e=>e!==a):[...z,a];i(e)}else i(a),S(!1)},[i,e,z]),G=(a,t)=>{t.preventDefault(),t.stopPropagation(),i&&i(e?z.filter(e=>e!==a):"")},K=x?q.slice(0,x):q,Y=x&&q.length>x?q.length-x:0;if(g)return t("div",{className:Fi("space-y-2",b),children:[c&&t(Hi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ps,{className:"h-10 w-full"})]});const Q="string"==typeof v?v:v instanceof Error?v.message:v?C("error_loading",C("error_loading")):void 0;return t("div",Q?{className:Fi("space-y-2",b),children:[c&&t(Hi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[a(O,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:Q})]})]}:{className:Fi("space-y-2",b),children:[c&&t(Hi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(bs,{open:k,onOpenChange:W,modal:!1,children:[a(xs,{asChild:!0,children:e?t("div",{role:"combobox","aria-expanded":k,"aria-disabled":h,tabIndex:h?-1:0,onKeyDown:e=>{h||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),W(!k))},className:Fi("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",h&&"pointer-events-none opacity-50 cursor-not-allowed",0===q.length&&"text-muted-foreground"),children:[0===q.length?t("span",{className:"flex items-center gap-2",children:[u&&a(u,{className:"h-4 w-4"}),R]}):t("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[K.map(e=>t(Go,{variant:"secondary",className:"gap-1 pr-1",children:[e.label,a("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:a=>{"Enter"===a.key&&G(e.value,a)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:a=>G(e.value,a),children:a(E,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),Y>0&&t(Go,{variant:"outline",className:"gap-1",children:["+",Y]})]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]}):t($i,{variant:"outline",role:"combobox","aria-expanded":k,disabled:h,className:Fi("w-full justify-between min-h-10 h-auto font-normal",0===q.length&&"text-muted-foreground"),children:[0===q.length?t("span",{className:"flex items-center gap-2",children:[u&&a(u,{className:"h-4 w-4"}),R]}):t("span",{className:"flex items-center gap-2",children:[u&&a(u,{className:"h-4 w-4"}),q[0]?.label]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),t(ys,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:F,collisionBoundary:F,children:[t("div",{className:"flex items-center border-b px-3",children:[a(B,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:L,value:A,onChange:e=>P(e.target.value)}),A&&a("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:a(E,{className:"h-3.5 w-3.5"})})]}),a("div",{className:"max-h-[300px] overflow-y-auto overflow-x-hidden",children:a("div",{role:"tree",className:"p-1",children:0===U.length?a("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?M:C("no_search_results",C("no_results"))}):a(Us,{nodes:U,level:0,expandedIds:$,onToggleExpand:V,selectedValues:z,onSelect:H})})})]})]})]})}class Os{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 n=e.split(".");if(3!==n.length)return null;const i=n[1];i.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(i),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(i),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(i),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),i=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let o=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const s=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<s){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(n.exp&&n.exp<s){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}Os.LARGE_PAYLOAD_THRESHOLD=1e3;const Bs="qualiex_access_token",$s="qualiex_id_token",Vs="supabase_token",qs="oauth_state",Ws="oauth_nonce",Hs="selected_alias",Gs="manual_logout",Ks="supabase_project_id",Ys={setAccessToken:e=>localStorage.setItem(Bs,e),getAccessToken:()=>localStorage.getItem(Bs),setIdToken:e=>localStorage.setItem($s,e),getIdToken:()=>localStorage.getItem($s),getSupabaseToken:()=>localStorage.getItem(Vs),setOAuthState:e=>sessionStorage.setItem(qs,e),getOAuthState:()=>sessionStorage.getItem(qs),clearOAuthState:()=>sessionStorage.removeItem(qs),setOAuthNonce:e=>sessionStorage.setItem(Ws,e),getOAuthNonce:()=>sessionStorage.getItem(Ws),clearOAuthNonce:()=>sessionStorage.removeItem(Ws),setSelectedAlias:e=>localStorage.setItem(Hs,e),getSelectedAlias:()=>localStorage.getItem(Hs),clearSelectedAlias:()=>localStorage.removeItem(Hs),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ys.getAccessToken()||!Ys.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(Ks);return a&&a!==e?(Ys.clearAll(),localStorage.setItem(Ks,e),!0):(a||localStorage.setItem(Ks,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Vs,e),Ys._clearValidationCache()},areAllTokensValid:()=>{const e=Ys.getAccessToken(),a=Ys.getIdToken();if(!e||!a)return!1;try{const t=Os.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ys.getAccessToken(),t=Ys.getIdToken(),r=Ys.getSupabaseToken();return a&&Ys.isTokenExpired(a)&&(localStorage.removeItem(Bs),e=!0),t&&Ys.isTokenExpired(t)&&(localStorage.removeItem($s),e=!0),r&&Ys.isTokenExpired(r)&&(localStorage.removeItem(Vs),e=!0),e},clearAll:()=>{localStorage.removeItem(Bs),localStorage.removeItem($s),localStorage.removeItem(Vs),localStorage.removeItem(Hs),localStorage.removeItem(Gs),sessionStorage.removeItem(qs),sessionStorage.removeItem(Ws),Ys._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Gs,"true"),isManualLogout:()=>"true"===localStorage.getItem(Gs),clearManualLogout:()=>localStorage.removeItem(Gs),isTokenExpired:e=>{try{return Os.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ys._validationCache.isValid=!1,Ys._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ys.getSupabaseToken();if(!e)return!1;if(Ys.isTokenExpired(e))return Ys._clearValidationCache(),Ys._handleExpiredToken(),!1;const a=Date.now();return a-Ys._validationCache.timestamp<Ys._validationCache.cacheValidityMs?Ys._validationCache.isValid:(Ys._validationCache.isValid=!0,Ys._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ys.isSupabaseTokenValid()?Ys.getSupabaseToken():null,_handleExpiredToken:()=>{Ys.clearAll()},extractTokenData:()=>{if(!Ys.isSupabaseTokenValid())return null;const e=Ys.getSupabaseToken();if(!e)return null;try{const a=Os.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let i=a.company_id;if(!i&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){i=e[7];break}}}return{alias:t,companyId:i,placeId:r,placeName:n,payload:a}}catch(a){return Ys._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ys.getAccessToken();if(a)try{const t=Os.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}const t=Ys.extractTokenData();if(t?.companyId)return t.companyId;const r=Ys.getIdToken();if(r)try{const a=Os.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}return null},getCompanyIdInt:e=>{const a=[Ys.getAccessToken(),Ys.getIdToken()];for(const t of a)if(t)try{const a=Os.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=Ys.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ys.getIdToken();if(!e)return[];try{const a=Os.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.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[]}}};const Qs=new class{constructor(){this.errors=[],this.toastCount=0,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}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),a&&this.shouldShowToast()){const e=this.getErrorTitle(t);C.error(e,{description:t})}}getErrorTitle(a){const t=a.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?e.t("error_session_expired"):t.includes("token")||t.includes("autenticação")?e.t("error_authentication"):t.includes("api")||t.includes("network")?e.t("error_connection"):"Erro"}success(e,a){C.success(e,{description:a})}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=[]}};["[forlogic-core] ⚠️ VITE_SUPABASE_PUBLISHABLE_KEY contém uma legacy anon key (JWT).","O Supabase desativou legacy API keys. Substitua pela nova publishable key (formato sb_publishable_*).","Todas as requests retornarão 401 Unauthorized.","Causa provável: a integração Supabase do Lovable sobrescreveu o .env com a anon key legada.","Solução: defina VITE_SUPABASE_PK_OVERRIDE no .env com a publishable key correta."].join(" ");function Xs(e){return!!e&&e.startsWith("eyJ")}function Js(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE;return e||(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY??"")}let Zs=!1;const el=import.meta.env.VITE_SUPABASE_URL,al=Js();class tl{constructor(){this.currentToken=null,function(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE,a=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;Zs?Xs(a):e&&Xs(a)?Zs=!0:Xs(a)?Zs=!0:Zs=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:al};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Qa(el,al,{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 tl.instance||(tl.instance=new tl),tl.instance}getClient(){const e=Ys.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Os.isTokenExpired(e)}catch(a){return Qs.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function rl(){return tl.getInstance().getClient()}class nl{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Ys.getSupabaseToken();if(e&&Ys.isSupabaseTokenValid())return e}const n=rl(),{data:i,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(Ys.setSupabaseToken(i.access_token),i.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class il{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const a=Ys.getAccessToken(),t=Ys.getSelectedAlias();if(!a||!t)return null;const r=await nl.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}il.regenerationPromise=null,il.onLogoutCallback=null;class ol{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ys.clearAll(),window.location.href="/login",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].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.")}}}class sl{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 il.attemptRegeneration()?(this.isRetrying=!1,!0):(ol.handleError(e),this.isRetrying=!1,!1)}catch(r){return ol.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ys.getAccessToken();return e?Ys.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."}}}sl.isRetrying=!1;const ll=new class{get baseUrl(){return xr()}async makeApiCall(e,a,t){const r=sl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Ys.getAccessToken();if(!n)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 i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status} ${o.statusText}`);throw e.status=o.status,e.statusCode=o.status,e}return await o.json()}mapToQualiexUser(e){let a;return a="boolean"==typeof e.isActive?e.isActive:"boolean"==typeof e.active?e.active:"string"!=typeof e.status||"active"===e.status.toLowerCase(),{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0,isActive:a}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return Qs.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(e=>this.mapToQualiexUser(e)):(Qs.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a,t="active"){const r={companyId:a,search:"",filterStatus:t};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",r,e);return this.parseUsersResponse(a)??[]}catch(n){if(await sl.handleApiError(n))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",r,e);return this.parseUsersResponse(a," após retry")??[]}catch(i){return Qs.handleError(i instanceof Error?i:"Erro ao buscar usuários após renovação de token",!0),[]}return Qs.handleError(n instanceof Error?n.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Qs.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a,"active"),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async fetchAllUsersMap(e,a){const t=await this.fetchUsers(e,a,"all"),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e,a="active"){const t=Ys.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId,a):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(Qs.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await sl.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return Qs.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Qs.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(Qs.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await sl.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return Qs.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return Qs.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function dl(e,a){const t=a||Nr.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function cl(e,a){const t=a||Nr.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function ul(e,a){const t=a||Nr.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function ml(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||dl(e.idField),emailField:e.emailField||cl(e.idField),usernameField:e.usernameField||ul(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:dl(e),emailField:cl(e),usernameField:ul(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const pl=new Map;class hl{static async fetchQualiexUsers(e,a){const t=`${a}_${e}_all`,r=pl.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await ll.fetchUsers(e,a,"all");return pl.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[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 r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const i=t.get(a);if(i){if(n.nameField){r[n.nameField]||(r[n.nameField]=i.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=i.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=i.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!Ys.areAllTokensValid())return e;const t=Ys.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=ml(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const o=await this.fetchQualiexUsers(r,n),s=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,i,s))}catch(t){return Qs.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const fl=["responsible_name"],gl=e=>fl.includes(e);function vl(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:i,selectFields:o,schemaName:s,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Ys.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return rl().schema(s).from(n)},u=(e,a,t,r)=>{let n=c().select(o||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&i.length>0){const t=i.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const s=a.includes(".");return s||gl(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:s}},m=async(e,a,t,n,i)=>{const o=ml(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),s=a.includes(".");if(gl(a)||s||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await p.getAll(e);if(!o?.data?.length)return o;const d=await hl.enrichWithUserData(o.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=s?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",o=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",o=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(d,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(c,n,i);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalItems,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await hl.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},p={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:o,limit:s,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...o}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:o}})(e),{query:p}=u(a,t,i,c),h=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(p,o,s),{data:f,error:g,count:v}=await h;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let b=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],v,o,s);if((e=>{if(!d||!l||0===e.length)return!1;const a=ml(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,o,s);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await c().select(o||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Ui(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:i}=await c().insert(t).select().single();if(i)throw new Error(`Error creating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Ui(a),updated_at:(new Date).toISOString()},{data:r,error:i}=await c().update(t).eq("id",e).select().single();if(i)throw new Error(`Error updating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},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 ${n}: ${t.message}`)}};return p}var bl;const xl={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class yl{static async initialize(){try{if(Ys.checkProjectMismatch())return{...xl};if(!Ys.hasAllTokens()||!Ys.areAllTokensValid())return Ys.clearExpiredTokens(),{...xl};const e=Ys.getAccessToken(),a=Ys.getIdToken();Ys.clearManualLogout();const t=this.extractUserFromIdToken(a,e),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=Ys.extractTokenData(),o=i?.alias;let s=null;if(o&&r.some(e=>e.alias===o))s=o;else{const e=Ys.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);s=a?e:n||r[0]?.alias||null}if(!Ys.isSupabaseTokenValid()&&s&&await il.attemptRegeneration(),!Ys.isSupabaseTokenValid())return{...xl};let l=null;if(s){const e=Ys.getCompanyId(s),a=r.find(e=>e.alias===s);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const d=i?.placeId??null,c=i?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:s,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{...xl}}}static async loginDev(){try{const e=rl(),{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 r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";Ys.setOAuthState(e);const a=Ys.generateOAuthNonce();Ys.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(pr.oauth.authUrl);r.searchParams.set("client_id",pr.oauth.clientId),r.searchParams.set("response_type",pr.oauth.responseType),r.searchParams.set("scope",pr.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{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),r=t("access_token"),n=t("id_token"),i=t("error");if(i)throw new Error(`Erro OAuth: ${i}`);if(r&&n){const e=Ys.getAccessToken();e!==r&&Ys.clearAll()}if(Ys.hasAllTokens()){return Ys.getValidSupabaseToken()||await il.attemptRegeneration(!0),!0}const o=r,s=n;if(!o||!s)throw new Error("Tokens não encontrados na URL de callback");Ys.setAccessToken(o),Ys.setIdToken(s),Ys.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)Ys.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ys.setSelectedAlias(e[0].alias)}if(!await il.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return Ys.clearOAuthState(),Ys.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){Ys.setManualLogout(),Ys.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return Os.parseJwtPayload(e)}static extractUserFromIdToken(e,a){const t=this.decodeToken(e);if(!t)return null;const r=a?this.decodeToken(a):null;return{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier,isSysAdmin:"1"===r?.admin}}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 r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=a[e].split("|");r&&n&&t.push({id:"",alias:r.trim(),name:n.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}bl=yl,il.setLogoutCallback(()=>{bl.logout()});const Nl=e=>e?.placeId||null,wl=e=>e?.placeName||null,_l=d(void 0),Cl=({children:e})=>{const[t,r]=o({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=Xa()}catch{}const[i,d]=o(!1),c=u(0),p=l(e=>{r(a=>({...a,...e}))},[]),h=l(e=>{r(a=>({...a,isLoading:e}))},[]),f=l(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=l(async e=>{if(e.alias===t.alias)return;const a=++c.current;try{const i=Ys.getAccessToken();if(!i)return;const o=await nl.generateToken(i,e.alias,void 0,!0);if(c.current!==a)return;if(!o)return;Ys.setSupabaseToken(o),Ys.setSelectedAlias(e.alias);const s=Ys.extractTokenData(),l=s?.alias||e.alias,d=s?.companyId||Ys.getCompanyId(e.alias),u={id:d||e.id,name:e.name,alias:l};let m=null,h=null;if(t.user?.id&&l&&d)try{const e=await ll.fetchActiveUsersMap(l,d);if(c.current!==a)return;const r=e.get(t.user.id);if(r){const e=(e=>({placeId:Nl(e),placeName:wl(e)}))(r);m=e.placeId,h=e.placeName}}catch(r){}if(c.current!==a)return;p({alias:l,selectedUnit:u,placeId:m,placeName:h,activePlaceId:m,activePlaceName:h}),n&&await n.clear()}catch(r){}},[p,n,t.user,t.alias]),v=l(async()=>{const e=await yl.processCallback();if(e){const e=await yl.initialize();e&&e.isAuthenticated&&(p({user:e.user,companies:e.companies,alias:e.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:e.selectedUnit,userId:e.userId,userAlias:e.userAlias,placeId:e.placeId,placeName:e.placeName,activePlaceId:e.activePlaceId,activePlaceName:e.activePlaceName}),n&&n.invalidateQueries({queryKey:["permission"]}))}return e},[p,n]),b=l(async()=>{await yl.logout(),f(),n&&await n.clear()},[f,n]),x=l(e=>{d(e)},[]),y=l(()=>{},[]),N=l(()=>{n&&n.invalidateQueries()},[n]);m(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(async()=>{if(e)if(Ys.areAllTokensValid()){if(!Ys.isSupabaseTokenValid())try{await il.attemptRegeneration()||e&&b()}catch(a){e&&b()}}else e&&b()},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,b]),m(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await yl.initialize();if(!e)return;a&&a.isAuthenticated?p({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&&h(!1)}catch(a){e&&(ol.handleError(a),h(!1))}})(),()=>{e=!1}},[p,h,b]);const w=s(()=>({...t,logout:b,processCallback:v,switchUnit:g,availableUnits:t.companies,isSearchVisible:i,setSearchVisible:x,clearSearch:y,refreshData:N}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,b,v,g,i,x,y,N]);return a(_l.Provider,{value:w,children:e})},kl=()=>{const e=c(_l);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Sl({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:i}){const[d,c]=tt(),u=Xa(),{alias:m,userId:p,isAuthenticated:h}=kl(),{t:f}=Ga(),g=l(a=>{const t=`${e}_${a}`,r=d.get(t);return r||(d.get(a)||"")},[d,e]),v=g("search"),b=g("sortField")||hr.sorting.defaultField,x=g("sortDirection")||hr.sorting.defaultDirection,y=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(hr.pagination.defaultPageSize)),w=v,_=s(()=>({search:w,sortField:b,sortDirection:x,page:y,limit:N,...n}),[w,b,x,y,N,n]),k=l(()=>a.getAll(_),[a,_]),S=Ja({queryKey:[e,m,p,_],queryFn:k,enabled:!!m&&h});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=Za({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(_r.success.created(t)),i?.()},onError:e=>{C.error(`${_r.error.create(t)}: ${e.message}`)}}),E=Za({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(_r.success.updated(t)),i?.()},onError:e=>{C.error(`${_r.error.update(t)}: ${e.message}`)}}),D=Za({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(_r.success.deleted(t))},onError:e=>{C.error(`${_r.error.delete(t)}: ${e.message}`)}}),P=l(a=>{const t={...Object.fromEntries(d)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[d,c,e]),I=l(e=>{P({search:e,page:1})},[P]),T=l(e=>{P({sortField:e,sortDirection:b===e&&"asc"===x?"desc":"asc",page:1})},[b,x,P]),R=l(e=>{P({page:e})},[P]),M=l(e=>{P({limit:e,page:1})},[P]),L=l(()=>{const a=Object.fromEntries(d),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,d,e]),[z,F]=o([]),U=l(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=l(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=l(()=>{F([])},[]),B=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),$=Za({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),C.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{C.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),V=l((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||hr.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:D?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:b,sortDirection:x,currentPage:y,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:D.mutate,save:V,handleSearch:I,handleSort:T,handlePageChange:R,handleItemsPerPageChange:M,clearFilters:L,refetch:S.refetch,selectedIds:z,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Al(e){const a=vl({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,r)=>Sl({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function El(e){const[a,t]=o(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return m(()=>{const a=window.matchMedia(e);t(a.matches);const r=e=>{t(e.matches)};return a.addEventListener("change",r),()=>a.removeEventListener("change",r)},[e]),a}function Dl(e=768){return El(`(max-width: ${e-1}px)`)}const Pl=n.forwardRef(({className:e,...t},r)=>a("table",{ref:r,className:Fi("w-full caption-bottom text-[13px] table-fixed",e),...t}));Pl.displayName="Table";const Il=n.forwardRef(({className:e,...t},r)=>a("thead",{ref:r,className:Fi("[&_tr]:border-b sticky top-0 z-[1] bg-background",e),...t}));Il.displayName="TableHeader";const Tl=n.forwardRef(({className:e,...t},r)=>a("tbody",{ref:r,className:Fi("[&_tr:last-child]:border-0",e),...t}));Tl.displayName="TableBody";const Rl=n.forwardRef(({className:e,...t},r)=>a("tfoot",{ref:r,className:Fi("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));Rl.displayName="TableFooter";const Ml=n.forwardRef(({className:e,...t},r)=>a("tr",{ref:r,className:Fi("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",e),...t}));Ml.displayName="TableRow";const Ll=n.forwardRef(({className:e,...t},r)=>a("th",{ref:r,className:Fi("h-9 px-4 py-2 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",e),...t}));Ll.displayName="TableHead";const zl=n.forwardRef(({className:e,...t},r)=>a("td",{ref:r,className:Fi("px-4 py-2 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",e),...t}));zl.displayName="TableCell";const Fl=n.forwardRef(({className:e,...t},r)=>a("caption",{ref:r,className:Fi("mt-4 text-sm text-muted-foreground",e),...t}));function Ul({rows:e=5,columns:r=4}){return a("div",{className:"w-full",children:t("div",{className:"rounded-md border",children:[a("div",{className:"border-b bg-muted/50 px-4 py-3",children:a("div",{className:"flex space-x-4",children:Array.from({length:r}).map((e,t)=>a(Ps,{className:"h-4 w-24"},t))})}),a("div",{children:Array.from({length:e}).map((e,t)=>a("div",{className:"border-b px-4 py-3 last:border-0",children:a("div",{className:"flex space-x-4",children:Array.from({length:r}).map((e,t)=>a(Ps,{className:"h-4 w-20"},t))})},t))})]})})}function jl({count:e=3}){return a("div",{className:"space-y-4",children:Array.from({length:e}).map((e,r)=>t(Gi,{children:[t(Ki,{children:[a(Ps,{className:"h-4 w-3/4"}),a(Ps,{className:"h-3 w-1/2"})]}),a(Xi,{children:t("div",{className:"space-y-2",children:[a(Ps,{className:"h-3 w-full"}),a(Ps,{className:"h-3 w-2/3"})]})})]},r))})}function Ol({fields:e=4}){return t("div",{className:"space-y-4",children:[Array.from({length:e}).map((e,r)=>t("div",{className:"space-y-2",children:[a(Ps,{className:"h-4 w-24"}),a(Ps,{className:"h-10 w-full"})]},r)),t("div",{className:"flex justify-end space-x-2 pt-4",children:[a(Ps,{className:"h-10 w-20"}),a(Ps,{className:"h-10 w-20"})]})]})}function Bl(){return t("div",{className:"flex items-center justify-between p-4 border-b",children:[t("div",{className:"flex items-center space-x-3",children:[a(Ps,{className:"h-8 w-8 rounded-full"}),a(Ps,{className:"h-6 w-32"})]}),t("div",{className:"flex items-center space-x-2",children:[a(Ps,{className:"h-8 w-8"}),a(Ps,{className:"h-8 w-24"})]})]})}function $l(){return a("div",{className:"w-64 border-r bg-muted/10",children:t("div",{className:"p-4",children:[a(Ps,{className:"h-8 w-32 mb-6"}),a("div",{className:"space-y-2",children:Array.from({length:6}).map((e,r)=>t("div",{className:"flex items-center space-x-3 p-2",children:[a(Ps,{className:"h-4 w-4"}),a(Ps,{className:"h-4 w-20"})]},r))})]})})}Fl.displayName="TableCaption";const Vl={default:$,search:B,error:O};function ql({icon:e,title:r,description:n,action:i,className:o,variant:s="default"}){const{t:l}=Ga(),d=!!e,c=Vl[s];return t("div",{className:Fi("flex flex-col items-center justify-center py-12 px-4 text-center",o),children:[a("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:d?e:a(c,{className:"h-8 w-8 text-muted-foreground"})}),a("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&a("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),i&&a($i,{onClick:i.onClick,variant:"outline",children:i.label})]})}function Wl({children:e,className:r}){const i=n.useRef(null),[o,s]=n.useState(!1);n.useEffect(()=>{const e=()=>{const e=i.current;e&&s(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return i.current&&a.observe(i.current),()=>a.disconnect()},[e]);const l=a("div",{ref:i,className:`truncate w-full max-w-full ${r||""}`,children:e});return o?a(ps,{delayDuration:300,children:t(hs,{children:[a(fs,{asChild:!0,children:l}),a(gs,{side:"top",className:"max-w-[400px] break-words",children:e})]})}):l}const Hl=n.forwardRef(({direction:e,onMouseDown:t,isDragging:r,className:n},i)=>{const o="horizontal"===e;return a("div",{ref:i,onMouseDown:t,className:Fi("absolute z-20 select-none touch-none","transition-colors duration-150",o&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!o&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:a("div",{className:Fi("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});Hl.displayName="TableResizeHandle";const Gl=lt.Root,Kl=lt.Trigger,Yl=lt.Group,Ql=lt.Portal,Xl=lt.Sub,Jl=lt.RadioGroup,Zl=n.forwardRef(({className:e,inset:r,children:n,...i},o)=>t(lt.SubTrigger,{ref:o,className:Fi("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",e),...i,children:[n,a(U,{className:"ml-auto h-4 w-4"})]}));Zl.displayName=lt.SubTrigger.displayName;const ed=n.forwardRef(({className:e,...t},r)=>a(lt.SubContent,{ref:r,className:Fi("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));ed.displayName=lt.SubContent.displayName;const ad=n.forwardRef(({className:e,...t},r)=>a(lt.Portal,{children:a(lt.Content,{ref:r,className:Fi("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t})}));ad.displayName=lt.Content.displayName;const td=n.forwardRef(({className:e,inset:t,...r},n)=>a(lt.Item,{ref:n,className:Fi("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));td.displayName=lt.Item.displayName;const rd=n.forwardRef(({className:e,children:r,checked:n,...i},o)=>t(lt.CheckboxItem,{ref:o,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...i,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(lt.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),r]}));rd.displayName=lt.CheckboxItem.displayName;const nd=n.forwardRef(({className:e,children:r,...n},i)=>t(lt.RadioItem,{ref:i,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(lt.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));nd.displayName=lt.RadioItem.displayName;const id=n.forwardRef(({className:e,inset:t,...r},n)=>a(lt.Label,{ref:n,className:Fi("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",e),...r}));id.displayName=lt.Label.displayName;const od=n.forwardRef(({className:e,...t},r)=>a(lt.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-border",e),...t}));od.displayName=lt.Separator.displayName;const sd=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});sd.displayName="ContextMenuShortcut";const ld=({onEdit:e,onDelete:n,onToggleStatus:i,isActive:o=!0,canDelete:s=!0,customActions:l=[],renderAs:d})=>{const{t:c}=Ga(),u=[];if(e){const a={icon:V,label:c("edit"),onClick:e};u.push(a)}if(l.forEach(e=>{u.push(e)}),i){const e={icon:o?q:W,label:o?"Inativar":"Ativar",onClick:i};u.push(e)}if(s&&n){const e={icon:H,label:c("ap_delete"),onClick:n,destructive:!0};u.push(e)}const m="dropdown"===d?ss:td;return a(r,{children:u.map((e,r)=>t(m,{onClick:e.onClick,className:Fi("whitespace-normal cursor-pointer",e.destructive&&"text-destructive focus:text-destructive"),children:[a(e.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.label]},r))})},dd=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:a(A,{size:12})})}),a(os,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:a(ld,{onEdit:e?a=>{a?.stopPropagation(),e?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:i?e=>{e?.stopPropagation(),i?.()}:void 0,isActive:o,canDelete:n&&!!r,customActions:s,renderAs:"dropdown"})})]}),cd=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>{const{t:l}=Ga();return a(ps,{delayDuration:200,children:t("div",{className:"flex items-center justify-end gap-0.5",children:[e&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e()},children:a(G,{size:14})})}),a(gs,{children:l("edit")})]}),s.map((e,r)=>{const n=e.icon;return t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e.onClick()},children:a(n,{size:14})})}),a(gs,{children:e.label})]},r)}),i&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:a(o?K:Y,{size:14})})}),a(gs,{children:o?"Inativar":"Ativar"})]}),r&&n&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:Fi("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:a(H,{size:14})})}),a(gs,{children:l("ap_delete")})]})]})})},ud=150;function md({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=o(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??ud,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??ud,e),{})}),[s,d]=o(!1),[c,p]=o(null),h=u(0),f=u(0),g=l((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),d(!0),p(e),h.current=a.clientX,f.current=n[e]??ud)},[r,n]);m(()=>{if(!s||!c)return;const r=e.find(e=>e.key===c),n=r?.minWidth??60,o=r?.maxWidth??500,l=e=>{const a=e.clientX-h.current,r=Math.max(n,Math.min(o,f.current+a));i(e=>{const a={...e,[c]:r};return t?.(a),a})},u=()=>{d(!1),p(null),a&&i(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",l),document.addEventListener("mouseup",u),()=>{document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",u)}},[s,c,e,a,t]),m(()=>(s?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[s]);const v=l(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??ud,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:s,activeColumn:c,handleMouseDown:g,resetWidths:v}}const pd=v("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"}}),hd=n.forwardRef(({className:e,variant:t,size:r,...n},i)=>a(ct.Root,{ref:i,className:Fi(pd({variant:t,size:r,className:e})),...n}));hd.displayName=ct.Root.displayName;const fd=n.createContext({size:"default",variant:"default"}),gd=n.forwardRef(({className:e,variant:t,size:r,children:n,...i},o)=>a(dt.Root,{ref:o,className:Fi("flex items-center justify-center gap-1",e),...i,children:a(fd.Provider,{value:{variant:t,size:r},children:n})}));gd.displayName=dt.Root.displayName;const vd=n.forwardRef(({className:e,children:t,variant:r,size:i,...o},s)=>{const l=n.useContext(fd);return a(dt.Item,{ref:s,className:Fi(pd({variant:l.variant||r,size:l.size||i}),e),...o,children:t})});vd.displayName=dt.Item.displayName;const bd=p(function({onNew:e,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:o="",onSearchChange:s,searchPlaceholder:l,showBulkActions:d=!1,selectedCount:c=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:p,customActions:h=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:b=!1,availableViewModes:x=["table","list","grid"],rightSlot:y,className:N}){const{t:w}=Ga(),_=c>0,C=e&&n||h.length>0,k=f||b||y,S=i&&s;return C||S||k||d&&_?t("div",{className:Fi("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",N),children:[t("div",{className:"flex items-center gap-2 shrink-0",children:[e&&n&&t($i,{onClick:e,children:[a(Q,{size:16,className:"mr-2"}),r||"Novo"]}),h.map((e,r)=>{const n=e.icon;return t($i,{onClick:e.action,variant:e.variant||"outline",disabled:e.disabled,title:e.disabled?e.disabledReason:void 0,children:[n&&a(n,{size:16,className:"mr-2"}),e.label]},r)})]}),d&&_&&t("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[a(Go,{variant:"secondary",className:"mr-1 tabular-nums",children:c}),t(ps,{delayDuration:200,children:[u.length>0?u.map((e,r)=>{const n=e.icon,i=e.disabled;return t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:Fi("h-8 w-8","destructive"===e.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:i,onClick:()=>e.action([]),children:n?a(n,{size:16}):a("span",{className:"text-xs",children:e.label[0]})})}),a(gs,{children:e.label})]},r)}):t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:a(H,{size:16})})}),a(gs,{children:w("ap_delete")})]}),t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:a(E,{size:16})})}),a(gs,{children:w("clear_selection")})]})]})]}),S&&a("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:t("div",{className:"relative w-full",children:[a(B,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{type:"text",placeholder:l||"Pesquisar",value:o,onChange:e=>s?.(e.target.value),className:"pl-9 w-full"})]})}),k&&t("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&g&&v&&a(gd,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:x.map(e=>{const t=(e=>{switch(e){case"table":return Z;case"list":return J;case"grid":return X}})(e);return a(vd,{value:e,"aria-label":"Visualizar como "+("table"===e?"tabela":"list"===e?"lista":"grade"),children:a(t,{className:"h-4 w-4"})},e)})}),y]})]}):null}),xd=p(({checked:e,onCheckedChange:t})=>a(qo,{checked:e,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function yd(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let r=t.groupByColumns||[];return 0===r.length&&t.groupByColumn&&(r=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:r}}catch{return null}}function Nd({columns:e,storageKey:a,enabled:t=!0,defaultHiddenColumns:r}){const n=s(()=>e.map(e=>String(e.key)),[e]),i=s(()=>new Set(r??[]),[r]),[d,c]=o(()=>{if(!t)return i;if(!a)return i;const e=yd(a);return e?.hiddenColumns??i}),[u,p]=o(()=>{if(!t||!a)return n;const e=yd(a)?.columnOrder;return e&&e.length>0?e:n}),[h,f]=o(()=>t&&a?yd(a)?.groupByColumns??[]:[]),[g,v]=o(new Set);m(()=>{t&&a&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(a,{hiddenColumns:d,columnOrder:u,groupByColumns:h})},[d,u,h,a,t]),m(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(u),r=[...a].filter(e=>!t.has(e));r.length>0&&p(e=>[...e.filter(e=>a.has(e)),...r])},[e]);const b=l(e=>d.has(e),[d]),x=l(e=>{c(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),y=l(()=>{c(new Set)},[]),N=l(()=>{if(c(i),p(n),f([]),v(new Set),a)try{localStorage.removeItem(a)}catch{}},[n,i,a]),w=l((e,a)=>{p(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),_=l(e=>{v(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),C=l(e=>{f(e),v(new Set)},[]),k=l(e=>{f(a=>a.includes(e)?a:[...a,e])},[]),S=l(e=>{f(a=>a.filter(a=>a!==e)),v(a=>{const t=new Set;for(const r of a)r.includes(`${e}:`)||t.add(r);return t})},[]),A=l((e,a)=>{f(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r}),v(new Set)},[]),E=h[0]??null,D=l(e=>{f(e?[e]:[]),v(new Set)},[]),P=s(()=>{if(!t)return e;const a=new Map(e.map(e=>[String(e.key),e]));return u.filter(e=>!d.has(e)&&a.has(e)).map(e=>a.get(e))},[e,u,d,t]),I=l(e=>{if(0===h.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,r,n){if(0===t.length)return[{groupKey:n||"__leaf__",groupValue:"",items:a,count:a.length,level:r}];const[i,...o]=t,s=new Map;for(const l of a){const e=String(l[i]??"(vazio)");s.has(e)||s.set(e,[]),s.get(e).push(l)}return Array.from(s.entries()).map(([a,t])=>{const s=n?`${n}|${i}:${a}`:`${i}:${a}`,l=o.length>0?e(t,o,r+1,s):void 0;return{groupKey:s,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,h,0,"")},[h]);return{visibleColumns:P,allColumns:e,isColumnHidden:b,toggleColumn:x,showAllColumns:y,resetColumns:N,columnOrder:u,reorderColumns:w,groupByColumn:E,setGroupByColumn:D,groupByColumns:h,setGroupByColumns:C,addGroupByColumn:k,removeGroupByColumn:S,reorderGroupByColumns:A,getGroupedData:I,collapsedGroups:g,toggleGroupCollapse:_}}function wd({enabled:e=!1,onReorder:a}){const[t,r]=o(null),[n,i]=o(null),d=l(()=>{r(null),i(null)},[]),c=l((n,o)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),o&&a.dataTransfer.setData("application/column-key",o))},onDragOver:a=>{e&&null!==t&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==t&&(a.preventDefault(),i(n))},onDrop:r=>{r.preventDefault(),e&&null!==t&&t!==n?(a(t,n),d()):d()},onDragEnd:()=>{d()}}),[e,t,a,d]);return s(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:c}),[t,n,c])}function _d({columns:e,columnOrder:r,isColumnHidden:n,toggleColumn:i,showAllColumns:s,reorderColumns:l,groupByColumn:d,setGroupByColumn:c,groupByColumns:m=[],addGroupByColumn:p,removeGroupByColumn:h,resetColumns:f}){const{t:g}=Ga(),[v,b]=o(null),[x,y]=o(null),N=u(null),w=new Map(e.map(e=>[String(e.key),e])),_=r.filter(e=>w.has(e)).map(e=>w.get(e)),C=()=>{N.current=null,b(null),y(null)};_.some(e=>n(String(e.key)));const k=_.every(e=>!n(String(e.key)));return t(bs,{children:[a(xs,{asChild:!0,children:a($i,{variant:"outline",size:"icon",className:"h-8 w-8",children:a(ee,{size:16})})}),t(ys,{className:"w-[260px] p-0",align:"end",children:[a("div",{className:"px-3 py-2 border-b",children:a("span",{className:"text-sm font-medium",children:"Colunas"})}),a("div",{className:"max-h-[300px] overflow-auto py-1",children:a(ps,{delayDuration:300,children:_.map((e,r)=>{const o=String(e.key),s=n(o),u=!1!==e.hideable,f=!0===e.groupable,w=m.includes(o)||d===o;return t("div",{draggable:!0,onDragStart:()=>(e=>{N.current=e,b(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),y(a)})(e,r),onDrop:()=>(e=>{null!==N.current&&N.current!==e&&l(N.current,e),N.current=null,b(null),y(null)})(r),onDragEnd:C,className:Fi("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",v===r&&"opacity-50",x===r&&"border-t-2 border-primary"),children:[a(ae,{size:14,className:"text-muted-foreground shrink-0"}),a(qo,{checked:!s,onCheckedChange:()=>u&&i(o),disabled:!u,className:"shrink-0"}),a("span",{className:Fi("flex-1 truncate",s&&"text-muted-foreground"),children:e.header}),f&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:Fi("h-6 w-6 shrink-0",w&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),w?h?h(o):c?.(null):p?p(o):c?.(o)},children:a(te,{size:14})})}),a(gs,{children:g(w?"remove_grouping":"group_by_column")})]})]},o)})})}),t("div",{className:"border-t px-3 py-2 space-y-1",children:[a($i,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:k?()=>_.filter(e=>!1!==e.hideable).forEach(e=>i(String(e.key))):s,children:g(k?"deselect_all":"select_all_columns")}),f&&a($i,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Cd({columns:e,groupByColumns:r,addGroupByColumn:n,removeGroupByColumn:s,reorderGroupByColumns:l}){const[d,c]=o(!1),[u,m]=o(null),[p,h]=o(null),f=new Map(e.map(e=>[String(e.key),e])),g=()=>{m(null),h(null)},v=r.length>0;return t("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",c(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||c(!1)},onDrop:e=>{e.preventDefault(),c(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!r.includes(a)){const e=f.get(a);e&&e.groupable&&n(a)}},className:Fi("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",d&&"bg-primary/5 border-primary/30",!v&&"text-muted-foreground"),children:[a(te,{size:14,className:"shrink-0 text-muted-foreground"}),a("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:v?r.map((e,r)=>{const n=f.get(e);if(!n)return null;const o=u===r,d=p===r&&u!==r;return t(i.Fragment,{children:[r>0&&a("span",{className:"text-xs text-muted-foreground",children:"›"}),t(Go,{variant:"secondary",className:Fi("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",o&&"opacity-50",d&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,a)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(a)),e.dataTransfer.effectAllowed="move",m(a)})(e,r),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),h(a)})(e,r),onDrop:e=>((e,a)=>{e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("application/group-chip-index");if(""!==t){const e=parseInt(t,10);isNaN(e)||e===a||l(e,a)}m(null),h(null)})(e,r),onDragEnd:g,children:[n.header,a("button",{onClick:a=>{a.stopPropagation(),s(e)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:a(E,{size:12})})]})]},e)}):a("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const kd=({manager:r,columns:n,onEdit:d,onView:c,onToggleStatus:u,onDelete:p,renderActions:h,customRowActions:f,enableBulkActions:g=!1,rowActionsVariant:v="dropdown",onNew:b,newButtonLabel:x,showNewButton:y=!0,customActions:N=[],hideActionBar:w,showActionBar:_=!0,showSearch:C=!1,searchValue:k,onSearchChange:S,searchPlaceholder:A,bulkActions:E=[],onBulkDelete:P,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M=!1,enableColumnResize:L=!0,resizeStorageKey:z,enableColumnManager:F=!0,columnManagerStorageKey:j,defaultHiddenColumns:O,enableGrouping:B=!1,enableExpandableRows:$=!1,renderExpandedContent:V,expandedRowIds:q,onToggleExpand:W,defaultExpandAll:H=!1,hideActionsColumn:G=!1})=>{const{t:K}=Ga(),{setSearchVisible:Y}=kl(),Q=Dl(),[X,J]=o(()=>H&&$?new Set(r.entities.map(e=>e.id)):new Set),Z=void 0!==q,ee=Z?new Set(q):X,ae=l(e=>{Z&&W?W(e):J(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[Z,W]),te=void 0!==w?!w:_;m(()=>{if(!C)return Y(!0),()=>Y(!1)},[Y,C]);const ie=Nd({columns:n,storageKey:j,enabled:F,defaultHiddenColumns:O}),oe=wd({enabled:F,onReorder:ie.reorderColumns}),se=F?ie.visibleColumns:n,{columnWidths:le,isDragging:de,activeColumn:ce,handleMouseDown:ue}=md({columns:se.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:z?`${z}-columns`:void 0,enabled:L}),me=s(()=>(()=>{if(L){const e=se.map(e=>le[String(e.key)]??e.width??e.minWidth??150),a=e.reduce((e,a)=>e+a,0);return se.map((t,r)=>({...t,calculatedWidth:e[r],style:{width:e[r]/a*100+"%"}}))}let e=0;const a=se.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,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`}})})(),[se,L,le]),pe=b||N.length>0||C||g||I||M||F,he=te&&pe,fe=P||(()=>{r.bulkDelete?.(r.selectedIds)}),ge=e=>a(zl,{className:"text-center",children:h?h(e):"inline"===v?a("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:a(cd,{onEdit:d?()=>d(e):void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,customActions:f?f(e):[]})}):a(dd,{onEdit:d?()=>d(e):void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,customActions:f?f(e):[]})}),ve=e=>a(ad,{className:"w-[160px]",children:a(ld,{onEdit:d?()=>d(e):void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,canDelete:!!p,customActions:f?f(e):[],renderAs:"context"})}),be=F?a(_d,{columns:n,columnOrder:ie.columnOrder,isColumnHidden:ie.isColumnHidden,toggleColumn:ie.toggleColumn,showAllColumns:ie.showAllColumns,resetColumns:ie.resetColumns,reorderColumns:ie.reorderColumns,groupByColumn:B?ie.groupByColumn:void 0,setGroupByColumn:B?ie.setGroupByColumn:void 0,groupByColumns:B?ie.groupByColumns:void 0,addGroupByColumn:B?ie.addGroupByColumn:void 0,removeGroupByColumn:B?ie.removeGroupByColumn:void 0}):void 0;if(Q)return r.isLoading?a(jl,{count:3}):0===r.entities.length?a(ql,{title:e.t("no_items_found_empty"),description:e.t("no_data_to_display"),variant:"search"}):t("div",{className:"flex flex-col h-full",children:[he&&a(bd,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:E,onBulkDelete:fe,onClearSelection:r.clearSelection,customActions:N,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M}),a("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:r.entities.map(e=>t(Gl,{children:[a(Kl,{asChild:!0,children:a(Gi,{className:Fi("overflow-hidden cursor-pointer hover:bg-muted/50",g&&r.selectedIds.includes(e.id)&&"bg-muted"),onClick:a=>{a.stopPropagation(),g?r.selectItem(e.id):d?.(e)},children:a(Xi,{className:"p-4",children:t("div",{className:"flex items-start gap-3",children:[g&&a("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:a(xd,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),t("div",{className:"flex-1",children:[se.map(r=>t("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[t("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[r.header,":"]}),a("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:r.render?r.render(e):String(e[r.key]??"")})]},String(r.key))),(d||c||h)&&a("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:h?h(e):a(dd,{onEdit:d?()=>{d(e)}:void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,customActions:f?f(e):[]})})]})]})})})}),ve(e)]},e.id))})]});const xe=B&&ie.groupByColumns.length>0?ie.getGroupedData(r.entities):null,ye=null!==xe,Ne=($?1:0)+(g?1:0)+se.length+(G?0:1),we=e=>{const n=$&&ee.has(e.id);return t(i.Fragment,{children:[t(Gl,{children:[a(Kl,{asChild:!0,children:t(Ml,{className:Fi("cursor-pointer hover:bg-muted/50 relative",("inline"===v||G)&&"group",g&&r.selectedIds.includes(e.id)&&"bg-muted"),onClick:a=>{a.stopPropagation(),g?r.selectItem(e.id):d?.(e)},children:[$&&a(zl,{className:"w-[40px] px-2",children:a("button",{onClick:a=>{a.stopPropagation(),ae(e.id)},className:"p-1 rounded-sm hover:bg-muted transition-colors","aria-label":K(n?"collapse_row":"expand_row"),children:a(n?D:U,{size:16,className:"text-muted-foreground"})})}),g&&a(zl,{onClick:e=>e.stopPropagation(),children:a(xd,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),se.map(t=>a(zl,{className:t.className,children:a(Wl,{children:t.render?t.render(e):String(e[t.key]??"")})},String(t.key))),!G&&ge(e)]})}),ve(e)]}),n&&V&&a(Ml,{className:"bg-muted/30 hover:bg-muted/30",children:a(zl,{colSpan:Ne,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:V(e)})})})]},e.id)},_e=(e,r)=>{const{t:n}=Ga();return e.map(e=>{const n=ie.collapsedGroups.has(e.groupKey),o=16*e.level,s=Math.max(30,70-15*e.level);return t(i.Fragment,{children:[a(Ml,{className:Fi("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${s}%)`},onClick:()=>ie.toggleGroupCollapse(e.groupKey),children:a(zl,{colSpan:r,className:"py-2 px-4",children:t("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${o}px`},children:[a(n?U:D,{size:16}),a("span",{children:e.groupValue}),t("span",{className:"text-muted-foreground font-normal",children:["(",e.count,")"]})]})})}),!n&&(e.children?_e(e.children,r):e.items.map(we))]},e.groupKey)})};return t("div",{className:"flex flex-col h-full",children:[he&&a(bd,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:E,onBulkDelete:fe,onClearSelection:r.clearSelection,customActions:N,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M}),r.isLoading?a(Ul,{rows:5,columns:se.length}):t("div",{className:"flex flex-col h-full overflow-hidden",children:[B&&a(Cd,{columns:n,groupByColumns:ie.groupByColumns,addGroupByColumn:ie.addGroupByColumn,removeGroupByColumn:ie.removeGroupByColumn,reorderGroupByColumns:ie.reorderGroupByColumns}),a("div",{className:"flex-1 overflow-auto",children:t(Pl,{className:"table-fixed w-full",children:[t("colgroup",{children:[$&&a("col",{style:{width:"40px"}}),g&&a("col",{style:{width:"50px"}}),me.map((e,t)=>a("col",{style:e.style},t)),!G&&a("col",{style:{width:"inline"===v?"auto":"50px",minWidth:"50px"}})]}),a(Il,{children:t(Ml,{children:[$&&a(Ll,{className:"w-[40px]"}),g&&a(Ll,{className:"w-[50px]",children:a(xd,{checked:r.isAllSelected,onCheckedChange:r.selectAll})}),se.map((e,n)=>{const i=L&&!1!==e.resizable,o=ce===String(e.key),s=F?oe.getDragProps(n,String(e.key)):{},l=oe.dragFromIndex===n,d=oe.dragOverIndex===n&&oe.dragFromIndex!==n;return t(Ll,{className:Fi(e.className,!1!==e.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",F&&oe.isDragging&&"cursor-grabbing",l&&"opacity-50",d&&"border-l-2 border-primary"),onClick:!1!==e.sortable?()=>r.handleSort(String(e.key)):void 0,...s,children:[t("div",{className:"flex items-center "+(e.className?.includes("text-center")?"justify-center":""),children:[e.header,!1!==e.sortable&&(c=String(e.key),r.sortField!==c?null:"asc"===r.sortDirection?a(re,{size:14,className:"ml-1"}):a(ne,{size:14,className:"ml-1"}))]}),i&&a(Hl,{direction:"horizontal",onMouseDown:a=>ue(String(e.key),a),isDragging:o})]},String(e.key));var c}),!G&&a(Ll,{className:"w-[50px] text-center",children:be||e.t("actions")})]})}),a(Tl,{children:0===r.entities.length?a(Ml,{children:a(zl,{colSpan:Ne,className:"h-32",children:a(ql,{title:e.t("no_items_found_empty"),description:"Não há dados para exibir no momento.",variant:"search"})})}):ye?_e(xe,Ne):r.entities.map(we)})]})})]})]})};function Sd(e,a,t,r){const[n,i]=o({}),[l,d]=o({}),c=s(()=>e,[e]),u=e=>e instanceof Date&&!isNaN(e.getTime()),p=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{}}},h=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return p(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};m(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},n=e(c),o={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);u(e)&&(t=e.toISOString().split("T")[0])}else u(t)&&(t=t.toISOString().split("T")[0])}else t=p(e);o[e.name]=t}),n.forEach(e=>{const a=h(e,o);void 0!==a&&(o[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(o[e]=a[e])}),i(o),d({}),t&&t(o)},[c,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},v=()=>{const e=g(c),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{i(r=>{const n={...r,[e]:a},i=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(c).filter(a=>a.dependsOn===e).forEach(e=>{const a=h(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(i),i}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(c).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&d(a=>({...a,[e]:t}))}},validateForm:v,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),v()&&e(n)}}}const Ad=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Ed=({value:e="#3b82f6",onChange:r,label:n,customColorLabel:i,presetColorsLabel:o})=>{const{t:s}=Ga(),l=i??s("custom_color"),d=o??s("preset_colors");return t("div",{className:"space-y-2",children:[n&&a(Hi,{children:n}),t(bs,{children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[a("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:e}}),e]})}),a(ys,{className:"w-64",children:t("div",{className:"space-y-3",children:[t("div",{children:[a(Hi,{htmlFor:"color-input",children:l}),a(qi,{id:"color-input",type:"color",value:e,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),t("div",{children:[a(Hi,{children:d}),a("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ad.map(e=>a("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:e},onClick:()=>r?.(e),"aria-label":`Selecionar cor ${e}`},e))})]})]})})]})]})},Dd=n.forwardRef(({className:e,children:r,...n},i)=>t(ut.Root,{ref:i,className:Fi("relative overflow-hidden",e),...n,children:[a(ut.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),a(Pd,{}),a(ut.Corner,{})]}));Dd.displayName=ut.Root.displayName;const Pd=n.forwardRef(({className:e,orientation:t="vertical",...r},n)=>a(ut.ScrollAreaScrollbar,{ref:n,orientation:t,className:Fi("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),...r,children:a(ut.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Pd.displayName=ut.ScrollAreaScrollbar.displayName;const Id=[{name:"alarm",filled:!1},{name:"account_box",filled:!0},{name:"announcement",filled:!0},{name:"assessment",filled:!0},{name:"assignment",filled:!0},{name:"bookmark",filled:!0},{name:"build",filled:!0},{name:"change_history",filled:!1},{name:"credit_card",filled:!1},{name:"date_range",filled:!0},{name:"extension",filled:!0},{name:"face",filled:!0},{name:"favorite",filled:!0},{name:"store",filled:!0},{name:"group_work",filled:!0},{name:"home",filled:!0},{name:"label",filled:!0},{name:"lightbulb_2",filled:!1},{name:"list",filled:!0},{name:"line_weight",filled:!0},{name:"question_answer",filled:!0},{name:"mode_heat",filled:!0},{name:"reorder",filled:!0},{name:"warning",filled:!0},{name:"room",filled:!0},{name:"settings",filled:!0},{name:"shopping_cart",filled:!0},{name:"work",filled:!0},{name:"star_rate",filled:!0},{name:"monetization_on",filled:!0},{name:"view_list",filled:!0},{name:"visibility",filled:!0},{name:"error",filled:!0},{name:"equalizer",filled:!0},{name:"release_alert",filled:!0},{name:"mic",filled:!0},{name:"videocam",filled:!0},{name:"call",filled:!0},{name:"chat",filled:!0},{name:"chat_bubble",filled:!0},{name:"email",filled:!0},{name:"link",filled:!0},{name:"report",filled:!0},{name:"flag",filled:!0},{name:"attach_file",filled:!0},{name:"attachment",filled:!0},{name:"attach_money",filled:!0},{name:"bubble_chart",filled:!0},{name:"folder",filled:!0},{name:"business",filled:!0},{name:"device_hub",filled:!0},{name:"flash_on",filled:!0},{name:"image",filled:!0},{name:"lens",filled:!0},{name:"photo_camera",filled:!0},{name:"style",filled:!0},{name:"view_compact",filled:!0},{name:"wb_incandescent",filled:!0},{name:"directions_bus",filled:!0},{name:"directions_car",filled:!0},{name:"flight",filled:!0},{name:"hotel",filled:!0},{name:"local_offer",filled:!0},{name:"restaurant",filled:!0},{name:"restaurant_menu",filled:!0},{name:"local_shipping",filled:!0},{name:"all_inclusive",filled:!0},{name:"business_center",filled:!0},{name:"notifications",filled:!0},{name:"share",filled:!0}];function Td({name:e,filled:t,className:r}){return a("span",{className:`material-symbols-outlined ${r??""}`,style:t?{fontVariationSettings:"'FILL' 1"}:void 0,children:e})}const Rd=({value:e=null,onChange:r,label:n,noIconLabel:i="SEM ÍCONE"})=>{const[s,l]=o(!1),d=e?(c=e,Id.find(e=>e.name===c)):null;var c;const u=e=>{r?.(e),l(!1)};return t("div",{className:"space-y-2",children:[n&&a(Hi,{children:n}),t(bs,{open:s,onOpenChange:l,children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",className:"justify-start text-left font-normal gap-2",children:[d?a(Td,{name:d.name,filled:d.filled,className:"text-xl text-muted-foreground"}):a("span",{className:"text-muted-foreground text-sm",children:i}),a(D,{className:"ml-auto h-4 w-4 opacity-50"})]})}),a(ys,{className:"w-72 p-3",align:"start",children:t("div",{className:"space-y-3",children:[a(Dd,{className:"h-64",children:a("div",{className:"grid grid-cols-7 gap-1",children:Id.map(t=>a("button",{type:"button",className:"flex items-center justify-center p-1.5 rounded hover:bg-accent transition-colors "+(e===t.name?"bg-primary/10 text-primary":"text-muted-foreground"),onClick:()=>u(t.name),title:t.name,children:a(Td,{name:t.name,filled:t.filled,className:"text-2xl"})},t.name))})}),a("button",{type:"button",className:"w-full py-2 text-sm font-semibold text-foreground hover:bg-accent rounded transition-colors border-t pt-3",onClick:()=>u(null),children:i})]})})]})]})},Md=n.forwardRef(({className:e,...t},r)=>a(mt.Root,{className:Fi("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:r,children:a(mt.Thumb,{className:Fi("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")})}));Md.displayName=mt.Root.displayName;const Ld=(e={})=>{const{user:a,alias:t}=kl(),{enabled:r=!0,status:n="active"}=e;return Ja({queryKey:["qualiex-users",t,n],queryFn:()=>ll.getUsers(t,n),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},zd=({value:t,onChange:r,multiple:n=!1,label:i,required:d,placeholder:c,icon:u,maxDisplayedBadges:p,className:h,disabled:f,enabled:g,displayFormat:v="name",customDisplayFn:b,filterFn:x,sortOptions:y=!0,popoverContainer:N,onOpen:w,onClose:_})=>{const{t:C}=Ga(),{data:k=[],isLoading:S,error:A}=Ld({enabled:g}),[E,D]=o(new Map),P=s(()=>t?Array.isArray(t)?t.filter(Boolean):[t].filter(Boolean):[],[t]),I=s(()=>{if(0===P.length||0===k.length)return"";const e=new Set(k.map(e=>e.userId||e.id||""));return P.filter(a=>a&&!e.has(a)&&!E.has(a)).sort().join(",")},[P,k,E]);m(()=>{if(!I)return;const e=I.split(",");let a=!1;const t=Ys.extractTokenData();return t?.alias&&t?.companyId?(ll.fetchUsers(t.alias,t.companyId,"all").then(t=>{a||D(a=>{const r=new Map(a);for(const n of e){const e=t.find(e=>e.userId===n||e.id===n);e&&r.set(n,{...e,isActive:e.isActive??!1})}return r})}).catch(()=>{}),()=>{a=!0}):void 0},[I]);const T=s(()=>x?k.filter(x):k,[k,x]),R=s(()=>{if(0===P.length)return T;const a=new Set(T.map(e=>e.userId||e.id||"")),t=P.filter(e=>e&&!a.has(e));if(0===t.length)return T;const r=t.map(a=>{const t=E.get(a);return t||{userId:a,id:a,userName:e.t("inactive_user"),userEmail:"",isActive:!1}});return[...T,...r]},[T,P,E]),M=l(a=>{let t;if("custom"===v&&b)t=b(a);else{const e=a.userName||"";switch(v){case"name-email":t=a.userEmail?`${e} (${a.userEmail})`:e;break;case"name-role":t=a.roleName?`${e} - ${a.roleName}`:e;break;default:t=e}}return!1===a.isActive?`${t} (${e.t("inactive")})`:t},[v,b]);return a(Rs,{multiple:n,value:t??(n?[]:""),onChange:r,options:R,isLoading:S,error:A,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:M,placeholder:c||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:C("no_results"),label:i,required:d,icon:u,maxDisplayedBadges:p,disabled:f,className:h,sortOptions:y,popoverContainer:N,onOpen:w,onClose:_})};function Fd({title:e,sections:r,initialData:n,onSubmit:d,onCancel:c,open:m,submitButtonText:p,isLoading:h=!1,usersData:f}){const[g,v]=o(r?.[0]?.id||""),b=u(null),[x,y]=o(null),N=l(e=>{b.current=e,y(e)},[]),w=s(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:_,errors:C,updateField:k,handleSubmit:S}=Sd(w,n,void 0,m),A=s(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(_):e.disabled||!1})):[],[r,_]),E=s(()=>{const e=A.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=A.find(e=>!e.disabled);return a?.id||g},[A,g]);i.useEffect(()=>{E!==g&&v(E)},[E,g]);const D=A.find(e=>e.id===E),P=e=>{const r=(e.computedValue,_[e.name]),n=void 0!==r?r:"",i=C[e.name];switch(e.type){case"group":const r="horizontal"===e.layout,o=r?`flex gap-3 w-full ${e.className||""}`:"space-y-3",s=r?Fi("space-y-2 w-full",e.wrapperClassName):Fi("space-y-2",e.className,e.wrapperClassName);return t("div",{className:s,children:[e.label,a("div",{className:o,children:e.fields?.map(e=>P(e))})]},e.name);case"user-select":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(zd,{value:n||"",onChange:a=>k(e.name,a),placeholder:e.placeholder,disabled:e.disabled,className:i?"border-destructive":""}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"textarea":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Wo,{id:e.name,value:n||"",onChange:a=>{k(e.name,a.target.value)},placeholder:e.placeholder,disabled:e.disabled,rows:e.rows,maxLength:e.maxLength,className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"select":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(Mo,{value:String(n),onValueChange:a=>{k(e.name,a),e.onValueChange&&e.onValueChange(a)},disabled:e.disabled,children:[a(Fo,{className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,children:a(zo,{placeholder:e.placeholder})}),a(Oo,{children:e.options?.map(e=>a($o,{value:e.value,children:e.label},e.value))})]}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"multiselect":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Rs,{options:e.options||[],value:Array.isArray(n)?n:[],onChange:a=>k(e.name,a),placeholder:e.placeholder,disabled:e.disabled,error:i,popoverContainer:x,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"date":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"date",value:String(n),onChange:a=>k(e.name,a.target.value),placeholder:e.placeholder,disabled:e.disabled,className:Fi("w-full",i?"border-destructive":"",e.disabled?"bg-muted cursor-not-allowed":"")}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"color":return t("div",{children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"color",value:n||e.defaultValue||"#000000",onChange:a=>k(e.name,a.target.value),className:"h-10"}),i&&a("p",{className:"text-sm text-destructive mt-1",children:i})]},e.name);case"color-picker":return t("div",{children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ed,{value:n||e.defaultValue||"#3b82f6",onChange:a=>k(e.name,a)}),i&&a("p",{className:"text-sm text-destructive mt-1",children:i})]},e.name);case"icon-picker":return t("div",{children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Rd,{value:n||e.defaultValue||null,onChange:a=>k(e.name,a)}),i&&a("p",{className:"text-sm text-destructive mt-1",children:i})]},e.name);case"custom":if(!e.component)return null;const l=e.component,d="function"==typeof e.componentProps?e.componentProps(_):e.componentProps||{};return t("div",{className:`space-y-2 ${e.className||""}`,children:[e.label&&t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(l,{value:n,onChange:a=>{k(e.name,a),e.onValueChange&&e.onValueChange(a)},disabled:e.disabled,error:i,popoverContainer:x,...d}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"number":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"number",value:null!=n?String(n):"",onChange:a=>{const t=a.target.value,r=""===t?null:Number(t);k(e.name,r)},placeholder:e.placeholder,disabled:e.disabled,className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,min:e.min,step:e.step||"1"}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"checkbox":return t("div",{className:`flex items-center space-x-2 ${e.className||""}`,children:[a(qo,{id:e.name,checked:!!n,onCheckedChange:a=>k(e.name,a),disabled:e.disabled}),t(Hi,{htmlFor:e.name,className:"cursor-pointer",children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"switch":return t("div",{className:`flex items-center justify-between space-x-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Md,{id:e.name,checked:!!n,onCheckedChange:a=>k(e.name,a),disabled:e.disabled}),i&&a("p",{className:"text-sm text-destructive mt-2",children:i})]},e.name);default:return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"text",value:n||"",onChange:a=>{k(e.name,a.target.value)},placeholder:e.placeholder,disabled:e.disabled,className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:e.disabled}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name)}},I=l(()=>{if(!D)return null;if(D.disabled)return t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[a("div",{className:"rounded-full bg-muted p-3 mb-4",children:a("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),a("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),a("p",{className:"text-muted-foreground max-w-sm",children:"Complete as informações obrigatórias na seção i18n.t('ap_general_info') para acessar esta seção."})]});if(D.component){const e=D.component;return a(e,{formData:_,updateField:k,errors:C,users:f,disabled:D.disabled})}return a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:D.fields.map(P)})},[D,_,k,C,f,P]),T=t("div",{className:"flex flex-col max-h-[80vh]",children:[A.length>1&&a("div",{className:"flex-shrink-0 p-4 border-b",children:a("div",{className:"flex space-x-2",children:A.map(e=>a($i,{variant:E===e.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&v(e)})(e.id),disabled:e.disabled,className:e.disabled?"opacity-50 cursor-not-allowed":"",children:e.title},e.id))})}),a("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:h?a("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-muted-foreground",children:"Carregando..."})}):t("form",{onSubmit:S(d),className:"space-y-3 md:space-y-4",children:[I(),t("div",{className:"flex justify-end space-x-2 pt-4",children:[a($i,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),a($i,{type:"submit",disabled:h,children:p||"Salvar"})]})]})})]});return a(mo,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:t(bo,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[t(xo,{showSeparator:!0,children:[a(wo,{children:e}),a(_o,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),T]})})}function Ud({currentPage:e,totalPages:n,totalItems:i,itemsPerPage:o,onPageChange:s,onItemsPerPageChange:l,variant:d="full"}){const{t:c}=Ga();if(0===i)return null;const u=(e-1)*o+1,m=Math.min(e*o,i);return t("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[a("div",{className:"flex items-center gap-2",children:"full"===d&&t(r,{children:[a("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:c("rows_per_page","Linhas por página")}),t(Mo,{value:String(o),onValueChange:e=>l(Number(e)),children:[a(Fo,{className:"h-8 w-[70px]",children:a(zo,{})}),t(Oo,{children:[a($o,{value:"10",children:"10"}),a($o,{value:"25",children:"25"}),a($o,{value:"50",children:"50"}),a($o,{value:"100",children:"100"})]})]})]})}),t("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",c("of","de")," ",i," ",c("items","itens")]}),t("div",{className:"flex items-center gap-1",children:[a($i,{variant:"outline",size:"sm",onClick:()=>s(1),disabled:1===e,className:"h-8 w-8 p-0",children:a(ie,{size:16})}),a($i,{variant:"outline",size:"sm",onClick:()=>s(e-1),disabled:1===e,className:"h-8 w-8 p-0",children:a(oe,{size:16})}),t("div",{className:"flex items-center gap-1 px-2",children:[a("span",{className:"text-sm font-medium",children:e}),a("span",{className:"text-sm text-muted-foreground",children:c("of","de")}),a("span",{className:"text-sm font-medium",children:n})]}),a($i,{variant:"outline",size:"sm",onClick:()=>s(e+1),disabled:e===n,className:"h-8 w-8 p-0",children:a(U,{size:16})}),a($i,{variant:"outline",size:"sm",onClick:()=>s(n),disabled:e===n,className:"h-8 w-8 p-0",children:a(se,{size:16})})]})]})}function jd({manager:e}){return a(Ud,{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 Od={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Bd={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},$d={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Vd({children:e,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:o=!1,className:s}){return a("div",{className:Fi("flex","column"===t?"flex-col":"flex-row",Od[r],Bd[n],$d[i],o&&"flex-wrap",s),children:e})}function qd({manager:e,filters:n,inline:i=!1}){const{t:o}=Ga(),{isSearchVisible:s}=kl(),l=e.searchTerm,d=t(r,{children:[n.some(e=>"search"===e.type)&&!s&&t("div",{className:"relative flex-1",children:[a(B,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(qi,{placeholder:"Pesquisar",value:e.searchTerm,onChange:a=>e.handleSearch(a.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((e,r)=>t(Mo,{value:e.value||"",onValueChange:a=>e.onChange?.(a),children:[a(Fo,{className:"w-[180px]",children:a(zo,{placeholder:e.placeholder})}),a(Oo,{children:e.options.map(e=>a($o,{value:e.value,children:e.label},e.value))})]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((e,t)=>{const r=e.component;return a("div",{className:i?"":"w-full sm:w-auto",children:a(r,{...e.props})},`custom-${t}`)}),l&&t($i,{variant:"outline",onClick:e.clearFilters,className:"whitespace-nowrap",children:[a(E,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?a("div",{className:"flex items-center gap-2",children:d}):a(Vd,{direction:"column",gap:"md",className:"mb-6",children:a(Vd,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:d})})}function Wd({manager:e,config:r,formSections:n,onSave:i,onToggleStatus:s,defaultSort:l}){e&&e.queryKey;const{setSearchVisible:d}=kl(),[c,u]=tt(),[p,h]=o(!1),[f,g]=o(null),[v,b]=o({isOpen:!1,entityId:null,entityName:""}),[x,y]=o({isOpen:!1,count:0});m(()=>(d(!0),()=>{d(!1)}),[d]),m(()=>{if(l&&e){const a=`${e.queryKey}_sortField`,t=`${e.queryKey}_sortDirection`;if(!c.has(a)&&!c.has(t)){const e=Object.fromEntries(c);e[a]=l.column,e[t]=l.direction,u(e)}}},[]);const N=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),h(!0))}:void 0,w="function"==typeof e?.deleteEntity?e=>{b({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,_=()=>{b({isOpen:!1,entityId:null,entityName:""})},C=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,k=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return t("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&a(bd,{onNew:()=>{r.onNew?r.onNew():(g(null),h(!0))},newButtonLabel:r.newButtonLabel,showNewButton:C,showSearch:r.showSearch,searchValue:e.searchTerm,onSearchChange:e.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:e.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{y({isOpen:!0,count:e.selectedIds.length})},onClearSelection:e.clearSelection,customActions:k,filters:r.filters&&r.filters.length>0?a(qd,{manager:e,filters:r.filters,inline:!0}):void 0}),a("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?a("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(e.entities,e)}):a(kd,{manager:e,columns:r.columns,onEdit:N,onDelete:w,onToggleStatus:s,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`,defaultHiddenColumns:r.defaultHiddenColumns})}),a("div",{className:"flex-shrink-0 border-t bg-background",children:a(jd,{manager:e})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&a(Fd,{open:p,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{i(e),h(!1),g(null)},onCancel:()=>{h(!1),g(null)},isLoading:e.isLoading,submitButtonText:f?"Atualizar":"Criar"}),a(mo,{open:v.isOpen,onOpenChange:_,children:t(bo,{size:"sm",variant:"destructive",children:[a(xo,{showSeparator:!0,children:a(wo,{children:"Você tem certeza absoluta?"})}),a("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:t("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",a("strong",{children:v.entityName}),". Esta ação não pode ser desfeita."]})}),t(No,{children:[a($i,{variant:"outline",onClick:_,children:"Cancelar"}),a($i,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof e?.deleteEntity&&(e.deleteEntity(v.entityId),b({isOpen:!1,entityId:null,entityName:""}))},disabled:e.isDeleting,children:e.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),a(mo,{open:x.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),children:t(bo,{size:"sm",variant:"destructive",children:[a(xo,{showSeparator:!0,children:a(wo,{children:"Você tem certeza absoluta?"})}),a("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:t("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",a("strong",{children:x.count})," ",1===x.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),t(No,{children:[a($i,{variant:"outline",onClick:()=>y({isOpen:!1,count:0}),children:"Cancelar"}),a($i,{variant:"destructive",onClick:()=>{e.bulkDelete?.(e.selectedIds),y({isOpen:!1,count:0})},disabled:e.isBulkDeleting,children:e.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Hd(e){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:o,onToggleStatus:s}=e,l=t??r,d={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:o||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return a(Wd,{manager:l,config:d,formSections:n.formSections,onSave:i,onToggleStatus:s,defaultSort:n.defaultSort})}}function Gd(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function Kd(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],n={key:e,header:Qd(e),label:Qd(e),...Yd(e,t),sortable:!0,searchable:"string"==typeof t};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Yd(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 Qd(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Xd=({children:n})=>{const{isAuthenticated:o,isLoading:s}=kl();if(i.useEffect(()=>{if(s)return;if(o)return;if(Ys.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 r=vr(),n=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",n);(async()=>{r?await yl.loginDev():yl.loginProd()})()},[o,s]),s&&!o)return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Carregando..."})}),t(Xi,{className:"text-center",children:[a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),a("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!o){const r=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return a("div",r?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Processando..."})}),t(Xi,{className:"text-center",children:[a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),a("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Iniciando..."})}),t(Xi,{className:"text-center",children:[a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),a("p",{className:"text-muted-foreground",children:vr()?e.t("auto_login"):e.t("redirecting_auth")})]})]})})}return a(r,{children:n})};function Jd(e={}){const{paramName:a="alias"}=e,t=rt(),{alias:r,companies:n}=kl(),i=t[a]||null;return s(()=>{if(!i)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===i)||null,a=!!e;return{urlAlias:i,isAliasMismatch:a&&i!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[i,r,n])}function Zd({children:e,paramName:n="alias"}){const i=nt(),s=it(),d=rt(),{alias:c,isAuthenticated:p,isLoading:h,switchUnit:f}=kl(),{urlAlias:g,isAliasMismatch:v,isValidAlias:b,isMissing:x,matchedCompany:y}=Jd({paramName:n}),[N,w]=o(!1),_=u(!1),C=n in d,k=l(e=>{const a=d[n],{pathname:t,search:r,hash:i}=s;if(a){const n=t.split("/"),o=n.findIndex(e=>e===a);if(o>=0)return n[o]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[d,n,s]);return m(()=>{if(C&&!h&&p&&c&&!_.current)if(x)i(k(c),{replace:!0});else if(!g||b){if(v&&y&&!_.current){(async()=>{_.current=!0,w(!0);try{await f(y)}catch(e){c&&i(k(c),{replace:!0})}finally{_.current=!1,w(!1)}})()}}else i(k(c),{replace:!0})},[C,h,p,c,x,g,b,v,y,f,k,i]),h||!p?a(r,{children:e}):N?a("div",{className:"flex items-center justify-center min-h-screen",children:t("div",{className:"flex flex-col items-center gap-3",children:[a(Yo,{size:"lg"}),a("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):a(r,{children:e})}function ec(){const{alias:e}=kl(),{pathname:t,search:r,hash:n}=it();return e?a(ot,{to:`/${e}${t}${r}${n}`,replace:!0}):null}const ac=v("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),tc={info:ce,warning:ce,danger:de,success:le},rc=n.forwardRef(({className:e,variant:r="info",showIcon:n=!0,children:i,...o},s)=>{const l=tc[r||"info"];return t("div",{ref:s,role:"alert",className:Fi(ac({variant:r}),e),...o,children:[n&&a(l,{className:"h-4 w-4"}),i]})});rc.displayName="Alert";const nc=n.forwardRef(({className:e,...t},r)=>a("h5",{ref:r,className:Fi("mb-1 font-medium leading-none tracking-tight",e),...t}));nc.displayName="AlertTitle";const ic=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("text-sm [&_p]:leading-relaxed",e),...t}));ic.displayName="AlertDescription";const oc=()=>{const{processCallback:e}=kl(),n=nt(),[i,s]=o(null),[l,d]=o(!1);m(()=>{(async()=>{try{if(await e()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else s("Falha na autenticação. Tente novamente.")}catch(a){localStorage.removeItem("auth_return_url"),s(a?.message||"Erro durante a autenticação. Tente novamente.")}})()},[e,n]);const c=async()=>{d(!0),s(null);try{await e()||s("Falha na autenticação. Tente novamente.")}catch(a){s(a?.message||"Erro ao tentar novamente.")}finally{d(!1)}},u=()=>{window.location.href="/"};return a("div",i?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:t(Yi,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[a(O,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),t(Xi,{className:"space-y-4",children:[a(rc,{variant:"danger",children:a(ic,{children:i})}),a("div",{className:"text-sm text-muted-foreground",children:a("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),t("div",{className:"flex gap-2",children:[a($i,{onClick:c,disabled:l,className:"flex-1",children:t(r,l?{children:[a(Yo,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[a(ue,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),a($i,{onClick:u,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),t(Xi,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(Yo,{size:"lg"})}),a("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},sc=()=>{const{t:e}=Ga();return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),t(Xi,{className:"text-center space-y-4",children:[a("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),a($i,{onClick:async()=>{vr()?await yl.loginDev():yl.loginProd()},className:"w-full",size:"lg",children:vr()?e("dev_login"):e("login_with_qualiex")})]})]})})},lc=d(void 0);function dc({children:e,actions:t}){const{t:r}=Ga(),[n,i]=o({}),[d,c]=o(t);m(()=>{c(t)},[t]);const u=l(()=>i({}),[]),p=s(()=>({metadata:n,setMetadata:i,clearMetadata:u,headerActions:d,setHeaderActions:c}),[n,u,d]);return a(lc.Provider,{value:p,children:e})}function cc(){const e=c(lc);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function uc(e){const{setMetadata:a,clearMetadata:t}=cc(),r=u({});m(()=>{const n=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||n)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>t()},[e.title,e.subtitle,e.breadcrumbs,a,t])}function mc(e){return{queryClient:e.queryClient||new et({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var pc={actions:"Ações",activate:"Ativar",add_first_item:"Adicione seu primeiro item para começar",add_item:"Adicionar Item",advanced_filter:"Filtro avançado",all:"Todos",allow:"Permitir",allowed_items:"Itens permitidos",also_discover:"Conheça também",alt_text:"Texto Alternativo",anonymous:"Anônimo",ap_action_plan:"Plano de Ação",ap_action_type:"Tipo de Ação",ap_add:"Adicionar",ap_add_comment_placeholder:"Adicionar comentário...",ap_add_cost:"Adicionar custo",ap_add_predecessor:"Adicionar predecessor",ap_attachments:"Anexos",ap_belongs_to:"Pertence a",ap_cause:"Causa",ap_change_status:"Alterar Status",ap_checker:"Verificador",ap_clear:"Limpar",ap_comments:"Comentários",ap_cost_description:"Descrição do custo",ap_costs:"Custos",ap_delete:"Excluir",ap_description:"Descrição",ap_description_placeholder:"Descreva o plano de ação",ap_duration_days:"Duração (dias)",ap_edit_progress:"Editar Progresso",ap_end_date:"Data de Término",ap_estimated_cost:"Custo Estimado",ap_file_duplicate:"Arquivo duplicado",ap_file_upload_error:"Erro ao enviar arquivo",ap_general:"Geral",ap_general_info:"Informações Gerais",ap_history:"Histórico",ap_justification:"Justificativa",ap_justification_placeholder:"Justificativa do plano de ação",ap_name:"Nome",ap_new_action:"Nova Ação",ap_no_attachments:"Nenhum anexo",ap_no_comments:"Nenhum comentário",ap_no_costs:"Nenhum custo registrado",ap_no_history:"Nenhum registro no histórico",ap_no_predecessors:"Nenhum predecessor adicionado",ap_no_progress:"Sem dados de progresso disponíveis",ap_overall_progress:"Progresso geral",ap_place:"Local",ap_plan_name_placeholder:"Nome do plano de ação",ap_predecessors:"Predecessores",ap_priority:"Prioridade",ap_priority_high:"Alta",ap_priority_low:"Baixa",ap_priority_medium:"Média",ap_progress:"Progresso",ap_progress_comment_placeholder:"Adicione um comentário sobre o progresso",ap_progress_percent:"Progresso (%)",ap_report:"Reportar",ap_report_progress:"Reportar progresso",ap_reporting:"Reportando...",ap_reports_history:"Histórico de reportes",ap_responsible:"Responsável",ap_select_action:"Selecione uma ação",ap_select_cause:"Selecione a causa",ap_select_checker:"Selecione o verificador",ap_select_date:"Selecione a data",ap_select_parent:"Selecione a ação pai",ap_select_place:"Selecione o local",ap_select_priority:"Selecione a prioridade",ap_select_responsible:"Selecione o responsável",ap_select_type:"Selecione o tipo",ap_start_date:"Data de Início",ap_status_canceled:"Cancelada",ap_status_done:"Concluída",ap_status_effectiveness_check:"Verificação de eficácia",ap_status_running:"Em andamento",ap_status_suspended:"Suspensa",ap_status_waiting_start:"Aguardando início",ap_time_label:"Tempo",ap_time_spent:"Tempo gasto (HH:MM)",ap_total_cost:"Custo total realizado",ap_total_time:"Tempo total",ap_type_corrective:"Corretiva",ap_type_immediate:"Imediata",ap_type_improvement:"Oportunidade de Melhoria",ap_type_preventive:"Preventiva",ap_type_standardization:"Padronização",ap_value:"Valor (R$)",ap_via_app:"Via app",approval_approve:"Aprovar",approval_execute_action:"Executar ação",approval_opinion:"Parecer *",approval_read_less:"Ler menos",approval_read_more:"Ler mais",approval_reprove_radio:"Reprovar e retornar para etapa",approval_search_approver:"Buscar aprovador...",approval_select_approver:"Selecionar aprovador",approval_select_approver_placeholder:"Selecione um aprovador...",approval_select_step:"Selecione a etapa",approval_step_label:"Etapa",approval_user_group:"Grupo de usuários",audit_description:"Descrição",audit_esign:"Assinatura eletrônica",audit_not_informed:"Não informado",audit_references:"Referências",audit_security:"Segurança",audit_trail:"Trilha de Auditoria",auth_error:"Erro durante a autenticação. Tente novamente.",auth_failed:"Falha na autenticação. Tente novamente.",auto_login:"Fazendo login automático...",back:"Voltar",bulk_delete_error:"Erro ao excluir itens em lote",bulk_delete_success:"Itens excluídos com sucesso",cancel:"Cancelar",change_photo:"Trocar foto",cannot_be_own_leader:"Um líder não pode ser seu próprio superior",clear_filters:"Limpar filtros",clear_formatting:"Limpar Formatação",clear_search:"Limpar busca",clear_selection:"Limpar seleção",close:"Fechar",collapse_row:"Recolher linha",columns:"Colunas",conclude:"Concluir",confirm_removal:"Confirmar remoção",could_not_load_info:"Não foi possível carregar as informações",current:"Atual",custom_color:"Cor personalizada",dashboard_advanced_filter:"Filtro avançado",dashboard_all_access:"Todos os colaboradores terão acesso",dashboard_average:"Média",dashboard_code:"Código",dashboard_distinct_count:"Contagem distinta",dashboard_edit:"Editar Dashboard",dashboard_exit_fullscreen:"Sair do fullscreen",dashboard_export_chart:"Exportar gráfico",dashboard_export_table:"Exportar tabela",dashboard_max_value:"Valor máximo",dashboard_min_value:"Valor mínimo",dashboard_my:"Meus dashboards",dashboard_new:"Novo Dashboard",dashboard_no_data:"A consulta não retornou itens para o seu perfil.",dashboard_no_refresh:"Não atualizar",dashboard_normal_page:"Página normal",dashboard_not_shared:"Não compartilhado",dashboard_only_mine:"Somente meus",dashboard_only_overdue:"Somente atrasados",dashboard_only_responsible:"Somente o responsável terá acesso",dashboard_open_query:"Open query",dashboard_remove_favorite:"Remover favorito",dashboard_responsible:"Responsável",dashboard_select_groups:"Selecione grupos, locais e colaboradores específicos",dashboard_shared_unit:"Compartilhado com todos os colaboradores da unidade",dashboard_status:"Situação",dashboard_title:"Título",dashboard_wait_refresh:"Aguarde para atualizar novamente",dashboard_work_done:"Trabalho executado",dashboard_work_planned:"Trabalho planejado",deactivate:"Inativar",deselect_all:"Deselecionar todas",dev_login:"Login Desenvolvimento",download:"Download",edit:"Editar",edit_profile:"Editar Perfil",edit_name:"Editar Nome",electronic_signature:"Assinatura Eletrônica",embed_code:"Código embed",embedded_content:"Embedded content",enter_code:"Digite o código",enter_password:"Digite sua senha",error_authentication:"Erro de Autenticação",error_connection:"Erro de Conexão",error_copied_clipboard:"Os detalhes do erro foram copiados para a área de transferência.",error_loading:"Erro ao carregar",error_loading_data:"Erro ao carregar dados",error_session_expired:"Sessão Expirada",error_token_expired:"Token de autenticação expirado. Faça login novamente.",esign_code_description:"Um código de verificação foi enviado para o seu e-mail. Insira o código abaixo para confirmar a operação.",esign_code_error:"Erro ao validar o código. Tente novamente.",esign_invalid_code:"Código inválido. Tente novamente.",esign_invalid_password:"Senha incorreta. Tente novamente.",esign_password_description:"Digite sua senha para confirmar a operação.",esign_password_error:"Erro ao validar a senha. Tente novamente.",esign_resend_error:"Erro ao reenviar o código.",expand_row:"Expandir linha",expiration_date:"Data de expiração",file_error:"Erro no arquivo",file_upload:"Upload de arquivo",go_to_next_page:"Ir para próxima página",go_to_previous_page:"Ir para página anterior",group_by_column:"Agrupar por esta coluna",heading_1:"Título 1",heading_2:"Título 2",heading_3:"Título 3",image_description:"Descrição da imagem",import_flows:"Fluxos de Importação",import_manage:"Gerencie seus fluxos de importação",inactive:"inativo",inactive_user:"[Usuário inativo]",input_type:"Tipo de entrada",invalid_form:"Formulário inválido. Preencha todos os campos obrigatórios.",italic:"Itálico",item_details:"Detalhes do item",items:"itens",items_per_page:"Itens por página",know_saber_gestao:"Conheça o Saber Gestão",know_staff:"Conheça Staff",language:"Idioma",last_update:"Última atualização",leader:"Líder",leader_create_error:"Erro ao criar líder",leader_not_found:"Líder não encontrado",leader_promoted_success:"Líder promovido com sucesso",leader_remove_error:"Erro ao remover líder",leader_removed_success:"Líder removido com sucesso",leader_update_error:"Erro ao atualizar líder",leader_updated_success:"Líder atualizado com sucesso",leadership_add_root:"Adicionar Líder Raiz",leadership_add_subordinate:"Adicionar Liderado",leadership_cycle_error:"Esta associação criaria um ciclo na hierarquia",leadership_define_leader:"Definir Líder",leadership_immediate_superior:"Superior Imediato",leadership_make_root:"Tornar Líder Raiz",leadership_make_root_short:"Tornar Raiz",leadership_no_hierarchy:"Nenhuma hierarquia de liderança encontrada.",leadership_no_members:"Nenhum membro na equipe",leadership_no_user_selected:"Nenhum usuário selecionado",leadership_no_users_available:"Nenhum usuário disponível",leadership_no_users_found:"Nenhum usuário encontrado",leadership_remove_team:"Remover da equipe",leadership_select_subordinates:"Selecione pelo menos um liderado",learn_qualiex:"Aprenda a usar o Qualiex",leave_without_saving:"Sair sem salvar",lines_per_page:"Linhas por página",link:"Link",login_with_qualiex:"Entrar com Qualiex",manage_access:"Gerenciar Acessos",mind_map_add_child:"Adicionar filho",mind_map_add_sibling:"Adicionar irmão",mind_map_aria_label:"Mapa mental",mind_map_collapse_all:"Colapsar tudo",mind_map_delete_node:"Excluir nó",mind_map_expand_all:"Expandir tudo",mind_map_export_image:"Exportar como imagem",mind_map_export_json:"Exportar como JSON",mind_map_fit_to_screen:"Ajustar à tela",mind_map_redo:"Refazer",mind_map_undo:"Desfazer",mind_map_zoom_in:"Aproximar",mind_map_zoom_out:"Afastar",modules:"Módulos",more_options:"Mais opções",msg_create_error:"Erro ao criar registro",msg_created_success:"Registro criado com sucesso",msg_delete_error:"Erro ao excluir registro",msg_deleted_success:"Registro excluído com sucesso",msg_load_error:"Erro ao carregar dados",msg_update_error:"Erro ao atualizar registro",msg_updated_success:"Registro atualizado com sucesso",new_document:"Novo Documento",new_folder:"Nova Pasta",new_item:"Novo Item",next:"Próximo",no_access_page:"Parece que você não tem acesso a essa página",no_data_to_display:"Não há dados para exibir no momento.",no_errors_recorded:"Nenhum erro registrado",no_image_selected:"Nenhuma imagem selecionada",no_item_selected:"Nenhum item selecionado",no_items_found:"Nenhum item encontrado",no_items_found_empty:"Nenhum item encontrado",no_place_found:"Nenhum local encontrado",no_place_selected:"Sem local",no_products:"Sem produtos",no_reports_found:"Nenhum relatório encontrado",no_results:"Nenhum resultado encontrado",no_search_results:"Nenhum resultado para a busca",no_video_selected:"Nenhum vídeo selecionado",not_authenticated:"Não autenticado",not_available:"Não disponível",of:"de",open_popover:"Abrir Popover",open_wiki:"Abrir Wiki",ordered_list:"Lista Ordenada",page:"Página",paste_embed_code:"Cole o código embed aqui",permissions:"Permissões",preset_colors:"Cores predefinidas",preview:"Visualizar",redirecting_auth:"Redirecionando para autenticação...",refresh_data:"Atualizar dados",remove:"Remover",remove_grouping:"Remover agrupamento",replace:"Substituir",report:"Relatório",request_date:"Data da solicitação",required_field:"Campo obrigatório",resend_code:"Reenviar código",restricted_access:"Acesso restrito",rows_per_page:"Registros por página",save:"Salvar",save_as_draft:"Salvar como Rascunho",save_as_template:"Salvar como Modelo",saving:"Salvando...",search:"Pesquisar",search_placeholder:"Pesquisar...",search_report_placeholder:"Buscar relatório...",search_user_placeholder:"Buscar usuário...",select_all:"Selecionar todos",select_all_columns:"Selecionar todas",select_all_items:"Selecionar todos",select_at_least_one:"Selecione pelo menos um item",select_at_least_one_item:"Selecione ao menos um item",select_date:"Selecione uma data",select_file_format:"Selecione o formato do arquivo",select_items_to_add:"Selecione itens para adicionar...",select_placeholder:"Selecione...",selected:"Selecionados",session_expired:"Sua sessão expirou. Você será redirecionado para fazer login novamente.",sign_access_error:"Erro ao acessar serviço de assinatura",sign_api_key_info:"Informe a API Key do provedor de assinatura",sign_api_key_input:"Insira a API Key do provedor de assinatura",sign_api_key_placeholder:"Insira a chave de API",sign_api_key_required:"Chave de API obrigatória",sign_attempt:"Tentativa de assinatura",sign_auth_required:"Autenticação necessária para assinar",sign_click_to_select:"Clique para selecionar documento",sign_config_save_err:"Erro ao salvar configuração de assinatura",sign_config_save_error:"Erro ao salvar configuração de assinatura",sign_config_saved:"Configuração de assinatura salva",sign_config_saved_success:"Configuração de assinatura salva com sucesso",sign_configured:"Assinatura configurada",sign_configured_unit:"Assinatura digital configurada para esta unidade",sign_digital_config:"Configuração de Assinatura Digital",sign_doc_available:"Documento assinado disponível para download",sign_doc_load_error:"Erro ao carregar documento",sign_doc_process_error:"Erro ao processar documento",sign_doc_sent:"Documento enviado para assinatura",sign_download_signed:"Baixar documento assinado",sign_email_fallback:"E-mail de fallback para assinatura",sign_environment:"Ambiente de assinatura",sign_fetch_failed:"Falha ao buscar documento assinado",sign_file_not_allowed:"Extensão de arquivo não permitida",sign_file_type_not_allowed:"Tipo de arquivo não permitido",sign_incorrect_data:"O signatário reportou dados incorretos.",sign_login_required:"Login necessário para assinar",sign_login_to_sign:"Faça login para utilizar a assinatura digital.",sign_monthly_limit:"Limite mensal de assinaturas atingido",sign_no_access:"Não foi possível obter o acesso para assinatura. Tente novamente.",sign_not_configured:"Assinatura não configurada",sign_not_configured_unit:"Assinatura digital ainda não configurada para esta unidade",sign_preparing_doc:"Preparando documento para assinatura",sign_process_error:"Erro ao processar assinatura",sign_save_config:"Salvar configuração",sign_save_config_btn:"Salvar Configuração",sign_select_pdf:"Selecione um arquivo PDF",sign_sending_doc:"Enviando documento para assinatura",sign_signed_success:"Documento assinado com sucesso",sign_signer_unavailable:"Signer ID não disponível",sign_try_again:"Tentar novamente",sign_update_config:"Atualizar configuração",sign_update_config_btn:"Atualizar Configuração",sign_waiting_provider:"Aguardando provedor de assinatura",sign_widget_error:"Erro no widget de assinatura",something_went_wrong:"Algo deu errado",state:"Estado",status:"Status",status_completed:"Concluído",status_error:"Erro",status_expired:"Expirado",status_processing:"Processando",status_waiting:"Aguardando",steps:"Etapas",subordinates_add_error:"Erro ao adicionar subordinados",subordinates_added_success:"Subordinados adicionados com sucesso",subordinates_sync_error:"Erro ao sincronizar subordinados",subordinates_synced_success:"Subordinados sincronizados com sucesso",team_all_groups:"Todos os grupos",terms_confirm_reading:"Confirmar leitura",terms_confirmation_available:"Confirmação disponível em",terms_of_use:"Termos de Uso",terms_read_agree:"Li e concordo",terms_see_later:"Ver depois",terms_updated:"Termos de Uso Atualizados",terms_view:"Visualizar termo de uso",terms_view_short:"View term",try_adjust_search:"Tente ajustar sua busca",try_again:"Tentar Novamente",unit_not_selected:"Nenhuma unidade selecionada",unknown_error:"Erro desconhecido",unsaved_changes:"Alterações não salvas",unsaved_changes_description:"Existem alterações não salvas. Deseja sair sem salvar?",updates:"Atualizações",user:"Usuário",user_info:"Informações do Usuário",user_photo:"Foto do usuário",users_already_leaders:"Usuários já são líderes",verification_code:"Código de verificação",video:"Vídeo",video_title:"Título do vídeo",view_report:"Visualizar relatório",want_to_know_more:"Quero conhecer mais",write_content_here:"Escreva o conteúdo aqui..."},hc={actions:"Actions",activate:"Activate",add_first_item:"Add your first item to get started",add_item:"Add Item",advanced_filter:"Advanced filter",all:"All",allow:"Allow",allowed_items:"Allowed items",also_discover:"Also discover",alt_text:"Alternative Text",anonymous:"Anonymous",ap_action_plan:"Action Plan",ap_action_type:"Action type",ap_add:"Add",ap_add_comment_placeholder:"Add a comment...",ap_add_cost:"Add cost",ap_add_predecessor:"Add predecessor",ap_attachments:"Attachments",ap_belongs_to:"Belongs to",ap_cause:"Cause",ap_change_status:"Change Status",ap_checker:"Checker",ap_clear:"Clear",ap_comments:"Comments",ap_cost_description:"Cost description",ap_costs:"Costs",ap_delete:"Delete",ap_description:"Description",ap_description_placeholder:"Describe the action plan",ap_duration_days:"Duration (days)",ap_edit_progress:"Edit Progress",ap_end_date:"End date",ap_estimated_cost:"Estimated cost",ap_file_duplicate:"Duplicate file",ap_file_upload_error:"Error uploading file",ap_general:"General",ap_general_info:"General Information",ap_history:"History",ap_justification:"Justification",ap_justification_placeholder:"Action plan justification",ap_name:"Name",ap_new_action:"New Action",ap_no_attachments:"No attachments",ap_no_comments:"No comments",ap_no_costs:"No costs recorded",ap_no_history:"No history records",ap_no_predecessors:"No predecessors added",ap_no_progress:"No progress data available",ap_overall_progress:"Overall progress",ap_place:"Place",ap_plan_name_placeholder:"Action plan name",ap_predecessors:"Predecessors",ap_priority:"Priority",ap_priority_high:"High",ap_priority_low:"Low",ap_priority_medium:"Medium",ap_progress:"Progress",ap_progress_comment_placeholder:"Add a comment about the progress",ap_progress_percent:"Progress (%)",ap_report:"Report",ap_report_progress:"Report progress",ap_reporting:"Reporting...",ap_reports_history:"Reports history",ap_responsible:"Responsible",ap_select_action:"Select an action",ap_select_cause:"Select cause",ap_select_checker:"Select checker",ap_select_date:"Select date",ap_select_parent:"Select parent action",ap_select_place:"Select place",ap_select_priority:"Select priority",ap_select_responsible:"Select responsible",ap_select_type:"Select type",ap_start_date:"Start date",ap_status_canceled:"Canceled",ap_status_done:"Completed",ap_status_effectiveness_check:"Effectiveness check",ap_status_running:"In progress",ap_status_suspended:"Suspended",ap_status_waiting_start:"Waiting to start",ap_time_label:"Time",ap_time_spent:"Time spent (HH:MM)",ap_total_cost:"Total realized cost",ap_total_time:"Total time",ap_type_corrective:"Corrective",ap_type_immediate:"Immediate",ap_type_improvement:"Improvement Opportunity",ap_type_preventive:"Preventive",ap_type_standardization:"Standardization",ap_value:"Value",ap_via_app:"Via app",approval_approve:"Approve",approval_execute_action:"Execute action",approval_opinion:"Opinion *",approval_read_less:"Read less",approval_read_more:"Read more",approval_reprove_radio:"Reject and return to step",approval_search_approver:"Search approver...",approval_select_approver:"Select approver",approval_select_approver_placeholder:"Select an approver...",approval_select_step:"Select the step",approval_step_label:"Step",approval_user_group:"User group",audit_description:"Description",audit_esign:"Electronic signature",audit_not_informed:"Not informed",audit_references:"References",audit_security:"Security",audit_trail:"Audit Trail",auth_error:"Error during authentication. Try again.",auth_failed:"Authentication failed. Try again.",auto_login:"Logging in automatically...",back:"Back",bulk_delete_error:"Error deleting items in bulk",bulk_delete_success:"Items deleted successfully",cancel:"Cancel",change_photo:"Change photo",cannot_be_own_leader:"A leader cannot be their own superior",clear_filters:"Clear filters",clear_formatting:"Clear Formatting",clear_search:"Clear search",clear_selection:"Clear selection",close:"Close",collapse_row:"Collapse row",columns:"Columns",conclude:"Finish",confirm_removal:"Confirm removal",could_not_load_info:"Could not load the information",current:"Current",custom_color:"Custom color",dashboard_advanced_filter:"Advanced filter",dashboard_all_access:"All collaborators will have access",dashboard_average:"Average",dashboard_code:"Code",dashboard_distinct_count:"Distinct count",dashboard_edit:"Edit Dashboard",dashboard_exit_fullscreen:"Exit fullscreen",dashboard_export_chart:"Export chart",dashboard_export_table:"Export table",dashboard_max_value:"Maximum value",dashboard_min_value:"Minimum value",dashboard_my:"My dashboards",dashboard_new:"New Dashboard",dashboard_no_data:"The query returned no items for your profile.",dashboard_no_refresh:"Do not refresh",dashboard_normal_page:"Normal page",dashboard_not_shared:"Not shared",dashboard_only_mine:"Only mine",dashboard_only_overdue:"Only overdue",dashboard_only_responsible:"Only the responsible will have access",dashboard_open_query:"Open query",dashboard_remove_favorite:"Remove favorite",dashboard_responsible:"Responsible",dashboard_select_groups:"Select groups, places and specific collaborators",dashboard_shared_unit:"Shared with all unit collaborators",dashboard_status:"Status",dashboard_title:"Title",dashboard_wait_refresh:"Wait to refresh again",dashboard_work_done:"Work done",dashboard_work_planned:"Work planned",deactivate:"Deactivate",deselect_all:"Deselect all",dev_login:"Development Login",download:"Download",edit:"Edit",edit_profile:"Edit Profile",edit_name:"Edit Name",electronic_signature:"Electronic Signature",embed_code:"Embed code",embedded_content:"Embedded content",enter_code:"Enter the code",enter_password:"Enter your password",error_authentication:"Authentication Error",error_connection:"Connection Error",error_copied_clipboard:"Error details were copied to the clipboard.",error_loading:"Error loading",error_loading_data:"Error loading data",error_session_expired:"Session Expired",error_token_expired:"Authentication token expired. Please log in again.",esign_code_description:"A verification code was sent to your email. Enter the code below to confirm the operation.",esign_code_error:"Error validating code. Try again.",esign_invalid_code:"Invalid code. Try again.",esign_invalid_password:"Incorrect password. Try again.",esign_password_description:"Enter your password to confirm the operation.",esign_password_error:"Error validating password. Try again.",esign_resend_error:"Error resending code.",expand_row:"Expand row",expiration_date:"Expiration date",file_error:"File error",file_upload:"File upload",go_to_next_page:"Go to next page",go_to_previous_page:"Go to previous page",group_by_column:"Group by this column",heading_1:"Heading 1",heading_2:"Heading 2",heading_3:"Heading 3",image_description:"Image description",import_flows:"Import Flows",import_manage:"Manage your import flows",inactive:"inactive",inactive_user:"[Inactive user]",input_type:"Input type",invalid_form:"Invalid form. Fill in all required fields.",italic:"Italic",item_details:"Item details",items:"items",items_per_page:"Items per page",know_saber_gestao:"Discover Saber Gestão",know_staff:"Discover Staff",language:"Language",last_update:"Last update",leader:"Leader",leader_create_error:"Error creating leader",leader_not_found:"Leader not found",leader_promoted_success:"Leader promoted successfully",leader_remove_error:"Error removing leader",leader_removed_success:"Leader removed successfully",leader_update_error:"Error updating leader",leader_updated_success:"Leader updated successfully",leadership_add_root:"Add Root Leader",leadership_add_subordinate:"Add Subordinate",leadership_cycle_error:"This association would create a cycle in the hierarchy",leadership_define_leader:"Define Leader",leadership_immediate_superior:"Immediate Superior",leadership_make_root:"Make Root Leader",leadership_make_root_short:"Make Root",leadership_no_hierarchy:"No leadership hierarchy found.",leadership_no_members:"No team members",leadership_no_user_selected:"No user selected",leadership_no_users_available:"No users available",leadership_no_users_found:"No users found",leadership_remove_team:"Remove from team",leadership_select_subordinates:"Select at least one subordinate",learn_qualiex:"Learn how to use Qualiex",leave_without_saving:"Leave without saving",lines_per_page:"Lines per page",link:"Link",login_with_qualiex:"Login with Qualiex",manage_access:"Manage Access",mind_map_add_child:"Add child",mind_map_add_sibling:"Add sibling",mind_map_aria_label:"Mind map",mind_map_collapse_all:"Collapse all",mind_map_delete_node:"Delete node",mind_map_expand_all:"Expand all",mind_map_export_image:"Export as image",mind_map_export_json:"Export as JSON",mind_map_fit_to_screen:"Fit to screen",mind_map_redo:"Redo",mind_map_undo:"Undo",mind_map_zoom_in:"Zoom in",mind_map_zoom_out:"Zoom out",modules:"Modules",more_options:"More options",msg_create_error:"Error creating record",msg_created_success:"Record created successfully",msg_delete_error:"Error deleting record",msg_deleted_success:"Record deleted successfully",msg_load_error:"Error loading data",msg_update_error:"Error updating record",msg_updated_success:"Record updated successfully",new_document:"New Document",new_folder:"New Folder",new_item:"New Item",next:"Next",no_access_page:"It seems you don't have access to this page",no_data_to_display:"No data to display at this time.",no_errors_recorded:"No errors recorded",no_image_selected:"No image selected",no_item_selected:"No item selected",no_items_found:"No items found",no_items_found_empty:"No items found",no_place_found:"No place found",no_place_selected:"No place",no_products:"No products",no_reports_found:"No reports found",no_results:"No results found",no_search_results:"No results for the search",no_video_selected:"No video selected",not_authenticated:"Not authenticated",not_available:"Not available",of:"of",open_popover:"Open Popover",open_wiki:"Open Wiki",ordered_list:"Ordered List",page:"Page",paste_embed_code:"Paste the embed code here",permissions:"Permissions",preset_colors:"Preset colors",preview:"Preview",redirecting_auth:"Redirecting to authentication...",refresh_data:"Refresh data",remove:"Remove",remove_grouping:"Remove grouping",replace:"Replace",report:"Report",request_date:"Request date",required_field:"Required field",resend_code:"Resend code",restricted_access:"Restricted access",rows_per_page:"Rows per page",save:"Save",save_as_draft:"Save as Draft",save_as_template:"Save as Template",saving:"Saving...",search:"Search",search_placeholder:"Search...",search_report_placeholder:"Search report...",search_user_placeholder:"Search user...",select_all:"Select all",select_all_columns:"Select all",select_all_items:"Select all",select_at_least_one:"Select at least one item",select_at_least_one_item:"Select at least one item",select_date:"Select a date",select_file_format:"Select the file format",select_items_to_add:"Select items to add...",select_placeholder:"Select...",selected:"Selected",session_expired:"Your session has expired. You will be redirected to log in again.",sign_access_error:"Error accessing signature service",sign_api_key_info:"Enter the signature provider API Key",sign_api_key_input:"Enter the signature provider API Key",sign_api_key_placeholder:"Enter API key",sign_api_key_required:"API key is required",sign_attempt:"Signature attempt",sign_auth_required:"Authentication required to sign",sign_click_to_select:"Click to select document",sign_config_save_err:"Error saving signature configuration",sign_config_save_error:"Error saving signature configuration",sign_config_saved:"Signature configuration saved",sign_config_saved_success:"Signature configuration saved successfully",sign_configured:"Signature configured",sign_configured_unit:"Digital signature configured for this unit",sign_digital_config:"Digital Signature Configuration",sign_doc_available:"Signed document available for download",sign_doc_load_error:"Error loading document",sign_doc_process_error:"Error processing document",sign_doc_sent:"Document sent for signature",sign_download_signed:"Download signed document",sign_email_fallback:"Signature fallback email",sign_environment:"Signature environment",sign_fetch_failed:"Failed to fetch signed document",sign_file_not_allowed:"File extension not allowed",sign_file_type_not_allowed:"File type not allowed",sign_incorrect_data:"The signer reported incorrect data.",sign_login_required:"Login required to sign",sign_login_to_sign:"Log in to use the digital signature.",sign_monthly_limit:"Monthly signature limit reached",sign_no_access:"Could not obtain access for signing. Try again.",sign_not_configured:"Signature not configured",sign_not_configured_unit:"Digital signature not yet configured for this unit",sign_preparing_doc:"Preparing document for signature",sign_process_error:"Error processing signature",sign_save_config:"Save configuration",sign_save_config_btn:"Save Configuration",sign_select_pdf:"Select a PDF file",sign_sending_doc:"Sending document for signature",sign_signed_success:"Document signed successfully",sign_signer_unavailable:"Signer ID not available",sign_try_again:"Try again",sign_update_config:"Update configuration",sign_update_config_btn:"Update Configuration",sign_waiting_provider:"Waiting for signature provider",sign_widget_error:"Signature widget error",something_went_wrong:"Something went wrong",state:"State",status:"Status",status_completed:"Completed",status_error:"Error",status_expired:"Expired",status_processing:"Processing",status_waiting:"Waiting",steps:"Steps",subordinates_add_error:"Error adding subordinates",subordinates_added_success:"Subordinates added successfully",subordinates_sync_error:"Error syncing subordinates",subordinates_synced_success:"Subordinates synced successfully",team_all_groups:"All groups",terms_confirm_reading:"Confirm reading",terms_confirmation_available:"Confirmation available at",terms_of_use:"Terms of Use",terms_read_agree:"I have read and agree",terms_see_later:"See later",terms_updated:"Terms of Use Updated",terms_view:"View terms of use",terms_view_short:"View term",try_adjust_search:"Try adjusting your search",try_again:"Try Again",unit_not_selected:"No unit selected",unknown_error:"Unknown error",unsaved_changes:"Unsaved changes",unsaved_changes_description:"There are unsaved changes. Do you want to leave without saving?",updates:"Updates",user:"User",user_info:"User Information",user_photo:"User photo",users_already_leaders:"Users are already leaders",verification_code:"Verification code",video:"Video",video_title:"Video title",view_report:"View report",want_to_know_more:"I want to know more",write_content_here:"Write content here..."},fc={actions:"Acciones",activate:"Activar",add_first_item:"Agregue su primer elemento para comenzar",add_item:"Agregar Elemento",advanced_filter:"Filtro avanzado",all:"Todos",allow:"Permitir",allowed_items:"Elementos permitidos",also_discover:"Conozca también",alt_text:"Texto Alternativo",anonymous:"Anónimo",ap_action_plan:"Plan de Acción",ap_action_type:"Tipo de acción",ap_add:"Agregar",ap_add_comment_placeholder:"Agregar comentario...",ap_add_cost:"Agregar costo",ap_add_predecessor:"Agregar predecesor",ap_attachments:"Anexos",ap_belongs_to:"Pertenece a",ap_cause:"Causa",ap_change_status:"Cambiar Estado",ap_checker:"Verificador",ap_clear:"Limpiar",ap_comments:"Comentarios",ap_cost_description:"Descripción del costo",ap_costs:"Costos",ap_delete:"Eliminar",ap_description:"Descripción",ap_description_placeholder:"Describa el plan de acción",ap_duration_days:"Duración (días)",ap_edit_progress:"Editar Progreso",ap_end_date:"Fecha de finalización",ap_estimated_cost:"Costo estimado",ap_file_duplicate:"Archivo duplicado",ap_file_upload_error:"Error al subir archivo",ap_general:"General",ap_general_info:"Información General",ap_history:"Historial",ap_justification:"Justificación",ap_justification_placeholder:"Justificación del plan de acción",ap_name:"Nombre",ap_new_action:"Nueva Acción",ap_no_attachments:"Sin anexos",ap_no_comments:"Sin comentarios",ap_no_costs:"Ningún costo registrado",ap_no_history:"Sin registros en el historial",ap_no_predecessors:"Sin predecesores agregados",ap_no_progress:"Sin datos de progreso disponibles",ap_overall_progress:"Progreso general",ap_place:"Lugar",ap_plan_name_placeholder:"Nombre del plan de acción",ap_predecessors:"Predecesores",ap_priority:"Prioridad",ap_priority_high:"Alta",ap_priority_low:"Baja",ap_priority_medium:"Media",ap_progress:"Progreso",ap_progress_comment_placeholder:"Agregue un comentario sobre el progreso",ap_progress_percent:"Progreso (%)",ap_report:"Reportar",ap_report_progress:"Reportar progreso",ap_reporting:"Reportando...",ap_reports_history:"Historial de reportes",ap_responsible:"Responsable",ap_select_action:"Seleccione una acción",ap_select_cause:"Seleccione la causa",ap_select_checker:"Seleccione el verificador",ap_select_date:"Seleccione la fecha",ap_select_parent:"Seleccione la acción padre",ap_select_place:"Seleccione el lugar",ap_select_priority:"Seleccione la prioridad",ap_select_responsible:"Seleccione el responsable",ap_select_type:"Seleccione el tipo",ap_start_date:"Fecha de inicio",ap_status_canceled:"Cancelada",ap_status_done:"Completada",ap_status_effectiveness_check:"Verificación de eficacia",ap_status_running:"En progreso",ap_status_suspended:"Suspendida",ap_status_waiting_start:"Esperando inicio",ap_time_label:"Tiempo",ap_time_spent:"Tiempo dedicado (HH:MM)",ap_total_cost:"Costo total realizado",ap_total_time:"Tiempo total",ap_type_corrective:"Correctiva",ap_type_immediate:"Inmediata",ap_type_improvement:"Oportunidad de Mejora",ap_type_preventive:"Preventiva",ap_type_standardization:"Estandarización",ap_value:"Valor",ap_via_app:"Vía app",approval_approve:"Aprobar",approval_execute_action:"Ejecutar acción",approval_opinion:"Opinión *",approval_read_less:"Leer menos",approval_read_more:"Leer más",approval_reprove_radio:"Rechazar y retornar a etapa",approval_search_approver:"Buscar aprobador...",approval_select_approver:"Seleccionar aprobador",approval_select_approver_placeholder:"Seleccione un aprobador...",approval_select_step:"Seleccione la etapa",approval_step_label:"Etapa",approval_user_group:"Grupo de usuarios",audit_description:"Descripción",audit_esign:"Firma electrónica",audit_not_informed:"No informado",audit_references:"Referencias",audit_security:"Seguridad",audit_trail:"Pista de Auditoría",auth_error:"Error durante la autenticación. Intente de nuevo.",auth_failed:"Fallo en la autenticación. Intente de nuevo.",auto_login:"Iniciando sesión automáticamente...",back:"Volver",bulk_delete_error:"Error al eliminar elementos en lote",bulk_delete_success:"Elementos eliminados exitosamente",cancel:"Cancelar",change_photo:"Cambiar foto",cannot_be_own_leader:"Un líder no puede ser su propio superior",clear_filters:"Limpiar filtros",clear_formatting:"Limpiar Formato",clear_search:"Limpiar búsqueda",clear_selection:"Limpiar selección",close:"Cerrar",collapse_row:"Contraer fila",columns:"Columnas",conclude:"Concluir",confirm_removal:"Confirmar eliminación",could_not_load_info:"No se pudo cargar la información",current:"Actual",custom_color:"Color personalizado",dashboard_advanced_filter:"Filtro avanzado",dashboard_all_access:"Todos los colaboradores tendrán acceso",dashboard_average:"Promedio",dashboard_code:"Código",dashboard_distinct_count:"Conteo distinto",dashboard_edit:"Editar Dashboard",dashboard_exit_fullscreen:"Salir de pantalla completa",dashboard_export_chart:"Exportar gráfico",dashboard_export_table:"Exportar tabla",dashboard_max_value:"Valor máximo",dashboard_min_value:"Valor mínimo",dashboard_my:"Mis dashboards",dashboard_new:"Nuevo Dashboard",dashboard_no_data:"La consulta no devolvió elementos para su perfil.",dashboard_no_refresh:"No actualizar",dashboard_normal_page:"Página normal",dashboard_not_shared:"No compartido",dashboard_only_mine:"Solo míos",dashboard_only_overdue:"Solo atrasados",dashboard_only_responsible:"Solo el responsable tendrá acceso",dashboard_open_query:"Abrir consulta",dashboard_remove_favorite:"Quitar favorito",dashboard_responsible:"Responsable",dashboard_select_groups:"Seleccione grupos, lugares y colaboradores específicos",dashboard_shared_unit:"Compartido con todos los colaboradores de la unidad",dashboard_status:"Situación",dashboard_title:"Título",dashboard_wait_refresh:"Espere para actualizar nuevamente",dashboard_work_done:"Trabajo ejecutado",dashboard_work_planned:"Trabajo planificado",deactivate:"Desactivar",deselect_all:"Deseleccionar todas",dev_login:"Login Desarrollo",download:"Descargar",edit:"Editar",edit_profile:"Editar Perfil",edit_name:"Editar Nombre",electronic_signature:"Firma Electrónica",embed_code:"Código embed",embedded_content:"Contenido embebido",enter_code:"Ingrese el código",enter_password:"Ingrese su contraseña",error_authentication:"Error de Autenticación",error_connection:"Error de Conexión",error_copied_clipboard:"Los detalles del error se copiaron al portapapeles.",error_loading:"Error al cargar",error_loading_data:"Error al cargar datos",error_session_expired:"Sesión Expirada",error_token_expired:"Token de autenticación expirado. Inicie sesión nuevamente.",esign_code_description:"Un código de verificación fue enviado a su correo. Ingrese el código a continuación para confirmar la operación.",esign_code_error:"Error al validar el código. Intente de nuevo.",esign_invalid_code:"Código inválido. Intente de nuevo.",esign_invalid_password:"Contraseña incorrecta. Intente de nuevo.",esign_password_description:"Ingrese su contraseña para confirmar la operación.",esign_password_error:"Error al validar la contraseña. Intente de nuevo.",esign_resend_error:"Error al reenviar el código.",expand_row:"Expandir fila",expiration_date:"Fecha de expiración",file_error:"Error en el archivo",file_upload:"Subir archivo",go_to_next_page:"Ir a la página siguiente",go_to_previous_page:"Ir a la página anterior",group_by_column:"Agrupar por esta columna",heading_1:"Título 1",heading_2:"Título 2",heading_3:"Título 3",image_description:"Descripción de la imagen",import_flows:"Flujos de Importación",import_manage:"Gestione sus flujos de importación",inactive:"inactivo",inactive_user:"[Usuario inactivo]",input_type:"Tipo de entrada",invalid_form:"Formulario inválido. Complete todos los campos obligatorios.",italic:"Itálica",item_details:"Detalles del elemento",items:"elementos",items_per_page:"Elementos por página",know_saber_gestao:"Conozca Saber Gestión",know_staff:"Conozca Staff",language:"Idioma",last_update:"Última actualización",leader:"Líder",leader_create_error:"Error al crear líder",leader_not_found:"Líder no encontrado",leader_promoted_success:"Líder promovido exitosamente",leader_remove_error:"Error al eliminar líder",leader_removed_success:"Líder eliminado exitosamente",leader_update_error:"Error al actualizar líder",leader_updated_success:"Líder actualizado exitosamente",leadership_add_root:"Agregar Líder Raíz",leadership_add_subordinate:"Agregar Subordinado",leadership_cycle_error:"Esta asociación crearía un ciclo en la jerarquía",leadership_define_leader:"Definir Líder",leadership_immediate_superior:"Superior Inmediato",leadership_make_root:"Hacer Líder Raíz",leadership_make_root_short:"Hacer Raíz",leadership_no_hierarchy:"No se encontró jerarquía de liderazgo.",leadership_no_members:"Ningún miembro en el equipo",leadership_no_user_selected:"Ningún usuario seleccionado",leadership_no_users_available:"Ningún usuario disponible",leadership_no_users_found:"Ningún usuario encontrado",leadership_remove_team:"Quitar del equipo",leadership_select_subordinates:"Seleccione al menos un subordinado",learn_qualiex:"Aprenda a usar Qualiex",leave_without_saving:"Salir sin guardar",lines_per_page:"Líneas por página",link:"Enlace",login_with_qualiex:"Iniciar sesión con Qualiex",manage_access:"Gestionar Accesos",mind_map_add_child:"Agregar hijo",mind_map_add_sibling:"Agregar hermano",mind_map_aria_label:"Mapa mental",mind_map_collapse_all:"Colapsar todo",mind_map_delete_node:"Eliminar nodo",mind_map_expand_all:"Expandir todo",mind_map_export_image:"Exportar como imagen",mind_map_export_json:"Exportar como JSON",mind_map_fit_to_screen:"Ajustar a la pantalla",mind_map_redo:"Rehacer",mind_map_undo:"Deshacer",mind_map_zoom_in:"Acercar",mind_map_zoom_out:"Alejar",modules:"Módulos",more_options:"Más opciones",msg_create_error:"Error al crear registro",msg_created_success:"Registro creado exitosamente",msg_delete_error:"Error al eliminar registro",msg_deleted_success:"Registro eliminado exitosamente",msg_load_error:"Error al cargar datos",msg_update_error:"Error al actualizar registro",msg_updated_success:"Registro actualizado exitosamente",new_document:"Nuevo Documento",new_folder:"Nueva Carpeta",new_item:"Nuevo Elemento",next:"Siguiente",no_access_page:"Parece que no tienes acceso a esta página",no_data_to_display:"No hay datos para mostrar en este momento.",no_errors_recorded:"Sin errores registrados",no_image_selected:"Ninguna imagen seleccionada",no_item_selected:"Ningún elemento seleccionado",no_items_found:"No se encontraron elementos",no_items_found_empty:"Ningún elemento encontrado",no_place_found:"Ningún lugar encontrado",no_place_selected:"Sin lugar",no_products:"Sin productos",no_reports_found:"Ningún informe encontrado",no_results:"No se encontraron resultados",no_search_results:"Sin resultados para la búsqueda",no_video_selected:"Ningún vídeo seleccionado",not_authenticated:"No autenticado",not_available:"No disponible",of:"de",open_popover:"Abrir Popover",open_wiki:"Abrir Wiki",ordered_list:"Lista Ordenada",page:"Página",paste_embed_code:"Pegue el código embed aquí",permissions:"Permisos",preset_colors:"Colores predefinidos",preview:"Vista previa",redirecting_auth:"Redirigiendo a autenticación...",refresh_data:"Actualizar datos",remove:"Eliminar",remove_grouping:"Quitar agrupación",replace:"Reemplazar",report:"Informe",request_date:"Fecha de solicitud",required_field:"Campo obligatorio",resend_code:"Reenviar código",restricted_access:"Acceso restringido",rows_per_page:"Registros por página",save:"Guardar",save_as_draft:"Guardar como Borrador",save_as_template:"Guardar como Plantilla",saving:"Guardando...",search:"Buscar",search_placeholder:"Buscar...",search_report_placeholder:"Buscar informe...",search_user_placeholder:"Buscar usuario...",select_all:"Seleccionar todo",select_all_columns:"Seleccionar todas",select_all_items:"Seleccionar todos",select_at_least_one:"Seleccione al menos un elemento",select_at_least_one_item:"Seleccione al menos un elemento",select_date:"Seleccione una fecha",select_file_format:"Seleccione el formato del archivo",select_items_to_add:"Seleccione elementos para agregar...",select_placeholder:"Seleccionar...",selected:"Seleccionados",session_expired:"Su sesión ha expirado. Será redirigido para iniciar sesión nuevamente.",sign_access_error:"Error al acceder al servicio de firma",sign_api_key_info:"Ingrese la API Key del proveedor de firma",sign_api_key_input:"Ingrese la API Key del proveedor de firma",sign_api_key_placeholder:"Ingrese la clave de API",sign_api_key_required:"Clave de API obligatoria",sign_attempt:"Intento de firma",sign_auth_required:"Autenticación requerida para firmar",sign_click_to_select:"Haga clic para seleccionar documento",sign_config_save_err:"Error al guardar configuración de firma",sign_config_save_error:"Error al guardar configuración de firma",sign_config_saved:"Configuración de firma guardada",sign_config_saved_success:"Configuración de firma guardada exitosamente",sign_configured:"Firma configurada",sign_configured_unit:"Firma digital configurada para esta unidad",sign_digital_config:"Configuración de Firma Digital",sign_doc_available:"Documento firmado disponible para descarga",sign_doc_load_error:"Error al cargar documento",sign_doc_process_error:"Error al procesar documento",sign_doc_sent:"Documento enviado para firma",sign_download_signed:"Descargar documento firmado",sign_email_fallback:"Correo de respaldo para firma",sign_environment:"Ambiente de firma",sign_fetch_failed:"Error al obtener documento firmado",sign_file_not_allowed:"Extensión de archivo no permitida",sign_file_type_not_allowed:"Tipo de archivo no permitido",sign_incorrect_data:"El firmante reportó datos incorrectos.",sign_login_required:"Inicio de sesión requerido para firmar",sign_login_to_sign:"Inicie sesión para usar la firma digital.",sign_monthly_limit:"Límite mensual de firmas alcanzado",sign_no_access:"No se pudo obtener acceso para firma. Intente de nuevo.",sign_not_configured:"Firma no configurada",sign_not_configured_unit:"Firma digital aún no configurada para esta unidad",sign_preparing_doc:"Preparando documento para firma",sign_process_error:"Error al procesar firma",sign_save_config:"Guardar configuración",sign_save_config_btn:"Guardar Configuración",sign_select_pdf:"Seleccione un archivo PDF",sign_sending_doc:"Enviando documento para firma",sign_signed_success:"Documento firmado exitosamente",sign_signer_unavailable:"ID del firmante no disponible",sign_try_again:"Intentar de nuevo",sign_update_config:"Actualizar configuración",sign_update_config_btn:"Actualizar Configuración",sign_waiting_provider:"Esperando proveedor de firma",sign_widget_error:"Error en el widget de firma",something_went_wrong:"Algo salió mal",state:"Estado",status:"Estado",status_completed:"Completado",status_error:"Error",status_expired:"Expirado",status_processing:"Procesando",status_waiting:"Esperando",steps:"Etapas",subordinates_add_error:"Error al agregar subordinados",subordinates_added_success:"Subordinados agregados exitosamente",subordinates_sync_error:"Error al sincronizar subordinados",subordinates_synced_success:"Subordinados sincronizados exitosamente",team_all_groups:"Todos los grupos",terms_confirm_reading:"Confirmar lectura",terms_confirmation_available:"Confirmación disponible en",terms_of_use:"Términos de Uso",terms_read_agree:"He leído y acepto",terms_see_later:"Ver después",terms_updated:"Términos de Uso Actualizados",terms_view:"Ver términos de uso",terms_view_short:"Ver término",try_adjust_search:"Intente ajustar su búsqueda",try_again:"Intentar de Nuevo",unit_not_selected:"Ninguna unidad seleccionada",unknown_error:"Error desconocido",unsaved_changes:"Cambios sin guardar",unsaved_changes_description:"Hay cambios sin guardar. ¿Desea salir sin guardar?",updates:"Actualizaciones",user:"Usuario",user_info:"Información del Usuario",user_photo:"Foto del usuario",users_already_leaders:"Los usuarios ya son líderes",verification_code:"Código de verificación",video:"Video",video_title:"Título del vídeo",view_report:"Ver informe",want_to_know_more:"Quiero conocer más",write_content_here:"Escriba el contenido aquí..."};const gc="true"===import.meta.env.VITE_I18N_DEBUG_MODE;function vc(a,t){e.addResourceBundle(a,"app",t,!0,!0)}gc&&e.use({type:"postProcessor",name:"debugKeys",process:(e,a)=>`🔑 ${Array.isArray(a)?a[0]:a}`}),e.use(Ka).init({resources:{"pt-BR":{core:pc},"en-US":{core:hc},"es-ES":{core:fc}},fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"app",fallbackNS:"core",ns:["core"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e,postProcess:gc?["debugKeys"]:[]});const bc=d(void 0),xc={locale:hi,timezone:gi,datetimeFormat:fi},yc=async()=>{},Nc=({children:e})=>a(bc.Provider,{value:{...xc,setLocale:yc,setTimezone:yc,setDatetimeFormat:yc,isLoading:!1},children:e}),wc=()=>{const e=c(bc);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},_c=d({moduleAlias:null});function Cc({moduleAlias:e=null,children:t}){return a(_c.Provider,{value:{moduleAlias:e},children:t})}function kc(){return c(_c)}const Sc=pt.Root,Ac=pt.CollapsibleTrigger,Ec=pt.CollapsibleContent;class Dc extends h{constructor(a){super(a),this.copyErrorDetails=()=>{const a=Qs.getErrors().slice(0,2),t=`\n=== ERRO ATUAL ===\n${this.state.error?.message||e.t("unknown_error")}\n\nStack Trace:\n${this.state.error?.stack||e.t("not_available")}\n\n=== ÚLTIMOS ERROS ===\n${a.map((e,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||e.t("no_errors_recorded")}\n `.trim();navigator.clipboard.writeText(t),C.success("Detalhes copiados!",{description:e.t("error_copied_clipboard")})},this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;Qs.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const r=Qs.getErrors().slice(0,2);return a("div",{className:"flex items-center justify-center min-h-screen p-4",children:t(Gi,{className:"w-full max-w-2xl",children:[t(Ki,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(de,{className:"h-12 w-12 text-destructive"})}),a(Yi,{children:e.t("something_went_wrong")})]}),t(Xi,{className:"space-y-4",children:[a("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),t(Sc,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[a(Ac,{asChild:!0,children:t($i,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[a(D,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),t(Ec,{className:"mt-4 space-y-4",children:[t("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[t("div",{children:[a("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),t("div",{className:"text-sm space-y-2",children:[a("p",{className:"font-medium text-destructive",children:this.state.error?.message||e.t("unknown_error")}),this.state.error?.stack&&a(Dd,{className:"h-32 w-full rounded border bg-muted p-2",children:a("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),r.length>0&&t("div",{className:"pt-3 border-t",children:[a("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),a("div",{className:"space-y-2",children:r.map((e,r)=>a("div",{className:"text-sm p-2 rounded bg-muted/50",children:t("div",{className:"flex items-start gap-2",children:[t("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),t("div",{className:"flex-1 min-w-0",children:[a("div",{className:"flex items-center gap-2 flex-wrap",children:t("span",{className:"text-xs text-muted-foreground",children:["[",new Date(e.timestamp).toLocaleTimeString(),"]"]})}),a("p",{className:"text-sm break-words",children:e.message})]})]})},e.id))})]})]}),t($i,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[a(me,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),a($i,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Pc=ht.Root,Ic=n.forwardRef(({className:e,...t},r)=>a(ht.List,{ref:r,className:Fi("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),...t}));Ic.displayName=ht.List.displayName;const Tc=n.forwardRef(({className:e,...t},r)=>a(ht.Trigger,{ref:r,className:Fi("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}));Tc.displayName=ht.Trigger.displayName;const Rc=n.forwardRef(({className:e,...t},r)=>a(ht.Content,{ref:r,className:Fi("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));function Mc({className:e}){return t("svg",{className:e,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a("path",{d:"M0.5 11.7455C0.5 10.2633 2.25695 9.52546 3.36816 10.4399L22.4346 26.1528C23.3588 26.9137 23.229 28.3353 22.1953 28.9301L16.3418 32.2963C15.7961 32.6097 15.1199 32.6098 14.5742 32.2963L1.36133 24.7006C0.832671 24.3966 0.500052 23.8398 0.5 23.2289V11.7455Z",stroke:"currentColor"}),a("path",{d:"M14.612 0.735352C15.1576 0.421927 15.833 0.421964 16.3786 0.735352L25.3776 5.90723V5.9082C26.5447 6.5808 26.5183 8.24018 25.3298 8.875L25.3307 8.87598L13.9333 14.9697L13.9323 14.9688C13.3016 15.3066 12.5233 15.2301 11.9733 14.7773L4.90302 8.9541C3.97881 8.19317 4.1086 6.77256 5.14227 6.17773L14.612 0.735352Z",stroke:"currentColor"}),a("path",{d:"M28.1066 9.7966C29.2466 9.18579 30.6895 9.9732 30.6896 11.2937V23.0691C30.6895 23.6825 30.3539 24.2382 29.8264 24.5417L29.8254 24.5427L27.3449 25.9607C26.7486 26.3015 26.0057 26.264 25.4494 25.8747L25.341 25.7917L16.6076 18.5974C15.6649 17.821 15.8224 16.3676 16.8937 15.7937V15.7927L28.1066 9.79758V9.7966Z",stroke:"currentColor"})]})}function Lc({className:e}){return t("svg",{className:e,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a("path",{d:"M0.524143 8.74979C1.44754 8.74979 2.36325 8.74979 3.30973 8.74979C3.30973 8.90069 3.30973 9.05162 3.30973 9.19497C3.30973 9.79101 3.64061 10.1154 4.24082 10.1154C6.8879 10.1154 9.54268 10.1154 12.1898 10.1154C12.7592 10.1154 13.1286 9.77589 13.1132 9.27793C13.0978 8.8856 12.8054 8.5612 12.3745 8.51594C11.2279 8.38767 10.0736 8.26696 8.91938 8.1387C7.72666 8.01043 6.52625 7.88216 5.33352 7.74635C4.71792 7.67845 4.10232 7.61811 3.48672 7.53511C2.00928 7.32386 0.754978 6.06386 0.547213 4.61526C0.331752 3.10631 1.00122 1.73316 2.34015 0.963593C2.89419 0.646712 3.5021 0.503353 4.14848 0.503353C6.84943 0.503353 9.55038 0.495808 12.2513 0.503353C14.0904 0.510898 15.5448 1.71808 15.8603 3.49865C15.8988 3.7099 15.8988 3.92116 15.9065 4.13996C15.9141 4.2984 15.9065 4.44928 15.9065 4.61526C14.9677 4.61526 14.0443 4.61526 13.0978 4.61526C13.0978 4.44928 13.0978 4.28329 13.0978 4.1173C13.0901 3.58162 12.7592 3.25719 12.2206 3.24965C9.53499 3.24965 6.84943 3.24965 4.17157 3.24965C3.69448 3.24965 3.36359 3.52881 3.30203 3.97396C3.24816 4.3512 3.51749 4.73597 3.90224 4.8265C4.10231 4.87177 4.31008 4.88687 4.51784 4.9095C5.8183 5.05285 7.12645 5.19622 8.42691 5.33957C9.71198 5.48292 10.997 5.63382 12.2898 5.75453C13.1824 5.83753 13.9981 6.08649 14.6906 6.68253C16.1604 7.92742 16.3066 10.2588 14.9984 11.6696C14.2443 12.4845 13.3132 12.8844 12.1975 12.8844C9.5273 12.8844 6.84944 12.8844 4.17927 12.8844C2.55562 12.8844 1.21669 11.9563 0.678043 10.4549C0.539533 9.98715 0.470277 9.38356 0.524143 8.74979Z",stroke:"currentColor"}),a("path",{d:"M8.21913 24.2393C8.21913 24.2317 8.21913 24.2317 8.21913 24.2393ZM8.21913 24.2393C8.98863 24.2393 9.75812 24.2619 10.5199 24.2317C11.7511 24.1789 12.9285 23.1378 13.067 21.9381C13.1439 21.3119 13.1285 20.6706 13.1131 20.0368C13.067 18.6335 11.8743 17.4339 10.443 17.3962C8.96554 17.3584 7.4881 17.366 6.00296 17.3962C4.70251 17.4263 3.54055 18.4373 3.37896 19.6973C3.29431 20.3462 3.3097 21.0101 3.34048 21.6665C3.40204 23.017 4.58708 24.1789 5.96449 24.2317C6.7186 24.2619 7.46502 24.2393 8.21913 24.2393ZM13.1439 15.427C13.7441 14.8385 14.3367 14.2575 14.9138 13.6917C15.5756 14.333 16.2296 14.9818 16.9222 15.6608C16.8914 15.6759 16.8298 15.7061 16.7837 15.7438C16.2604 16.2493 15.7448 16.7624 15.2216 17.2679C15.1446 17.3434 15.1369 17.4037 15.1908 17.4943C15.7064 18.3845 15.9526 19.3427 15.9295 20.3613C15.9141 20.9799 15.9526 21.6062 15.8603 22.2097C15.5371 24.2846 14.352 25.7332 12.3975 26.5782C11.7126 26.8724 10.9816 26.9931 10.2352 26.9931C8.89629 26.9931 7.56504 26.9931 6.22611 26.9931C3.49438 26.9931 1.20897 25.1899 0.631845 22.5719C0.56259 22.2475 0.524115 21.9155 0.51642 21.5835C0.508725 20.9422 0.470242 20.2933 0.547192 19.6596C0.816518 17.3584 2.08619 15.7967 4.27927 14.9516C4.84101 14.7328 5.42584 14.6347 6.02605 14.6347C7.4958 14.6347 8.96554 14.6272 10.4276 14.6423C11.3279 14.6498 12.1667 14.9064 12.9516 15.3289C13.0131 15.3591 13.067 15.3892 13.1439 15.427Z",stroke:"currentColor"}),a("path",{d:"M0.508791 28.3813C1.43989 28.3813 2.3633 28.3813 3.2944 28.3813C3.31748 28.4945 3.32516 28.6001 3.35594 28.7058C3.50984 29.2943 4.01772 29.7017 4.63332 29.7319C4.76414 29.7394 4.89496 29.7394 5.02578 29.7394C7.22655 29.7394 9.4273 29.7394 11.6281 29.7394C12.3206 29.7394 12.8439 29.3923 13.0363 28.7963C13.0747 28.668 13.0978 28.5323 13.1286 28.3889C14.0443 28.3889 14.9677 28.3889 15.9142 28.3889C15.9219 28.7435 15.868 29.0906 15.7757 29.4301C15.2986 31.1955 13.6519 32.4782 11.7897 32.4857C9.39653 32.5008 7.01108 32.5083 4.61794 32.4857C2.44025 32.4706 0.624216 30.7353 0.508791 28.6077C0.501096 28.5322 0.508791 28.4643 0.508791 28.3813Z",stroke:"currentColor"})]})}Rc.displayName=ht.Content.displayName;const zc={init(e){!function(e){try{return void function(e,a,t,r,n,i,o){a.getElementById("clarity-script")||(e[t]=e[t]||function(){(e[t].q=e[t].q||[]).push(arguments)},(i=a.createElement(r)).async=1,i.src="https://www.clarity.ms/tag/"+n+"?ref=npm",i.id="clarity-script",(o=a.getElementsByTagName(r)[0]).parentNode.insertBefore(i,o))}(window,document,"clarity","script",e)}catch(a){return}}(e)},setTag(e,a){window.clarity("set",e,a)},identify(e,a,t,r){window.clarity("identify",e,a,t,r)},consent(e=!0){window.clarity("consent",e)},consentV2(e={ad_Storage:"granted",analytics_Storage:"granted"}){window.clarity("consentv2",e)},upgrade(e){window.clarity("upgrade",e)},event(e){window.clarity("event",e)}},Fc="forlogic_";function Uc(){return"undefined"!=typeof window&&"function"==typeof window.clarity}function jc(){return"undefined"!=typeof window&&"piggyback"===window.__forlogicClarityMode}function Oc(e){return jc()?`${Fc}${e}`:e}function Bc(e){return jc()?`${Fc}${e}`:e}function $c(e){try{e()}catch(a){import.meta.env.DEV}}function Vc(e){for(const[a,t]of Object.entries(e))null!=t&&""!==t&&zc.setTag(Bc(a),t)}function qc({module:e,isContracted:a,sourceModule:t,alias:r}){Uc()&&$c(()=>{Vc({clicked_module:e.name,clicked_module_id:e.softwareAlias,is_contracted:String(a),source_module:t,alias:r}),zc.event(Oc("module_menu_click"))})}function Wc({module:e,sourceModule:a,alias:t}){Uc()&&$c(()=>{Vc({clicked_module:e.name,clicked_module_id:e.softwareAlias,is_contracted:"false",source_module:a,alias:t}),zc.event(Oc("module_interest_click"))})}function Hc({resource:e,sourceModule:a,alias:t}){Uc()&&$c(()=>{Vc({footer_resource:e,source_module:a,alias:t}),zc.event(Oc("module_footer_click"))})}function Gc({educaUrl:e="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n,alias:i,sourceModule:o}){const{t:s}=Ga(),l=zi(e||n||"https://educacao.sabergestao.com.br/{alias}/fe",i),d=e=>{Hc({resource:e,sourceModule:o,alias:i})};return t("div",{className:"flex-shrink-0 pt-4",children:[a(Zi,{className:"mb-4"}),t("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3",children:[t("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[t("div",{className:"relative z-10",children:[a("h4",{className:"font-semibold text-sm text-white",children:s("learn_qualiex")}),t("a",{href:l,target:"_blank",rel:"noopener noreferrer",onClick:()=>d("educa"),className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",a(pe,{className:"h-3.5 w-3.5"})]})]}),a(Mc,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),t("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[t("div",{className:"relative z-10",children:[a("h4",{className:"font-semibold text-sm text-foreground",children:s("know_saber_gestao")}),t("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:()=>d("saber-gestao"),className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",a(pe,{className:"h-3.5 w-3.5"})]})]}),a(Lc,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),t("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[t("div",{className:"relative z-10",children:[a("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),t("a",{href:n||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",onClick:()=>d("wiki"),className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",a(pe,{className:"h-3.5 w-3.5"})]})]}),a(he,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}const Kc=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias={alias}"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias={alias}"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function Yc({module:e,onClick:r}){return t("button",{type:"button",onClick:r,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[a("div",{className:Fi("w-4 h-4 rounded-sm shrink-0 mt-0.5",e.color)}),t("div",{className:"min-w-0",children:[a("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:e.name}),e.description&&a("div",{className:"text-sm text-muted-foreground truncate",children:e.description})]})]})}function Qc(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let i=0;i<a;i++){const a=i*t+n;a<e.length&&r.push(e[a])}return r}function Xc({modules:e,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const s=function(){const[e,a]=o(4);return m(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...e].sort((e,a)=>e.name.localeCompare(a.name)),d=void 0!==n,c=d?l.filter(e=>n.includes(e.name)):l,u=d?l.filter(e=>!n.includes(e.name)):[],p=Qc(c,s),h=Qc(u,s),f=(e,a)=>{a?r?.(e):i?.(e)};return t("div",{className:"space-y-6",children:[p.length>0&&a("section",{children:a("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(e=>a(Yc,{module:e,onClick:()=>f(e,!0)},e.name))})}),h.length>0&&t("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[a("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),a("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(e=>a(Yc,{module:e,onClick:()=>f(e,!1)},e.name))})]})]})}function Jc({onModuleClick:e,contractedModules:r,onModuleInterest:n,nonContractedUrl:i="https://qualiex.com/",educaUrl:s="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:d,alias:c,sourceModule:u}){const[m,p]=o("qualiex"),h=e=>{Wc({module:e,sourceModule:u,alias:c}),window.open(i,"_blank","noopener,noreferrer"),n?.(e)};return t("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[t(Pc,{value:m,onValueChange:p,className:"flex-1 flex flex-col min-h-0",children:[a(Ic,{className:"w-fit shrink-0",children:Kc.map(e=>t(Tc,{value:e.id,children:[e.label,t("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),Kc.map(t=>a(Rc,{value:t.id,className:"flex-1 mt-4 overflow-auto pr-2",children:a(Xc,{modules:t.modules,onModuleClick:a=>{return n=a,i=t.id,qc({module:n,isContracted:"qualiex"!==i||!r||r.includes(n.name),sourceModule:u,alias:c}),void e?.(n);var n,i},contractedModules:"qualiex"===t.id?r:void 0,onModuleInterest:h})},t.id))]}),a(Gc,{educaUrl:s,saberGestaoUrl:l,wikiUrl:d,alias:c,sourceModule:u})]})}const Zc={analysis:12,decisions:13,audit:1,common:0,competencies:23,performance:24,docs:17,education:25,flow:7,suppliers:15,"suppliers-portal":16,mapping:11,metrology:8,control:18,msa:21,occurrences:3,okr:26,pdi:27,plans:6,"strategy-extension":14,pulse:28,boards:10,risks:4,fmea:20,staff:19,"control-plan":22},eu=6e5;function au(e){const{moduleAlias:a}=kc(),{alias:t,user:r,isAuthenticated:n}=kl(),i=e??a,o=r?.id??null,d=n&&!!t&&!!o,{data:c=[],isLoading:u}=Ja({queryKey:["qualiex-associations",o,t],queryFn:()=>ll.fetchUserAssociations(o,t),enabled:d,staleTime:eu,gcTime:12e5}),m=s(()=>t&&0!==c.length?c.find(e=>e.companyAlias===t)??null:null,[c,t]),p=l(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Zc[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:s(()=>!i||p(i),[i,p]),isLoading:d&&u,role:s(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:p}}function tu(e){const{association:a}=au();return s(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=Kc.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=Zc[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function ru({open:e,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:d,sourceModule:c}){const{alias:u}=kl(),m=tu(i);return a(mo,{open:e,onOpenChange:r,children:t(bo,{size:"lg",className:"overflow-hidden flex flex-col",children:[a(xo,{className:"sr-only",children:a(wo,{children:"Módulos"})}),a(Jc,{onModuleClick:e=>{n?n(e):e.url&&Li(zi(e.url,u||void 0))},contractedModules:m,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:d,alias:u||void 0,sourceModule:c})]})})}function nu({open:r,onOpenChange:n,onModuleClick:i,contractedModules:o,onModuleInterest:l,userName:d,unitName:c,units:u=[],currentAlias:m,onUnitChange:p,onLogout:h,educaUrl:f,saberGestaoUrl:g,wikiUrl:v,blocking:b=!0,size:x="lg",children:y,sourceModule:N}){const{t:w}=Ga(),_=s(()=>{if(!u.length)return[];const e=new Map;u.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===m),r=a.filter(e=>e.alias!==m).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[u,m]);return a(mo,{open:r,onOpenChange:b?void 0:n,children:t(bo,{size:x,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:b?e=>e.preventDefault():void 0,onEscapeKeyDown:b?e=>e.preventDefault():void 0,children:[t("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[t("div",{className:"flex flex-col gap-1.5 text-left",children:[a(wo,{children:w("no_access_page")}),a(_o,{children:"Selecione um módulo para continuar navegando!"})]}),t("div",{className:"flex items-center gap-2 shrink-0",children:[_.length>1&&t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[a(fe,{className:"h-4 w-4 shrink-0"}),a("span",{className:"truncate text-xs",children:c||"Unidade"}),a(D,{className:"h-3 w-3 shrink-0"})]})}),a(os,{align:"end",className:"max-h-[300px] overflow-auto",children:_.map(e=>t(ss,{onClick:()=>p?.(e),className:e.alias===m?"bg-muted":"",children:[a(fe,{className:"mr-2 h-4 w-4 shrink-0"}),a("span",{className:"truncate",children:e.name}),e.alias===m&&a(Go,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},e.alias))})]}),t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"ghost",size:"sm",className:"gap-2",children:[a("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:a(ge,{className:"h-3.5 w-3.5 text-primary-foreground"})}),a(D,{className:"h-3 w-3"})]})}),t(os,{align:"end",children:[t("div",{className:"px-2 py-1.5",children:[a("p",{className:"text-sm font-medium",children:d||e.t("user")}),a("p",{className:"text-xs text-muted-foreground",children:c})]}),a(us,{}),t(ss,{onClick:h,children:[a(ve,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),y?t("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[a("div",{className:"flex-1",children:y}),a(Gc,{educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m,sourceModule:N})]}):a(Jc,{onModuleClick:i,contractedModules:o,onModuleInterest:l,educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m,sourceModule:N})]})})}function iu(e,a){const{t:t}=Ga();return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function ou({children:e,contractedModules:t,onModuleClick:n,onModuleInterest:i,educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:d="https://sabergestao.com.br/",wikiUrl:c,bypassPaths:u,accessDeniedRoutes:m,sourceModule:p}){const{t:h}=Ga(),{hasAccess:f,isLoading:g,association:v}=au(),{user:b,alias:x,companies:y,isAuthenticated:N,isLoading:w,logout:_,switchUnit:C}=kl(),k=tu(t),S=s(()=>y?.length?x&&y.find(e=>e.alias===x)||y[0]:null,[y,x]),A=s(()=>y?.length?y.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[y]),E=l(e=>{const a=y?.find(a=>a.alias===e.alias);if(!a)return;const{pathname:t,search:r,hash:n}=window.location;if(x){const e=t.split("/"),i=e.indexOf(x);if(i>=0)return e[i]=a.alias,void(window.location.href=e.join("/")+r+n)}C(a)},[x,C,y]),D=l(e=>{n?n(e):e.url&&Li(zi(e.url,x||void 0))},[n,x]),P=s(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>iu(e,[a]));return a?m[a]:void 0},[m]);return w||!N||u?.length&&iu(window.location.pathname,u)?a(r,{children:e}):g?a("div",{className:"flex items-center justify-center min-h-screen",children:a(Yo,{size:"lg"})}):f?a(r,{children:e}):a(nu,{open:!0,onModuleClick:D,contractedModules:k,onModuleInterest:i,userName:b?.name,unitName:S?.name,units:A,currentAlias:x||void 0,onUnitChange:E,onLogout:_,educaUrl:o,saberGestaoUrl:d,wikiUrl:c,sourceModule:p,blocking:!0,children:P})}function su({title:e,description:r,image:n,icon:i,ctaLabel:o,onCtaClick:s,children:l}){const{t:d}=Ga(),c=o??d("want_to_know_more");return t("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||i)&&a("div",{className:"flex items-center justify-center",children:n?a("img",{src:n,alt:e,className:"max-h-48 w-auto object-contain rounded-lg"}):i?a("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:a(i,{className:"h-12 w-12 text-primary"})}):null}),t("div",{className:"space-y-3 max-w-lg",children:[a("h3",{className:"text-xl font-semibold text-foreground",children:e}),a("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?a("div",{className:"w-full",children:l}):s?t($i,{onClick:s,size:"lg",className:"gap-2",children:[a(be,{className:"h-4 w-4"}),c]}):null]})}let lu=!1;function du(){if(lu||"undefined"==typeof document)return;lu=!0;for(const a of["https://fonts.googleapis.com","https://fonts.gstatic.com"])if(!document.querySelector(`link[href="${a}"]`)){const e=document.createElement("link");e.rel="preconnect",e.href=a,a.includes("gstatic")&&(e.crossOrigin="anonymous"),document.head.appendChild(e)}const e=["https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap","https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap"];for(const a of e)if(!document.querySelector(`link[href="${a}"]`)){const e=document.createElement("link");e.rel="stylesheet",e.href=a,document.head.appendChild(e)}}function cu({projectId:e,mode:a="auto"}){const{user:t,alias:r,isAuthenticated:n}=kl();m(()=>{if("undefined"!=typeof window&&"disabled"!==a&&e&&!vr()&&!window.__forlogicClarityOwned)if("function"!=typeof window.clarity)try{zc.init(e),window.__forlogicClarityOwned=!0,window.__forlogicClarityMode="owned"}catch(t){import.meta.env.DEV,window.__forlogicClarityMode="inactive"}else window.__forlogicClarityMode="piggyback"},[e,a]),m(()=>{if("undefined"!=typeof window&&"disabled"!==a&&n&&t&&"function"==typeof window.clarity)try{const e=t.email||t.identifier||"anonymous";zc.identify(e,void 0,"modules-menu",t.name||void 0),r&&zc.setTag("alias",r),"boolean"==typeof t.isSysAdmin&&zc.setTag("isSysAdmin",String(t.isSysAdmin))}catch(e){import.meta.env.DEV}},[t,r,n,a])}function uu({children:r,queryClient:n,moduleAlias:o,moduleAccessGuardProps:s,appTranslations:l,clarityProjectId:d,clarityMode:c="auto"}){du();const[u]=i.useState(()=>new et({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),m=n??u;i.useEffect(()=>{if(l)for(const[e,a]of Object.entries(l))vc(e,a)},[l]);const p={sourceModule:o,...s};return t(Dc,{children:[a(pu,{}),a(Ya,{i18n:e,children:a(at,{client:m,children:t(Cl,{children:[a(mu,{projectId:d,mode:c}),a(Nc,{children:a(Cc,{moduleAlias:o,children:a(ou,{...p,children:r})})})]})})})]})}function mu({projectId:e,mode:a}){return cu({projectId:e,mode:a}),null}function pu(){const e=Xs(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY),r=!!import.meta.env.VITE_SUPABASE_PK_OVERRIDE;if(!e||r||!import.meta.env.DEV)return null;const n={background:"rgba(0,0,0,.2)",padding:"1px 4px",borderRadius:4};return t("div",{style:{position:"fixed",top:0,left:0,right:0,zIndex:99999,background:"#dc2626",color:"#fff",padding:"8px 16px",fontSize:"13px",fontFamily:"Inter, system-ui, sans-serif",textAlign:"center",lineHeight:1.4},children:[a("strong",{children:"⚠️ Legacy Supabase Key Detectada"})," — O ",a("code",{style:n,children:"VITE_SUPABASE_PUBLISHABLE_KEY"})," contém uma anon key JWT legada. Adicione ",a("code",{style:n,children:'VITE_SUPABASE_PK_OVERRIDE="sb_publishable_..."'})," no .env para corrigir."]})}const hu=ft.Root,fu=n.forwardRef(({className:e,...t},r)=>a(ft.Item,{ref:r,className:Fi("border-b",e),...t}));fu.displayName="AccordionItem";const gu=n.forwardRef(({className:e,children:r,...n},i)=>a(ft.Header,{className:"flex",children:t(ft.Trigger,{ref:i,className:Fi("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[r,a(D,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));gu.displayName=ft.Trigger.displayName;const vu=n.forwardRef(({className:e,children:t,...r},n)=>a(ft.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:a("div",{className:Fi("pb-4 pt-0",e),children:t})}));vu.displayName=ft.Content.displayName;const bu=n.forwardRef(({className:e,...t},r)=>a(gt.Root,{ref:r,className:Fi("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));bu.displayName=gt.Root.displayName;const xu=n.forwardRef(({className:e,...t},r)=>a(gt.Image,{ref:r,className:Fi("aspect-square h-full w-full",e),...t}));xu.displayName=gt.Image.displayName;const yu=n.forwardRef(({className:e,...t},r)=>a(gt.Fallback,{ref:r,className:Fi("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));yu.displayName=gt.Fallback.displayName;const Nu=n.forwardRef(({...e},t)=>a("nav",{ref:t,"aria-label":"breadcrumb",...e}));Nu.displayName="Breadcrumb";const wu=n.forwardRef(({className:e,...t},r)=>a("ol",{ref:r,className:Fi("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",e),...t}));wu.displayName="BreadcrumbList";const _u=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Fi("inline-flex items-center gap-1.5",e),...t}));_u.displayName="BreadcrumbItem";const Cu=n.forwardRef(({asChild:e,className:t,...r},n)=>a(e?g:"a",{ref:n,className:Fi("transition-colors hover:text-foreground",t),...r}));Cu.displayName="BreadcrumbLink";const ku=n.forwardRef(({className:e,...t},r)=>a("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Fi("font-normal text-foreground",e),...t}));ku.displayName="BreadcrumbPage";const Su=({children:e,className:t,...r})=>a("li",{role:"presentation","aria-hidden":"true",className:Fi("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:e??a(U,{})});Su.displayName="BreadcrumbSeparator";const Au=({className:e,...r})=>t("span",{role:"presentation","aria-hidden":"true",className:Fi("flex h-9 w-9 items-center justify-center",e),...r,children:[a(xe,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Mais"})]});Au.displayName="BreadcrumbEllipsis";const Eu=v("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),Du=n.forwardRef(({className:e,orientation:t,...r},n)=>a("div",{ref:n,className:Fi(Eu({orientation:t}),e),...r}));function Pu({className:e,classNames:t,showOutsideDays:r=!0,...n}){return a(vt,{showOutsideDays:r,className:Fi("p-3 pointer-events-auto",e),locale:ci,classNames:{months:"relative flex flex-col gap-4 sm:flex-row",month:"flex flex-col gap-4",month_caption:"flex h-9 w-full items-center justify-center px-8",caption_label:"text-sm font-medium",nav:"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1 px-1",button_previous:Fi(Bi({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Fi(Bi({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),month_grid:"w-full border-collapse",weekdays:"flex",weekday:"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal w-9",week:"mt-2 flex w-full",day:"group/day relative h-9 w-9 select-none p-0 text-center text-sm [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md focus-within:relative focus-within:z-20",day_button:Fi(Bi({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:e})=>a("left"===e?oe:U,{className:"h-4 w-4"})},...n})}Du.displayName="ButtonGroup",Pu.displayName="Calendar";const Iu={Root:function({children:e,className:t}){return a("div",{className:Fi("space-y-4",t),children:e})},Item:function({children:e,onClick:t,className:r}){return a(Gi,{className:Fi("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:a(Xi,{className:"p-4",children:e})})},Field:function({label:e,value:r,className:n}){return t("div",{className:Fi("flex justify-between items-center text-sm",n),children:[t("span",{className:"text-muted-foreground font-medium",children:[e,":"]}),a("span",{className:"text-foreground",children:r})]})}};function Tu({date:e,onDateChange:r,placeholder:n,disabled:i=!1,className:o,disabledDates:s}){const{t:l}=Ga(),d=n??l("select_date");return t(bs,{children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",disabled:i,className:Fi("w-full justify-start text-left font-normal",!e&&"text-muted-foreground",o),children:[a(ye,{className:"mr-2 h-4 w-4"}),e?_(e,"d 'de' MMMM 'de' yyyy",{locale:ci}):a("span",{children:d})]})}),a(ys,{className:"w-auto p-0",align:"start",children:a(Pu,{mode:"single",selected:e,onSelect:r,disabled:s,initialFocus:!0,className:"pointer-events-auto"})})]})}const Ru=({shouldScaleBackground:e=!0,...t})=>a(bt.Root,{shouldScaleBackground:e,...t});Ru.displayName="Drawer";const Mu=bt.Trigger,Lu=bt.Portal,zu=bt.Close,Fu=n.forwardRef(({className:e,...t},r)=>a(bt.Overlay,{ref:r,className:Fi("fixed inset-0 z-50 bg-black/80",e),...t}));Fu.displayName=bt.Overlay.displayName;const Uu=n.forwardRef(({className:e,children:r,...n},i)=>t(Lu,{children:[a(Fu,{}),t(bt.Content,{ref:i,className:Fi("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",e),...n,children:[a("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));Uu.displayName="DrawerContent";const ju=({className:e,...t})=>a("div",{className:Fi("grid gap-1.5 p-4 text-center sm:text-left",e),...t});ju.displayName="DrawerHeader";const Ou=({className:e,...t})=>a("div",{className:Fi("mt-auto flex flex-col gap-2 p-4",e),...t});Ou.displayName="DrawerFooter";const Bu=n.forwardRef(({className:e,...t},r)=>a(bt.Title,{ref:r,className:Fi("text-lg font-semibold leading-none tracking-tight",e),...t}));Bu.displayName=bt.Title.displayName;const $u=n.forwardRef(({className:e,...t},r)=>a(bt.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));$u.displayName=bt.Description.displayName;const Vu={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))]"},qu={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Wu({children:e,cols:t="auto-fit",gap:r="md",className:n}){return a("div",{className:Fi("grid",Vu[t],qu[r],n),children:e})}const Hu=xt.Root,Gu=xt.Trigger,Ku=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,...n},i)=>a(xt.Content,{ref:i,align:t,sideOffset:r,className:Fi("z-50 w-64 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),...n}));Ku.displayName=xt.Content.displayName;const Yu=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-slot":"input-group",className:Fi("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",e),...t}));Yu.displayName="InputGroup";const Qu=v("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),Xu=n.forwardRef(({className:e,align:t,...r},n)=>a("div",{ref:n,"data-slot":"input-group-addon",className:Fi(Qu({align:t}),e),...r}));Xu.displayName="InputGroupAddon";const Ju=v("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),Zu=n.forwardRef(({className:e,size:t,variant:r="ghost",...n},i)=>a($i,{ref:i,"data-slot":"input-group-button",variant:r,className:Fi(Ju({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",e),...n}));Zu.displayName="InputGroupButton";const em=n.forwardRef(({className:e,...t},r)=>a(qi,{ref:r,"data-slot":"input-group-control",className:Fi("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));em.displayName="InputGroupInput";const am=n.forwardRef(({className:e,...t},r)=>a(Wo,{ref:r,"data-slot":"input-group-control",className:Fi("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));am.displayName="InputGroupTextarea";const tm=n.forwardRef(({className:e,...t},r)=>a("h1",{ref:r,className:Fi("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",e),...t}));tm.displayName="H1";const rm=n.forwardRef(({className:e,...t},r)=>a("h2",{ref:r,className:Fi("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",e),...t}));rm.displayName="H2";const nm=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Fi("scroll-m-20 text-2xl font-semibold tracking-tight",e),...t}));nm.displayName="H3";const im=n.forwardRef(({className:e,...t},r)=>a("h4",{ref:r,className:Fi("scroll-m-20 text-xl font-semibold tracking-tight",e),...t}));im.displayName="H4";const om=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("leading-7 [&:not(:first-child)]:mt-6",e),...t}));om.displayName="P";const sm=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("text-xl text-muted-foreground",e),...t}));sm.displayName="Lead";const lm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("text-lg font-semibold",e),...t}));lm.displayName="Large";const dm=n.forwardRef(({className:e,...t},r)=>a("small",{ref:r,className:Fi("text-sm font-medium leading-none",e),...t}));dm.displayName="Small";const cm=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));cm.displayName="Muted";const um=n.forwardRef(({className:e,...t},r)=>a("code",{ref:r,className:Fi("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",e),...t}));um.displayName="InlineCode";const mm=n.forwardRef(({className:e,...t},r)=>a("blockquote",{ref:r,className:Fi("mt-6 border-l-2 pl-6 italic",e),...t}));mm.displayName="Blockquote";const pm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Fi("my-6 ml-6 list-disc [&>li]:mt-2",e),...t}));pm.displayName="List";const hm=n.forwardRef(({className:e,children:r,...n},i)=>t(yt.Root,{ref:i,className:Fi("relative z-10 flex max-w-max flex-1 items-center justify-center",e),...n,children:[r,a(Nm,{})]}));hm.displayName=yt.Root.displayName;const fm=n.forwardRef(({className:e,...t},r)=>a(yt.List,{ref:r,className:Fi("group flex flex-1 list-none items-center justify-center space-x-1",e),...t}));fm.displayName=yt.List.displayName;const gm=yt.Item,vm=v("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),bm=n.forwardRef(({className:e,children:r,...n},i)=>t(yt.Trigger,{ref:i,className:Fi(vm(),"group",e),...n,children:[r," ",a(D,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));bm.displayName=yt.Trigger.displayName;const xm=n.forwardRef(({className:e,...t},r)=>a(yt.Content,{ref:r,className:Fi("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",e),...t}));xm.displayName=yt.Content.displayName;const ym=yt.Link,Nm=n.forwardRef(({className:e,...t},r)=>a("div",{className:Fi("absolute left-0 top-full flex justify-center"),children:a(yt.Viewport,{className:Fi("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",e),ref:r,...t})}));Nm.displayName=yt.Viewport.displayName;const wm=n.forwardRef(({className:e,...t},r)=>a(yt.Indicator,{ref:r,className:Fi("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",e),...t,children:a("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));function _m({items:e,maxItems:n=3,className:i}){const o=e.length>n?[e[0],...e.slice(-(n-1))]:e,s=e.length>n;return a(Nu,{className:i,children:a(wu,{children:o.map((e,n)=>{const i=s&&1===n;return t(_u,{children:[!(0===n)&&a(Su,{}),i&&t(r,{children:[a(Au,{}),a(Su,{})]}),e.isCurrentPage?a(ku,{children:e.label}):a(Cu,{asChild:!0,children:a(st,{to:e.href||"/",children:e.label})})]},e.label)})})})}function Cm(){const e=it();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const i=n===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:i?void 0:r,isCurrentPage:i})}),t})()}wm.displayName=yt.Indicator.displayName;const km=({className:e,...t})=>a("nav",{role:"navigation","aria-label":"pagination",className:Fi("mx-auto flex w-full justify-center",e),...t});km.displayName="Pagination";const Sm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Fi("flex flex-row items-center gap-1",e),...t}));Sm.displayName="PaginationContent";const Am=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Fi("",e),...t}));Am.displayName="PaginationItem";const Em=({className:e,isActive:t,size:r="icon",...n})=>a("a",{"aria-current":t?"page":void 0,className:Fi(Bi({variant:t?"outline":"ghost",size:r}),e),...n});Em.displayName="PaginationLink";const Dm=({className:r,...n})=>t(Em,{"aria-label":e.t("go_to_previous_page"),size:"default",className:Fi("gap-1 pl-2.5",r),...n,children:[a(oe,{className:"h-4 w-4"}),a("span",{children:"Previous"})]});Dm.displayName="PaginationPrevious";const Pm=({className:r,...n})=>t(Em,{"aria-label":e.t("go_to_next_page"),size:"default",className:Fi("gap-1 pr-2.5",r),...n,children:[a("span",{children:"Next"}),a(U,{className:"h-4 w-4"})]});Pm.displayName="PaginationNext";const Im=({className:e,...r})=>t("span",{"aria-hidden":!0,className:Fi("flex h-9 w-9 items-center justify-center",e),...r,children:[a(xe,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"More pages"})]});Im.displayName="PaginationEllipsis";const Tm=n.forwardRef(({className:e,value:t,...r},n)=>a(Nt.Root,{ref:n,className:Fi("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...r,children:a(Nt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Tm.displayName=Nt.Root.displayName;const Rm=n.forwardRef(({className:e,...t},r)=>a(wt.Root,{className:Fi("grid gap-2",e),...t,ref:r}));Rm.displayName=wt.Root.displayName;const Mm=n.forwardRef(({className:e,...t},r)=>a(wt.Item,{ref:r,className:Fi("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:a(wt.Indicator,{className:"flex items-center justify-center",children:a(j,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Mm.displayName=wt.Item.displayName;const Lm=({className:e,...t})=>a(_t.PanelGroup,{className:Fi("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),zm=_t.Panel,Fm=({withHandle:e,className:t,...r})=>a(_t.PanelResizeHandle,{className:Fi("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:e&&a("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:a(ae,{className:"h-2.5 w-2.5"})})}),Um=Ma.Root,jm=Ma.Trigger,Om=Ma.Close,Bm=Ma.Portal,$m=n.forwardRef(({className:e,...t},r)=>a(Ma.Overlay,{className:Fi("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:r}));$m.displayName=Ma.Overlay.displayName;const Vm=v("fixed z-50 flex flex-col bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),qm=n.forwardRef(({side:e="right",className:r,children:n,...i},o)=>t(Bm,{children:[a($m,{}),t(Ma.Content,{ref:o,className:Fi(Vm({side:e}),r),...i,children:[n,t(Ma.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[a(E,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]})]}));qm.displayName=Ma.Content.displayName;const Wm=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Fi("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(Zi,{className:"mt-2"})]});Wm.displayName="SheetHeader";const Hm=({className:e,...t})=>a("div",{className:Fi("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",e),...t});Hm.displayName="SheetBody";const Gm=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(Zi,{className:"mb-4"}),a("div",{className:Fi("flex flex-row justify-end gap-2",e),...n,children:r})]});Gm.displayName="SheetFooter";const Km=n.forwardRef(({className:e,...t},r)=>a(Ma.Title,{ref:r,className:Fi("text-lg font-semibold text-foreground",e),...t}));Km.displayName=Ma.Title.displayName;const Ym=n.forwardRef(({className:e,...t},r)=>a(Ma.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));Ym.displayName=Ma.Description.displayName;const Qm="sidebar:state",Xm=n.createContext(null);function Jm(){const e=n.useContext(Xm);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Zm=n.forwardRef(({defaultOpen:e=!0,open:t,onOpenChange:r,className:i,style:o,children:s,...l},d)=>{const c=Dl(),[u,m]=n.useState(!1),[p,h]=n.useState(()=>{if("undefined"!=typeof window){const a=localStorage.getItem(Qm);return null!==a?"true"===a:e}return e}),f=t??p,g=n.useCallback(e=>{const a="function"==typeof e?e(f):e;r?r(a):h(a),"undefined"!=typeof window&&localStorage.setItem(Qm,String(a))},[r,f]),v=n.useCallback(()=>c?m(e=>!e):g(e=>!e),[c,g,m]);n.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const b=f?"expanded":"collapsed",x=n.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:c,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[b,f,g,c,u,m,v]);return a(Xm.Provider,{value:x,children:a(ps,{delayDuration:0,children:a("div",{className:Fi("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",i),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...o},ref:d,...l,children:s})})})});Zm.displayName="SidebarProvider";const ep=n.forwardRef(({side:e="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:o,...s},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Jm();return"none"===n?a("div",{className:Fi("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...s,children:o}):d?a(Um,{open:u,onOpenChange:m,...s,children:t(qm,{"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:[a(Km,{className:"sr-only",children:"Menu de Navegação"}),a("div",{className:"flex h-full w-full flex-col",children:o})]})}):t("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?n:"","data-variant":r,"data-side":e,children:[a("div",{className:Fi("duration-200 relative h-[calc(100svh-var(--header-height,0px))] w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),a("div",{className:Fi("duration-200 fixed z-30 hidden w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","top-[var(--header-height,0px)] h-[calc(100svh-var(--header-height,0px))]","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"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",i),...s,children:a("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible 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:o})})]})});ep.displayName="Sidebar";const ap=n.forwardRef(({className:e,onClick:r,...n},i)=>{const{toggleSidebar:o}=Jm();return t($i,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Fi("h-7 w-7",e),onClick:e=>{r?.(e),o()},...n,children:[a(Ne,{}),a("span",{className:"sr-only",children:"Toggle Sidebar"})]})});ap.displayName="SidebarTrigger";const tp=n.forwardRef(({className:e,...t},r)=>{const{toggleSidebar:n}=Jm();return a("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Fi("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})});tp.displayName="SidebarRail";const rp=n.forwardRef(({className:e,...t},r)=>a("main",{ref:r,className:Fi("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}));rp.displayName="SidebarInset";const np=n.forwardRef(({className:e,...t},r)=>a(qi,{ref:r,"data-sidebar":"input",className:Fi("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",e),...t}));np.displayName="SidebarInput";const ip=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"header",className:Fi("flex flex-col gap-2 p-2",e),...t}));ip.displayName="SidebarHeader";const op=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"footer",className:Fi("flex flex-col gap-2 p-2",e),...t}));op.displayName="SidebarFooter";const sp=n.forwardRef(({className:e,...t},r)=>a(Zi,{ref:r,"data-sidebar":"separator",className:Fi("mx-2 w-auto bg-sidebar-border",e),...t}));sp.displayName="SidebarSeparator";const lp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"content",className:Fi("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t}));lp.displayName="SidebarContent";const dp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group",className:Fi("relative flex w-full min-w-0 flex-col p-2",e),...t}));dp.displayName="SidebarGroup";const cp=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"div",{ref:n,"data-sidebar":"group-label",className:Fi("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}));cp.displayName="SidebarGroupLabel";const up=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"button",{ref:n,"data-sidebar":"group-action",className:Fi("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}));up.displayName="SidebarGroupAction";const mp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group-content",className:Fi("w-full text-sm",e),...t}));mp.displayName="SidebarGroupContent";const pp=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu",className:Fi("flex w-full min-w-0 flex-col gap-1",e),...t}));pp.displayName="SidebarMenu";const hp=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,"data-sidebar":"menu-item",className:Fi("group/menu-item relative",e),...t}));hp.displayName="SidebarMenuItem";const fp=v("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-primary/10 data-[active=true]:font-medium data-[active=true]:text-primary 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"}}),gp=n.forwardRef(({asChild:e=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:o,className:s,...l},d)=>{const c=e?g:"button",{isMobile:u,state:m}=Jm(),p=a(c,{ref:d,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Fi(fp({variant:n,size:i}),s),...l});return o?("string"==typeof o&&(o={children:o}),t(hs,{children:[a(fs,{asChild:!0,children:p}),a(gs,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):p});gp.displayName="SidebarMenuButton";const vp=n.forwardRef(({className:e,asChild:t=!1,showOnHover:r=!1,...n},i)=>a(t?g:"button",{ref:i,"data-sidebar":"menu-action",className:Fi("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),...n}));vp.displayName="SidebarMenuAction";const bp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"menu-badge",className:Fi("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}));bp.displayName="SidebarMenuBadge";const xp=n.forwardRef(({className:e,showIcon:r=!1,...i},o)=>{const s=n.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return t("div",{ref:o,"data-sidebar":"menu-skeleton",className:Fi("rounded-md h-8 flex gap-2 px-2 items-center",e),...i,children:[r&&a("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),a("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":s}})]})});xp.displayName="SidebarMenuSkeleton";const yp=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu-sub",className:Fi("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}));yp.displayName="SidebarMenuSub";const Np=n.forwardRef(({...e},t)=>a("li",{ref:t,...e}));Np.displayName="SidebarMenuSubItem";const wp=n.forwardRef(({asChild:e=!1,size:t="md",isActive:r,className:n,...i},o)=>a(e?g:"a",{ref:o,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Fi("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"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i}));wp.displayName="SidebarMenuSubButton";const _p=n.forwardRef(({className:e,value:r,defaultValue:n,...i},o)=>{const s=r||n||[0];return t(Ct.Root,{ref:o,value:r,defaultValue:n,className:Fi("relative flex w-full touch-none select-none items-center",e),...i,children:[a(Ct.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:a(Ct.Range,{className:"absolute h-full bg-primary"})}),s.map((e,t)=>a(Ct.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"},t))]})});function Cp({children:e,className:t}){return a("div",{className:Fi("flex flex-col h-full",t),children:a(Dd,{className:"flex-1",children:a("div",{className:"space-y-6 p-6",children:e})})})}function kp({title:e,description:r,actions:n,className:i}){return t("div",{className:Fi("space-y-4",i),children:[t("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[t("div",{className:"space-y-1",children:[a("h2",{className:"text-2xl font-bold tracking-tight",children:e}),r&&a("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&a("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),a(Zi,{})]})}function Sp({children:e,className:t}){return a("div",{className:Fi("space-y-6",t),children:e})}_p.displayName=Ct.Root.displayName;const Ap=kt.Menu,Ep=kt.Group,Dp=kt.Portal,Pp=kt.Sub,Ip=kt.RadioGroup,Tp=n.forwardRef(({className:e,...t},r)=>a(kt.Root,{ref:r,className:Fi("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",e),...t}));Tp.displayName=kt.Root.displayName;const Rp=n.forwardRef(({className:e,...t},r)=>a(kt.Trigger,{ref:r,className:Fi("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",e),...t}));Rp.displayName=kt.Trigger.displayName;const Mp=n.forwardRef(({className:e,inset:r,children:n,...i},o)=>t(kt.SubTrigger,{ref:o,className:Fi("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",e),...i,children:[n,a(U,{className:"ml-auto h-4 w-4"})]}));Mp.displayName=kt.SubTrigger.displayName;const Lp=n.forwardRef(({className:e,...t},r)=>a(kt.SubContent,{ref:r,className:Fi("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));Lp.displayName=kt.SubContent.displayName;const zp=n.forwardRef(({className:e,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},o)=>a(kt.Portal,{children:a(kt.Content,{ref:o,align:t,alignOffset:r,sideOffset:n,className:Fi("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...i})}));zp.displayName=kt.Content.displayName;const Fp=n.forwardRef(({className:e,inset:t,...r},n)=>a(kt.Item,{ref:n,className:Fi("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));Fp.displayName=kt.Item.displayName;const Up=n.forwardRef(({className:e,children:r,checked:n,...i},o)=>t(kt.CheckboxItem,{ref:o,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...i,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(kt.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),r]}));Up.displayName=kt.CheckboxItem.displayName;const jp=n.forwardRef(({className:e,children:r,...n},i)=>t(kt.RadioItem,{ref:i,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(kt.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));jp.displayName=kt.RadioItem.displayName;const Op=n.forwardRef(({className:e,inset:t,...r},n)=>a(kt.Label,{ref:n,className:Fi("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));Op.displayName=kt.Label.displayName;const Bp=n.forwardRef(({className:e,...t},r)=>a(kt.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-muted",e),...t}));Bp.displayName=kt.Separator.displayName;const $p=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});$p.displayname="MenubarShortcut";const Vp={light:"",dark:".dark"},qp=n.createContext(null);function Wp(){const e=n.useContext(qp);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Hp=n.forwardRef(({id:e,className:r,children:i,config:o,...s},l)=>{const d=n.useId(),c=`chart-${e||d.replace(/:/g,"")}`;return a(qp.Provider,{value:{config:o},children:t("div",{"data-chart":c,ref:l,className:Fi("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",r),...s,children:[a(Gp,{id:c,config:o}),a(St.ResponsiveContainer,{children:i})]})})});Hp.displayName="Chart";const Gp=({id:e,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?a("style",{dangerouslySetInnerHTML:{__html:Object.entries(Vp).map(([a,t])=>`\n${t} [data-chart=${e}] {\n${r.map(([e,t])=>{const r=t.theme?.[a]||t.color;return r?` --color-${e}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},Kp=St.Tooltip,Yp=n.forwardRef(({active:e,payload:i,className:o,indicator:s="dot",hideLabel:l=!1,hideIndicator:d=!1,label:c,labelFormatter:u,labelClassName:m,formatter:p,color:h,nameKey:f,labelKey:g},v)=>{const{config:b}=Wp(),x=n.useMemo(()=>{if(l||!i?.length)return null;const[e]=i,t=Jp(b,e,`${g||e?.dataKey||e?.name||"value"}`),r=g||"string"!=typeof c?t?.label:b[c]?.label||c;return u?a("div",{className:Fi("font-medium",m),children:u(r,i)}):r?a("div",{className:Fi("font-medium",m),children:r}):null},[c,u,i,l,m,b,g]);if(!e||!i?.length)return null;const y=1===i.length&&"dot"!==s;return t("div",{ref:v,className:Fi("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",o),children:[y?null:x,a("div",{className:"grid gap-1.5",children:i.map((e,n)=>{const i=`${f||e.name||e.dataKey||"value"}`,o=Jp(b,e,i),l=h||e.payload?.fill||e.color;return a("div",{className:Fi("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===s&&"items-center"),children:p&&void 0!==e?.value&&e.name?p(e.value,e.name,e,n,e.payload):t(r,{children:[o?.icon?a(o.icon,{}):!d&&a("div",{className:Fi("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===s,"w-1":"line"===s,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===s,"my-0.5":y&&"dashed"===s}),style:{"--color-bg":l,"--color-border":l}}),t("div",{className:Fi("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[t("div",{className:"grid gap-1.5",children:[y?x:null,a("span",{className:"text-muted-foreground",children:o?.label||e.name})]}),void 0!==e.value&&a("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof e.value?e.value.toLocaleString():e.value})]})]})},e.dataKey||n)})})]})});Yp.displayName="ChartTooltip";const Qp=St.Legend,Xp=n.forwardRef(({className:e,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:o},s)=>{const{config:l}=Wp();return n?.length?a("div",{ref:s,className:Fi("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",e),children:n.map(e=>{const n=`${o||e.dataKey||"value"}`,i=Jp(l,e,n);return t("div",{className:Fi("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[i?.icon&&!r?a(i.icon,{}):a("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:e.color}}),i?.label]},e.value)})}):null});function Jp(e,a,t){if("object"!=typeof a||null===a)return;const r="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let n=t;return t in a&&"string"==typeof a[t]?n=a[t]:r&&t in r&&"string"==typeof r[t]&&(n=r[t]),n in e?e[n]:e[t]}Xp.displayName="ChartLegend";const Zp=({onClick:e,isActive:t,disabled:r,children:n,title:i})=>a("button",{type:"button",onClick:e,disabled:r,title:i,className:Fi("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),eh=()=>a("div",{className:"w-px h-5 bg-border mx-1"}),ah=({value:r,onChange:i,disabled:s,placeholder:d=e.t("write_content_here"),minHeight:c="300px",showModeToggle:u=!0,showVariableHint:m=!0,className:p})=>{const{t:h}=Ga(),[f,g]=o("visual"),v=Vt({extensions:[Wt.configure({heading:{levels:[1,2,3]}}),Ht,Gt.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Kt,Yt,Qt.configure({multicolor:!0})],content:r||"",editable:!s,onUpdate:({editor:e})=>{i(e.getHTML())}});n.useEffect(()=>{v&&r!==v.getHTML()&&v.commands.setContent(r||"")},[r,v]);const b=l(()=>{if(!v)return;const e=v.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?v.chain().focus().extendMarkRange("link").setLink({href:a}).run():v.chain().focus().extendMarkRange("link").unsetLink().run())},[v]);return v?t("div",{className:Fi("space-y-2",p),children:[u&&t("div",{className:"flex justify-between items-center",children:[t("div",{className:"flex gap-1",children:[t($i,{type:"button",size:"sm",variant:"visual"===f?"default":"outline",onClick:()=>g("visual"),disabled:s,children:[a(we,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),t($i,{type:"button",size:"sm",variant:"code"===f?"default":"outline",onClick:()=>g("code"),disabled:s,children:[a(_e,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),t($i,{type:"button",size:"sm",variant:"preview"===f?"default":"outline",onClick:()=>g("preview"),disabled:s,children:[a(Ce,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),m&&t("p",{className:"text-xs text-muted-foreground",children:["Use ",a("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===f&&t("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||v?.commands.focus()},children:[t("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[a(Zp,{onClick:()=>v.chain().focus().toggleHeading({level:1}).run(),isActive:v.isActive("heading",{level:1}),disabled:s,title:e.t("heading_1"),children:a(ke,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleHeading({level:2}).run(),isActive:v.isActive("heading",{level:2}),disabled:s,title:e.t("heading_2"),children:a(Se,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleHeading({level:3}).run(),isActive:v.isActive("heading",{level:3}),disabled:s,title:e.t("heading_3"),children:a(Ae,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().toggleBold().run(),isActive:v.isActive("bold"),disabled:s,title:e.t("bold"),children:a(Ee,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleItalic().run(),isActive:v.isActive("italic"),disabled:s,title:e.t("italic"),children:a(De,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleUnderline().run(),isActive:v.isActive("underline"),disabled:s,title:"Sublinhado",children:a(Pe,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleStrike().run(),isActive:v.isActive("strike"),disabled:s,title:"Riscado",children:a(Ie,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().toggleBulletList().run(),isActive:v.isActive("bulletList"),disabled:s,title:"Lista",children:a(J,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleOrderedList().run(),isActive:v.isActive("orderedList"),disabled:s,title:h("ordered_list"),children:a(Te,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().toggleHighlight().run(),isActive:v.isActive("highlight"),disabled:s,title:"Destacar",children:a(Re,{className:"h-4 w-4"})}),a(Zp,{onClick:b,isActive:v.isActive("link"),disabled:s,title:"Link",children:a(Me,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().unsetAllMarks().clearNodes().run(),disabled:s,title:h("clear_formatting"),children:a(Le,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().undo().run(),disabled:s||!v.can().undo(),title:"Desfazer",children:a(ze,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().redo().run(),disabled:s||!v.can().redo(),title:"Refazer",children:a(Fe,{className:"h-4 w-4"})})]}),a(qt,{editor:v,className:Fi("prose prose-sm max-w-none focus:outline-none","[&_.ProseMirror]:p-4","[&_.ProseMirror]:min-h-full","[&_.ProseMirror]:cursor-text","[&_.ProseMirror]:outline-none","[&_.ProseMirror_p.is-editor-empty:first-child::before]:text-muted-foreground","[&_.ProseMirror_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]","[&_.ProseMirror_p.is-editor-empty:first-child::before]:float-left","[&_.ProseMirror_p.is-editor-empty:first-child::before]:h-0","[&_.ProseMirror_p.is-editor-empty:first-child::before]:pointer-events-none"),style:{minHeight:c}})]}),"code"===f&&a("textarea",{value:r||"",onChange:e=>i(e.target.value),disabled:s,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:c},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===f&&a("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:c},children:a("div",{className:"bg-background shadow-sm rounded border p-4",children:a("div",{dangerouslySetInnerHTML:{__html:r||`<p class="text-muted-foreground">${d}</p>`}})})})]}):null};function th({image:e,title:t,className:r}){return a("div",{className:Fi("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:e?a("img",{src:e,alt:t,className:"w-full h-full object-cover"}):a("div",{className:"flex items-center justify-center h-full",children:a(Ue,{className:"w-16 h-16 text-muted-foreground"})})})}function rh({steps:e,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:o}){const{t:s}=Ga(),l=e.length,d=(r+1)/l*100;return t("div",{className:Fi("flex items-center gap-3",o),children:[t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",l,a(D,{className:"h-3 w-3 ml-1"})]})}),a(os,{align:"start",children:e.map((e,a)=>t(ss,{onClick:()=>n(a),className:Fi(a===r&&"bg-accent"),children:[a+1,". ",e.title]},e.id))})]}),a(Tm,{value:d,className:"w-32 h-2"})]})}function nh({currentStepIndex:e,totalSteps:r,onBack:n,onNext:i,onComplete:o,backButtonText:s,continueButtonText:l,finishButtonText:d,className:c}){const{t:u}=Ga(),m=0===e,p=e===r-1;return t("div",{className:Fi("flex items-center gap-2",c),children:[!m&&t($i,{variant:"outline",onClick:n,size:"sm",children:[a(je,{className:"h-4 w-4 mr-2"}),s]}),t($i,{onClick:p?o:i,size:"sm",children:[p?d:l,!p&&a(Oe,{className:"h-4 w-4 ml-2"})]})]})}const ih=n.forwardRef(({open:r,onOpenChange:i,steps:o,onComplete:s,onStepChange:l,continueButtonText:d="Continuar",backButtonText:c="Voltar",finishButtonText:u="Concluir",stepLabel:m=e.t("approval_step_label"),size:p="md",showProgressIndicator:h=!0,currentStepIndex:f,onCurrentStepChange:g,className:v},b)=>{const[x,y]=n.useState(0),N=void 0!==f,w=N?f:x,_=n.useCallback(e=>{N?g?.(e):y(e),l?.(e)},[N,g,l]);n.useEffect(()=>{r||N||y(0)},[r,N]);const C=o[w],k=o.length;return C?a(mo,{open:r,onOpenChange:i,children:t(bo,{ref:b,size:p,variant:"informative",className:Fi("p-0 gap-0 overflow-hidden",v),children:[t(fo,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[a(E,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Fechar"})]}),a("div",{className:"flex-1 min-h-0 overflow-auto",children:t("div",{className:"p-6 space-y-4",children:[a(th,{image:C.image,title:C.title}),a(wo,{className:"text-xl font-semibold",children:C.title}),a(_o,{className:"text-muted-foreground",children:C.description})]})}),t("div",{className:"flex-shrink-0",children:[a(Zi,{}),t("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?a(rh,{steps:o,currentStepIndex:w,onStepSelect:e=>{_(e)},stepLabel:m}):a("div",{}),a(nh,{currentStepIndex:w,totalSteps:k,onBack:()=>{w>0&&_(w-1)},onNext:()=>{w<k-1&&_(w+1)},onComplete:()=>{s?.(),i(!1)},backButtonText:c,continueButtonText:d,finishButtonText:u})]})]})]})}):null});function oh({label:e,onClick:r,icon:n,actions:i=[],variant:o="default",size:s="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const{t:m}=Ga(),p=l||d;if(!(i.length>0))return t($i,{variant:o,size:s,disabled:p,onClick:r,className:u,children:[d?a(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?a(n,{className:"mr-2 h-4 w-4"}):null,e]});return t("div",{className:Fi("inline-flex rounded-md shadow-sm",u),children:[t($i,{variant:o,size:s,disabled:p,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[d?a(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?a(n,{className:"mr-2 h-4 w-4"}):null,e]}),t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:o,size:s,disabled:p,className:Fi("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[s]),"aria-label":m("more_options"),children:a(D,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[s]})})}),a(os,{align:c,className:"min-w-[160px]",children:i.map(e=>{const r=e.icon;return t(ss,{onClick:e.onClick,disabled:e.disabled,className:Fi("destructive"===e.variant&&"text-destructive focus:text-destructive"),children:[r&&a(r,{className:"mr-2 h-4 w-4"}),e.label]},e.id)})})]})]})}var sh,lh;ih.displayName="OnboardingDialog",(lh=sh||(sh={})).CSV="csv",lh.PDF="pdf",lh.XLSX="xlsx",lh.PNG="png",lh.JPEG="jpeg",lh.SVG="svg";const dh=[{value:sh.CSV,label:"CSV",icon:a(Be,{className:"h-5 w-5"})},{value:sh.PDF,label:"PDF",icon:a(Be,{className:"h-5 w-5"})},{value:sh.XLSX,label:"XLSX",icon:a($e,{className:"h-5 w-5"})}],ch=[{value:sh.PNG,label:"PNG",icon:a(Ve,{className:"h-5 w-5"})},{value:sh.JPEG,label:"JPEG",icon:a(qe,{className:"h-5 w-5"})},{value:sh.SVG,label:"SVG",icon:a(qe,{className:"h-5 w-5"})},{value:sh.PDF,label:"PDF",icon:a(Be,{className:"h-5 w-5"})}];function uh({open:e,onOpenChange:r,onExport:n,mode:i="table",options:s,title:l,description:d,cancelLabel:c="Cancelar",exportLabel:u="Exportar"}){const{t:m}=Ga(),[p,h]=o(""),f=s??("chart"===i?ch:dh),g=l??m("chart"===i?"dashboard_export_chart":"dashboard_export_table"),v=d??m("select_file_format"),b=e=>{e||h(""),r(e)};return a(mo,{open:e,onOpenChange:b,children:t(bo,{className:"sm:max-w-md",variant:"form",isDirty:!!p,children:[a(xo,{children:a(wo,{children:g})}),t("div",{className:"py-4",children:[a("p",{className:"text-sm text-muted-foreground mb-4",children:v}),a(Rm,{value:p,onValueChange:h,className:"gap-3",children:f.map(e=>t("div",{className:"flex items-center space-x-3",children:[a(Mm,{value:e.value,id:`export-${e.value}`}),t(Hi,{htmlFor:`export-${e.value}`,className:Fi("flex items-center gap-2 cursor-pointer font-normal",p===e.value&&"font-medium"),children:[e.icon,e.label]})]},e.value))})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>b(!1),children:c}),a($i,{onClick:()=>{p&&(n(p),r(!1),h(""))},disabled:!p,children:u})]})]})})}const mh=f(({value:e,onChange:r,onTimeChange:i,label:o,error:s,format:d="24h",className:c,id:u,...m},p)=>{const h=u??n.useId(),f=l(e=>{const a=e.target.value;r?.(a),i?.(a)},[r,i]),g=l(e=>{["0","1","2","3","4","5","6","7","8","9","Backspace","Tab",":","ArrowLeft","ArrowRight","Delete"].includes(e.key)||e.preventDefault()},[]);return t("div",{className:Fi("grid gap-1.5",c),children:[o&&a(Hi,{htmlFor:h,children:o}),t("div",{className:"relative",children:[a(qi,{ref:p,id:h,type:"time",value:e??"",onChange:f,onKeyDown:g,min:"00:00",max:"23:59",step:60,className:Fi("pr-9",s&&"border-destructive focus-visible:ring-destructive"),...m}),a(We,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),s&&a("p",{className:"text-sm text-destructive",children:s})]})});function ph({open:r,onOpenChange:n,onConfirm:i,onGenerateCode:s,mode:d="code",email:c,maxLength:u=8,title:m=e.t("electronic_signature"),description:p,confirmLabel:h=e.t("conclude"),cancelLabel:f=e.t("cancel"),resendLabel:g=e.t("resend_code"),errorMessage:v}){const b="password"===d,x=b?e.t("esign_password_description"):e.t("esign_code_description"),y=p??x,[N,w]=o(""),[_,C]=o(!1),[k,S]=o(!1),[A,E]=o(null),D=l(async()=>{if(N.trim()){C(!0),E(null);try{await i(N)?(w(""),n(!1)):E(v??(b?e.t("esign_invalid_password"):e.t("esign_invalid_code")))}catch{E(v??(b?e.t("esign_password_error"):e.t("esign_code_error")))}finally{C(!1)}}},[N,i,n,v,b]),P=l(async()=>{if(s){S(!0),E(null);try{await s()}catch{E(e.t("esign_resend_error"))}finally{S(!1)}}},[s]),I=e=>{e||(w(""),E(null)),n(e)},T=b?He:Ge,R=b?"Senha":e.t("verification_code"),M=b?e.t("enter_password"):e.t("enter_code");return a(mo,{open:r,onOpenChange:I,children:t(bo,{className:"sm:max-w-md",variant:"form",isDirty:!!N,children:[a(xo,{children:t(wo,{className:"flex items-center gap-2",children:[a(T,{className:"h-5 w-5 text-primary"}),m]})}),t("div",{className:"py-4 space-y-4",children:[a("p",{className:"text-sm text-muted-foreground",children:y}),!b&&c&&t("div",{className:"flex items-center gap-2 text-sm bg-muted/50 rounded-md px-3 py-2",children:[a(Ke,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-muted-foreground",children:"Enviado para:"}),a("span",{className:"font-medium",children:c})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"signature-input",children:R}),a(qi,{id:"signature-input",type:b?"password":"text",value:N,onChange:e=>w(e.target.value),onKeyDown:e=>{"Enter"===e.key&&N.trim()&&(e.preventDefault(),D())},maxLength:b?void 0:u,placeholder:M,autoFocus:!0,className:Fi(A&&"border-destructive focus-visible:ring-destructive")}),A&&a("p",{className:"text-sm text-destructive",children:A})]}),!b&&t($i,{variant:"ghost",size:"sm",onClick:P,disabled:k,className:"text-primary",children:[a(ue,{className:Fi("h-4 w-4 mr-1",k&&"animate-spin")}),g]})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>I(!1),disabled:_,children:f}),a($i,{onClick:D,disabled:!N.trim()||_,children:_?"Validando...":h})]})]})})}function hh({currentStep:e,totalSteps:r,onStepChange:i,stepLabels:o,canGoToStep:s,className:l,progressWidth:d="w-32"}){n.useEffect(()=>{process.env.NODE_ENV},[]);const c=Array.from({length:r},(e,a)=>a+1),u=a=>!(a<=e)&&(!!s&&!s(a));return t("div",{className:Fi("flex items-center gap-3",l),children:[t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",e,"/",r,a(D,{className:"h-3 w-3 ml-1"})]})}),a(os,{align:"start",children:c.map(r=>t(ss,{onClick:()=>{var a;(a=r)<e?i(a):s&&!s(a)||i(a)},disabled:u(r),className:Fi("cursor-pointer",r===e&&"bg-muted font-medium",u(r)&&"opacity-50 cursor-not-allowed"),children:[t("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),o?.[r-1]||`Etapa ${r}`,r===e&&a(I,{className:"h-4 w-4 ml-auto"})]},r))})]}),a(Tm,{value:e/r*100,className:Fi("h-2",d)})]})}function fh({open:r,onOpenChange:n,currentStep:i,onStepChange:o,steps:s,canGoToStep:l,children:d,title:c,description:u,onSave:m,saveLabel:p=e.t("save"),nextLabel:h=e.t("next"),backLabel:f=e.t("back"),variant:g="form",isDirty:v,size:b="lg",unsavedChangesTitle:x,unsavedChangesDescription:y,cancelText:N,leaveWithoutSavingText:w,className:_,disableNext:C,hideNavigation:k,footerLeft:S}){const{t:A}=Ga(),E=s.length,D=i>=E,P=i<=1;return a(mo,{open:r,onOpenChange:n,children:t(bo,{size:b,variant:g,isDirty:v,unsavedChangesTitle:x,unsavedChangesDescription:y,cancelText:N,leaveWithoutSavingText:w,className:Fi("!p-0 !border-l-0 flex-row overflow-hidden",_),children:[t("div",{className:"hidden sm:flex w-56 flex-shrink-0 flex-col bg-primary text-primary-foreground p-6 rounded-l-lg",children:[a("h3",{className:"text-sm font-medium opacity-80 mb-6",children:"Etapas"}),a("nav",{className:"flex flex-col gap-1 flex-1",children:s.map((e,r)=>{const n=r+1,s=n===i,d=(e=>e<i)(n),c=(u=n)<=i||!l||l(u);var u;return t("button",{type:"button",onClick:()=>(e=>{e!==i&&(e<i?o(e):l&&!l(e)||o(e))})(n),disabled:!c,className:Fi("flex items-center gap-2 py-3 px-2 rounded-md text-left transition-colors text-xs",s&&"bg-primary-foreground/20 font-semibold",!s&&c&&"hover:bg-primary-foreground/10 cursor-pointer",!c&&"opacity-40 cursor-not-allowed"),children:[a("span",{className:Fi("flex items-center justify-center h-7 w-7 rounded-full text-xs font-bold flex-shrink-0 transition-colors",s&&"bg-primary-foreground text-primary",d&&!s&&"bg-primary-foreground/30 text-primary-foreground",!s&&!d&&"border-2 border-primary-foreground/40 text-primary-foreground/60"),children:d&&!s?a(I,{className:"h-3.5 w-3.5"}):n}),a("span",{className:Fi("line-clamp-2",s&&"text-primary-foreground",!s&&"text-primary-foreground/70"),children:e})]},n)})})]}),t("div",{className:"flex flex-col flex-1 min-w-0",children:[t(xo,{className:"p-6 pb-0",children:[t("p",{className:"text-xs text-muted-foreground sm:hidden mb-1",children:["Etapa ",i," de ",E]}),a(wo,{children:c}),u&&a("p",{className:"text-sm text-muted-foreground mt-1",children:u})]}),a(yo,{className:"px-6",children:d}),!k&&a(No,{className:"px-6 pb-6",children:t("div",{className:"flex items-center justify-between w-full",children:[a("div",{className:"flex items-center gap-2",children:S}),t("div",{className:"flex items-center gap-2",children:[!P&&a($i,{variant:"outline",onClick:()=>o(i-1),children:f}),a($i,D?{onClick:m,disabled:C,children:p}:{onClick:()=>o(i+1),disabled:C,children:h})]})]})})]})]})})}function gh(e){const a=Ys.getAccessToken(),t={"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{},"un-alias":e};if(a)try{const e=JSON.parse(atob(a.split(".")[1]));e.sub&&(t["x-waf-rate"]=btoa(e.sub))}catch{}return t}async function vh(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await sl.handleApiError({status:401})){const n={...a,headers:gh(t)};r=await fetch(e,n)}}return r}function bh(e){const[a,t]=o([]),[r,n]=o(0),[i,s]=o(!1);m(()=>{if(!e)return;let a=!1;const r=`${xr().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){s(!0);try{const i=gh(e),o=await vh(r,{method:"GET",headers:i},e);if(!o.ok)return;const s=await o.json();!a&&s.data?.[0]&&(t(s.data[0].updates??[]),n(s.data[0].valueBadge??0))}catch(i){}finally{a||s(!1)}}(),()=>{a=!0}},[e]);const d=l(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${xr().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=gh(e),r=JSON.stringify({id:t,idUpdateType:3});await vh(i,{method:"POST",headers:a,body:r},e)}catch(o){}},[e,r,a]);return{updates:a,badgeCount:r,loading:i,markAsVisualized:d}}mh.displayName="Timepicker";const xh=i.forwardRef(({updates:r,badgeCount:n,onOpen:i,onViewAll:o},s)=>{const l=void 0===r,d=kl(),c=d?.alias??null,u=bh(l?c:null),m=l?u.updates??[]:r,p=l?u.badgeCount??0:n??0,h=i??(l?u.markAsVisualized:void 0),f=o??(l&&c?()=>{const e=`https://apps4.qualiex.com/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return t(bs,{children:[a(xs,{asChild:!0,children:t($i,{ref:s,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:h,title:e.t("updates"),children:[a(Ye,{className:"h-7 w-7"}),p>0&&a("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground",children:p>99?"99+":p})]})}),t(ys,{align:"end",className:"w-80 p-0",children:[a("div",{className:"border-b border-border px-4 py-3",children:a("h4",{className:"text-sm font-semibold text-foreground",children:"Atualizações"})}),a("div",{className:"max-h-72 overflow-y-auto",children:m.length>0?a("ul",{className:"divide-y divide-border",children:m.map(e=>t("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:f,children:[a("p",{className:"text-sm font-medium text-foreground",children:e.title}),a("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:e.text})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-8 px-4 text-center",children:[a(Ye,{className:"h-8 w-8 text-muted-foreground mb-2"}),a("p",{className:"text-sm text-muted-foreground",children:"Nenhum café quentinho, ou melhor, atualização quentinha no momento!"})]})}),a("div",{className:"border-t border-border px-4 py-2",children:t($i,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:f,children:["Ver todas as atualizações",a(Oe,{className:"h-[18px] w-[18px]"})]})})]})]})});var yh,Nh,wh,_h;xh.displayName="UpdatesNotification",(Nh=yh||(yh={}))[Nh.none=0]="none",Nh[Nh.image=1]="image",Nh[Nh.video=2]="video",Nh[Nh.audio=3]="audio",Nh[Nh.wopi=4]="wopi",Nh[Nh.onlineEditor=5]="onlineEditor",Nh[Nh.report=6]="report",(_h=wh||(wh={}))[_h.SimplePrint=0]="SimplePrint",_h[_h.ManagedCopy=1]="ManagedCopy",_h[_h.NonManagedCopy=2]="NonManagedCopy";const Ch={".jpg":yh.image,".jpeg":yh.image,".png":yh.image,".bmp":yh.image,".gif":yh.image,".svg":yh.image,".webp":yh.image,".wav":yh.audio,".mp3":yh.audio,".mp4":yh.video,".webm":yh.video,".ogg":yh.video,".pdf":yh.wopi,".ods":yh.wopi,".xls":yh.wopi,".xlsb":yh.wopi,".xlsm":yh.wopi,".xlsx":yh.wopi,".doc":yh.wopi,".docm":yh.wopi,".docx":yh.wopi,".dot":yh.wopi,".dotm":yh.wopi,".dotx":yh.wopi,".odt":yh.wopi,".odp":yh.wopi,".pot":yh.wopi,".potm":yh.wopi,".potx":yh.wopi,".pps":yh.wopi,".ppsm":yh.wopi,".ppsx":yh.wopi,".ppt":yh.wopi,".pptm":yh.wopi,".pptx":yh.wopi,".gdocs":yh.onlineEditor,".gsheets":yh.onlineEditor};function kh(e){const{t:a}=Ga();return e?Ch[e.toLowerCase()]??yh.none:yh.none}function Sh(e){const{t:a}=Ga();return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"}const Ah={".pdf":"wv/wordviewerframe.aspx?PdfMode=1&",".xls":"x/_layouts/xlviewerinternal.aspx?",".xlsb":"x/_layouts/xlviewerinternal.aspx?",".xlsm":"x/_layouts/xlviewerinternal.aspx?",".xlsx":"x/_layouts/xlviewerinternal.aspx?",".ods":"x/_layouts/xlviewerinternal.aspx?",".doc":"wv/wordviewerframe.aspx?",".docm":"wv/wordviewerframe.aspx?",".docx":"wv/wordviewerframe.aspx?",".dot":"wv/wordviewerframe.aspx?",".dotm":"wv/wordviewerframe.aspx?",".dotx":"wv/wordviewerframe.aspx?",".odt":"wv/wordviewerframe.aspx?",".ppt":"p/PowerPointFrame.aspx?",".pptm":"p/PowerPointFrame.aspx?",".pptx":"p/PowerPointFrame.aspx?",".pot":"p/PowerPointFrame.aspx?",".potm":"p/PowerPointFrame.aspx?",".potx":"p/PowerPointFrame.aspx?",".pps":"p/PowerPointFrame.aspx?",".ppsm":"p/PowerPointFrame.aspx?",".ppsx":"p/PowerPointFrame.aspx?",".odp":"p/PowerPointFrame.aspx?"};function Eh(e){const{t:a}=Ga();return Ah[e?.toLowerCase()]||""}function Dh(e){const{t:a}=Ga(),{viewerUrl:t,wopiUrl:r,fileId:n,token:i,extension:o,language:s="pt-br"}=e,l=Eh(o);if(!l)return null;return`${t}${l}ui=${s}&rs=${s}&access_token=${i}&WOPISrc=${encodeURIComponent(`${r}${n}`)}`}function Ph({open:e,onOpenChange:n,template:i,viewerType:o,isLoading:s=!1,enableDownload:d=!0,onDownload:c,isDownloading:p=!1,enableFavorite:h=!1,isFavorite:f=!1,onFavorite:g,isFavoriting:v=!1,enableConfirmReading:b=!1,readingConfirmationDate:x,onConfirmReading:y,isConfirmingReading:N=!1,readingConfirmationTimeRemaining:w,onIframeLoad:_,className:C}){const{t:k}=Ga(),S=u(null),A=o??kh(i.extension),D=p||N||v,P=i.code?`${i.code} – ${i.name}`:i.name,I=l(()=>{S.current&&_&&_(S.current)},[_]);return m(()=>{if(!e)return;const a=e=>{"Escape"===e.key&&n(!1)};return window.addEventListener("keyup",a),()=>window.removeEventListener("keyup",a)},[e,n]),a(mo,{open:e,onOpenChange:n,children:t(bo,{className:Fi("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(A===yh.wopi||A===yh.report)&&"w-[90vw]",C),children:[t("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[a("h2",s?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-200px)]",children:P}),t("div",{className:"flex items-center gap-1 ml-4 z-20",children:[!s&&t(r,{children:[(b||x)&&a(r,{children:x?t("div",{className:"flex flex-col mr-2.5",children:[t("span",{className:"text-sm font-medium flex items-center gap-1 text-foreground",children:[a(Qe,{className:"h-4 w-4"}),"Leitura confirmada"]}),a("span",{className:"text-xs text-muted-foreground ml-5",children:x.toLocaleDateString()})]}):null!=w&&w>0?t("div",{className:"flex items-center gap-1 mr-2.5 text-sm text-muted-foreground",children:[a("span",{children:k("terms_confirmation_available")}),a("span",{className:"font-medium min-w-[72px]",children:Ih(w)}),a("span",{children:"segundos"})]}):t($i,{variant:"default",size:"sm",disabled:D,onClick:()=>y?.(),className:"mr-2.5",children:[a(Ge,{className:"h-4 w-4 mr-1"}),N?"Confirmando...":k("terms_confirm_reading")]})}),A!==yh.none&&h&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>g?.(f),children:a(Xe,{className:Fi("h-4 w-4",f&&"fill-accent text-accent")})})}),a(gs,{children:f?"Desfavoritar":"Favoritar"})]}),A!==yh.none&&d&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>c?.(),children:a(Je,{className:"h-4 w-4"})})}),a(gs,{children:"Download"})]})]}),t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>n(!1),children:a(E,{className:"h-4 w-4"})})}),a(gs,{children:"Fechar"})]})]})]}),a("div",{className:Fi("flex flex-col items-center justify-center min-h-[160px] w-full",s&&"relative -top-5",A===yh.none&&"min-h-[124px]",A===yh.image&&"max-h-[85vh]",(A===yh.wopi||A===yh.report)&&"min-w-[77vw] min-h-[80vh]"),children:s?a(Yo,{className:"h-14 w-14"}):t(r,{children:[(A===yh.none||!i.url)&&t("div",{className:"text-center",children:[a("p",{className:"text-base text-foreground mb-1",children:"Extensão não suportada para visualização."}),a("b",{className:"text-base text-foreground",children:"Deseja fazer o download do arquivo?"})]}),A===yh.image&&a("img",{loading:"eager",src:i.url,alt:i.name,className:"max-w-full max-h-[85vh] object-contain"}),A===yh.video&&a("video",{controls:!0,autoPlay:!0,src:i.url,className:"w-full h-full"}),A===yh.audio&&a("audio",{controls:!0,autoPlay:!0,src:i.url}),(A===yh.wopi||A===yh.report)&&t("div",{className:"relative w-full h-[79.5vh]",children:[a(Yo,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),a("iframe",{ref:S,src:i.url,onLoad:I,className:"border-none w-full h-full z-[1] relative",title:i.name})]})]})}),!s&&A===yh.none&&t("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[a($i,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),d&&a($i,{variant:"default",onClick:()=>c?.(),children:"Download"})]})]})})}function Ih(e){const{t:a}=Ga(),t=e%60;return`${Math.floor(e/60)}min ${t<10?"0":""}${t}`}function Th({open:e,onOpenChange:r,identifier:n,fileName:i,mode:s="edit",type:d="document",onClose:c,className:u}){const[p,h]=o(!0),f=function(e,a="edit",t="document"){return`https://docs.google.com/${t}/d/${e}/${a}?usp=drivesdk?embedded=true&rm=demo`}(n,s,d);m(()=>{if(e){h(!0);const e=setTimeout(()=>h(!1),300);return()=>clearTimeout(e)}},[e]);const g=l(()=>{c?.(),r(!1)},[c,r]);return m(()=>{if(!e)return;const a=e=>{"Escape"===e.key&&g()};return window.addEventListener("keyup",a),()=>window.removeEventListener("keyup",a)},[e,g]),a(mo,{open:e,onOpenChange:r,children:t(bo,{className:Fi("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",u),children:[t("div",{className:"flex items-center justify-between mb-6 min-h-[30px]",children:[a("h2",p?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-80px)]",children:i}),a("div",{className:"flex items-center ml-4 z-20",children:t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:g,children:a(E,{className:"h-4 w-4"})})}),a(gs,{children:"Fechar"})]})})]}),a("div",{className:"flex flex-col items-center justify-center min-h-[160px] w-full min-w-[77vw] min-h-[80vh]",children:p?a(Yo,{className:"h-14 w-14"}):t("div",{className:"relative w-full h-[79.5vh]",children:[a(Yo,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),a("iframe",{src:f,className:"border-none w-full h-full z-[1] relative",title:i})]})})]})})}function Rh({open:e,onOpenChange:r,url:n,title:i,className:o,minHeight:s="250px"}){const{t:d}=Ga(),c=l(()=>{r(!1)},[r]);return m(()=>{if(!e)return;const a=e=>{"Escape"===e.key&&c()};return window.addEventListener("keyup",a),()=>window.removeEventListener("keyup",a)},[e,c]),a(mo,{open:e,onOpenChange:r,children:t(bo,{className:Fi("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",o),children:[t("div",{className:"flex items-center justify-end mb-2.5",children:[i&&a("h2",{className:"text-lg font-medium text-foreground truncate mr-auto",children:i}),t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c,children:a(E,{className:"h-4 w-4"})})}),a(gs,{children:"Fechar"})]})]}),a("iframe",{src:n,className:"border-none w-full",style:{minHeight:s},title:i||d("embedded_content")})]})})}function Mh({term:n,open:i,onClose:s,onAgree:d,title:c=e.t("terms_updated"),seeLaterLabel:u=e.t("terms_see_later"),agreeLabel:m=e.t("terms_read_agree"),viewTermLabel:p=e.t("terms_view")}){const[h,f]=o(!1),g=l(()=>{d(n.id)},[d,n.id]);return t(r,{children:[a(mo,{open:i&&!h,onOpenChange:e=>!e&&s(),children:t(bo,{className:"sm:max-w-md",children:[a(xo,{children:t(wo,{className:"flex items-center gap-2",children:[a(Ge,{className:"h-5 w-5 text-primary"}),c]})}),t("div",{className:"space-y-4",children:[n.description&&a(Dd,{className:"max-h-48",children:a("div",{className:"text-sm text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:n.description}})}),n.file&&t($i,{variant:"link",className:"px-0 text-primary",onClick:()=>f(!0),children:[a(pe,{className:"mr-1 h-4 w-4"}),p]})]}),t(No,{className:"gap-2 sm:gap-0",children:[a($i,{variant:"ghost",onClick:s,children:u}),a($i,{onClick:g,children:m})]})]})}),h&&a(Lh,{term:n,open:h,onClose:()=>f(!1),viewOnly:!0})]})}function Lh({term:r,open:n,onClose:i,onSign:o,viewOnly:d=!1,title:c=e.t("terms_of_use"),signLabel:u=e.t("terms_read_agree")}){const m=s(()=>r.file?function(e,a=""){const{t:t}=Ga(),r=atob(e),n=[];for(let o=0;o<r.length;o+=512){const e=r.slice(o,o+512),a=new Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t);n.push(new Uint8Array(a))}const i=new Blob(n,{type:a});return URL.createObjectURL(i)}(r.file,r.type):null,[r.file,r.type]),p=l(()=>{m&&URL.revokeObjectURL(m),i()},[m,i]),h=l(()=>{r.hasUserSignature?p():o?.(r.id)},[r,o,p]),f=!d&&!r.hasUserSignature&&o;return a(mo,{open:n,onOpenChange:e=>!e&&p(),children:t(bo,{className:Fi("flex flex-col p-0 sm:max-w-[80vw] h-[95vh]","[&>button.absolute]:hidden"),children:[t("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[t("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[a(Be,{className:"h-5 w-5 text-primary"}),c]}),t("div",{className:"flex items-center gap-2",children:[f&&a($i,{size:"sm",onClick:h,children:u}),a($i,{variant:"ghost",size:"icon",onClick:p,children:a(E,{className:"h-4 w-4"})})]})]}),a("div",{className:"flex-1 min-h-0",children:r.file&&m?a("iframe",{className:"h-full w-full border-0",src:m,title:c}):a("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:a("p",{children:"Nenhum termo de uso ativo encontrado."})})})]})})}function zh(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Fh({users:r,groups:n=[],value:i,onChange:d,disabled:c=!1,maxHeight:u=350,hideGroupFilter:m=!1,searchPlaceholder:p="Buscar usuário...",selectLabel:h="Selecionar",doneLabel:f="Concluir",allLabel:g="Todos",emptyLabel:v=e.t("leadership_no_user_selected"),selectedLabel:b="selecionado",selectedPluralLabel:x="selecionados",className:y}){const[N,w]=o(!1),[_,C]=o(""),[k,S]=o(void 0),A=s(()=>new Set(i),[i]),E=s(()=>{let e=r;if(k&&(e=e.filter(e=>e.groupIds?.includes(k))),_){const a=zh(_);e=e.filter(e=>zh(e.name).includes(a)||zh(e.email??"").includes(a))}return e},[r,k,_]),D=s(()=>N?E:r.filter(e=>A.has(e.id)),[N,E,r,A]),P=i.length,I=s(()=>E.length>0&&E.every(e=>A.has(e.id)),[E,A]),T=l(e=>{if(c)return;const a=A.has(e)?i.filter(a=>a!==e):[...i,e];d(a)},[i,A,d,c]),R=l(e=>{if(c)return;const a=new Set(E.map(e=>e.id));if(e){const e=new Set([...i,...a]);d(Array.from(e))}else d(i.filter(e=>!a.has(e)))},[i,E,d,c]),M=l(()=>{w(e=>!e),C(""),S(void 0)},[]);return t("div",{className:Fi("rounded-md border bg-muted/30",y),children:[(!c||P>0)&&t("div",{className:Fi("flex items-center justify-between px-4 py-2",!c&&"cursor-pointer hover:bg-muted/50"),onClick:c?void 0:M,children:[a("span",{className:"text-sm font-medium text-primary uppercase",children:!c&&(N?f:h)}),a("span",{className:"text-xs text-muted-foreground",children:P>0&&`${P} ${1===P?b:x}`})]}),t("div",{className:"px-4 pb-3",children:[N&&t("div",{className:"flex gap-3 mb-3",children:[!m&&n.length>0&&t(Mo,{value:k??"__all__",onValueChange:e=>S("__all__"===e?void 0:e),children:[a(Fo,{className:"w-[200px] h-9 text-sm",children:a(zo,{placeholder:e.t("approval_user_group")})}),t(Oo,{children:[a($o,{value:"__all__",children:e.t("team_all_groups")}),n.map(e=>a($o,{value:e.id,children:e.name},e.id))]})]}),t("div",{className:"relative flex-1",children:[a(B,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{className:"pl-8 h-9 text-sm",placeholder:p,value:_,onChange:e=>C(e.target.value)})]})]}),!N&&0===P&&t("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:[a(Ze,{className:"h-4 w-4 mr-2"}),v]}),N&&E.length>0&&t("div",{className:"flex items-center gap-2 mb-2",children:[a(qo,{checked:I,onCheckedChange:e=>R(!!e)}),a("span",{className:"text-sm",children:g})]}),D.length>0&&a(Dd,{style:{maxHeight:u},className:"pr-2",children:a("div",{className:"space-y-0.5",children:D.map(e=>{return t("div",{className:Fi("flex items-center gap-3 rounded-md bg-background px-3 py-2 text-sm",N&&!c&&"cursor-pointer hover:bg-accent/50"),onClick:N?()=>T(e.id):void 0,children:[N&&a(qo,{checked:A.has(e.id),onCheckedChange:()=>T(e.id),onClick:e=>e.stopPropagation()}),t(bu,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(xu,{src:e.avatar,alt:e.name}),a(yu,{className:"text-xs",children:(r=e.name,r.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join(""))})]}),t("div",{className:"flex flex-col min-w-0",children:[a("span",{className:"font-normal truncate",children:e.name}),e.email&&a("span",{className:"text-xs text-muted-foreground truncate",children:e.email})]})]},e.id);var r})})}),N&&0===E.length&&a("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:"Nenhum usuário encontrado"})]})]})}function Uh(e){const{t:a}=Ga();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function jh(e){const{t:a}=Ga(),t=new Set;if(!e)return t;for(const r of e)r.allowedIds?.forEach(e=>t.add(e)),r.inheritedIds?.forEach(e=>t.add(e));return t}function Oh({items:r,categories:n,value:i,onChange:d,readonly:c=!1,isLoading:u=!1,title:m=e.t("permissions"),addButtonLabel:p=e.t("allow"),chipsTitle:h=e.t("allowed_items"),chipsPlaceholder:f=e.t("no_item_selected"),searchPlaceholder:g=e.t("search_placeholder"),selectPlaceholder:v=e.t("select_items_to_add"),itemInfoTemplate:b=e=>`${e} ${1===e?"item":"itens"}`,disclaimer:x,disclaimerLink:y,onDisclaimerClick:N,className:w}){const[_,C]=o(n[0]?.id??""),[k,S]=o(""),[A,P]=o([]),[T,R]=o(!1),M=s(()=>jh(i[_]),[i,_]),L=s(()=>function(e){const{t:a}=Ga(),t=new Set;if(!e)return t;for(const r of e)r.inheritedIds?.forEach(e=>t.add(e));return t}(i[_]),[i,_]),z=s(()=>r.filter(e=>M.has(e.id)),[r,M]),F=s(()=>{const e=Uh(k);return r.filter(a=>!M.has(a.id)&&!(e&&!Uh(a.name).includes(e)))},[r,M,k]),U=s(()=>{const e={};for(const a of n)e[a.id]=jh(i[a.id]).size;return e},[n,i]),j=l(e=>{C(e),P([]),S("")},[]),O=l(e=>{P(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),$=l(()=>{if(0===A.length)return;const e=[...i[_]??[]];for(const a of A){const t=r.find(e=>e.id===a),n=t?.group??"default",i=e.find(e=>e.context===n);i?i.allowedIds.includes(a)||(i.allowedIds=[...i.allowedIds,a]):e.push({context:n,allowedIds:[a],inheritedIds:[]})}d({...i,[_]:e}),P([]),S(""),R(!1)},[A,i,_,r,d]),V=l(e=>{if(L.has(e))return;const a=(i[_]??[]).map(a=>({...a,allowedIds:a.allowedIds.filter(a=>a!==e)}));d({...i,[_]:a})},[i,_,L,d]);return u?t("div",{className:Fi("rounded-md border bg-muted/30 p-4 animate-pulse space-y-3",w),children:[a("div",{className:"h-4 w-32 bg-muted rounded"}),a("div",{className:"h-9 w-full bg-muted rounded"}),a("div",{className:"h-20 w-full bg-muted rounded"})]}):a("div",{className:Fi("rounded-md border bg-muted/30",w),children:t("div",{className:"p-4 space-y-4",children:[t("div",{className:"space-y-2",children:[a("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:m}),t(Mo,{value:_,onValueChange:j,children:[a(Fo,{className:"h-9 text-sm",children:a(zo,{})}),a(Oo,{children:n.map(e=>a($o,{value:e.id,children:t("span",{className:"flex items-center gap-2",children:[e.icon,e.name,U[e.id]>0&&a(Go,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:U[e.id]})]})},e.id))})]})]}),!c&&t("div",{className:"flex gap-2",children:[t(bs,{open:T,onOpenChange:R,children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[A.length>0?`${A.length} selecionado${A.length>1?"s":""}`:v,a(D,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t(ys,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:[a("div",{className:"p-2 border-b",children:t("div",{className:"relative",children:[a(B,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{className:"pl-8 h-8 text-sm",placeholder:g,value:k,onChange:e=>S(e.target.value)})]})}),a(Dd,{className:"max-h-[220px]",children:0===F.length?a("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Nenhum item encontrado"}):a("div",{className:"p-1",children:F.map(e=>{const r=A.includes(e.id);return t("div",{className:Fi("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",r&&"bg-accent/50"),onClick:()=>O(e.id),children:[a("div",{className:Fi("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",r&&"bg-primary text-primary-foreground"),children:r&&a(I,{className:"h-3 w-3"})}),t("div",{className:"flex flex-col min-w-0",children:[a("span",{className:"truncate",children:e.name}),null!=e.count&&a("span",{className:"text-xs text-muted-foreground",children:b(e.count)})]})]},e.id)})})})]})]}),t($i,{size:"sm",className:"h-9 gap-1",disabled:0===A.length,onClick:$,children:[a(Q,{className:"h-4 w-4"}),p]})]}),t("div",{className:"space-y-2",children:[a("p",{className:"text-sm font-medium",children:h}),a("div",{className:Fi("rounded-md border bg-background p-3 min-h-[60px]",c&&"bg-muted/50"),children:0===z.length?a("span",{className:"text-sm text-muted-foreground",children:f}):a("div",{className:"flex flex-wrap gap-1.5",children:z.map(e=>{const r=L.has(e.id);return t(Go,{variant:r?"secondary":"default",className:"gap-1 pl-2 pr-1 py-1 text-xs",children:[e.name,!c&&!r&&a("button",{type:"button",className:"ml-0.5 rounded-full hover:bg-primary-foreground/20 p-0.5",onClick:()=>V(e.id),children:a(E,{className:"h-3 w-3"})})]},e.id)})})}),c&&x&&t("p",{className:"text-xs text-muted-foreground",children:[a("span",{dangerouslySetInnerHTML:{__html:x}})," ",y&&N&&a("button",{type:"button",className:"text-primary underline hover:no-underline",onClick:N,children:y})]})]})]})})}var Bh,$h;($h=Bh||(Bh={}))[$h.WaitingProcessing=1]="WaitingProcessing",$h[$h.Processing=2]="Processing",$h[$h.Completed=3]="Completed",$h[$h.Error=4]="Error",$h[$h.Expired=5]="Expired";const Vh={report:e.t("report"),status:e.t("status"),requestDate:e.t("request_date"),lastUpdate:e.t("last_update"),expirationDate:e.t("expiration_date"),viewReport:e.t("view_report"),searchPlaceholder:e.t("search_report_placeholder"),noResults:e.t("no_reports_found"),statusWaiting:e.t("status_waiting"),statusProcessing:e.t("status_processing"),statusCompleted:e.t("status_completed"),statusError:e.t("status_error"),statusExpired:e.t("status_expired")};function qh(e){const{t:a}=Ga();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Wh(e){const{t:a}=Ga();return e.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Hh({requests:e,isLoading:n=!1,onGetReportUrl:i,formatDate:d=Wh,labels:c,className:u}){const{t:m}=Ga(),p={...Vh,...c},[h,f]=o(""),[g,v]=o(!1),[b,x]=o(""),[y,N]=o(""),[w,_]=o(null),C=s(()=>{if(!h)return e;const a=qh(h);return e.filter(e=>qh(e.reportName).includes(a))},[e,h]),k=l(async e=>{if(!w){_(e.id);try{const a=await i(e.id);a&&(x(a),N(e.reportName),v(!0))}finally{_(null)}}},[i,w]);return n?a("div",{className:Fi("space-y-3",u),children:Array.from({length:5}).map((e,t)=>a(Ps,{className:"h-12 w-full"},t))}):t(r,{children:[t("div",{className:Fi("space-y-3",u),children:[t("div",{className:"relative max-w-sm",children:[a(B,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{className:"pl-8 h-9 text-sm",placeholder:p.searchPlaceholder,value:h,onChange:e=>f(e.target.value)})]}),a(Dd,{className:"rounded-md border",children:t(Pl,{children:[a(Il,{children:t(Ml,{children:[a(Ll,{className:"min-w-[140px]",children:p.report}),a(Ll,{className:"min-w-[150px]",children:p.status}),a(Ll,{className:"min-w-[160px]",children:p.requestDate}),a(Ll,{className:"min-w-[160px]",children:p.lastUpdate}),a(Ll,{className:"min-w-[160px]",children:p.expirationDate}),a(Ll,{className:"min-w-[140px]"})]})}),a(Tl,{children:0===C.length?a(Ml,{children:a(zl,{colSpan:6,className:"text-center text-muted-foreground py-8",children:p.noResults})}):C.map(e=>{const r=function(e){const{t:a}=Ga();return new Date>new Date(e.expirationDate)&&e.statusId===Bh.Completed?Bh.Expired:e.statusId}(e),n=function(e,t){const{t:r}=Ga();switch(e){case Bh.WaitingProcessing:return{label:t.statusWaiting,icon:a(ta,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case Bh.Processing:return{label:t.statusProcessing,icon:a(ue,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case Bh.Completed:return{label:t.statusCompleted,icon:a(aa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case Bh.Error:return{label:t.statusError,icon:a(O,{className:"h-3.5 w-3.5"}),variant:"danger"};case Bh.Expired:return{label:t.statusExpired,icon:a(ea,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-orange-600 border-orange-300 bg-orange-50"};default:return{label:"—",icon:null,variant:"secondary"}}}(r,p),i=r===Bh.Completed,o=r===Bh.Expired;return t(Ml,{children:[a(zl,{className:"font-medium",children:e.reportName}),a(zl,{children:t(Go,{variant:n.variant,className:Fi("gap-1",n.className),children:[n.icon,n.label]})}),a(zl,{className:"text-sm",children:d(new Date(e.requestDate))}),a(zl,{className:"text-sm",children:d(new Date(e.lastUpdate))}),a(zl,{className:Fi("text-sm",o&&"text-destructive"),children:d(new Date(e.expirationDate))}),a(zl,{children:t($i,{variant:"ghost",size:"sm",className:"gap-1.5",disabled:!i||w===e.id,onClick:()=>k(e),children:[w===e.id?a(T,{className:"h-4 w-4 animate-spin"}):a(Ce,{className:"h-4 w-4"}),p.viewReport]})})]},e.id)})})]})})]}),a(Rh,{open:g,onOpenChange:v,url:b,title:y})]})}function Gh({reportApiUrl:e,parameters:t={},minHeight:r="80vh",...n}){const i=s(()=>{const a=`${e}/api/reports/v1/Viewer/InitViewer`,r=new URLSearchParams(t).toString();return r?`${a}?${r}`:a},[e,t]);return a(Rh,{...n,url:i,minHeight:r})}const Kh={sm:{badge:"px-1.5 py-0.5 text-[11px] gap-1",icon:14},md:{badge:"px-2.5 py-1 text-xs gap-1.5",icon:16},lg:{badge:"px-3 py-1.5 text-sm gap-2",icon:18}};function Yh({label:e,color:r,icon:n,showIcon:i,size:o="md",variant:s="filled",backgroundColor:l,className:d}){const c=Kh[o],u=i??!!n;return t("span",{className:Fi("inline-flex items-center rounded-md font-medium whitespace-nowrap","outline"===s&&"border",c.badge,d),style:(()=>{switch(s){case"outline":return{color:r,borderColor:Ti(r,.3),backgroundColor:"transparent"};case"ghost":return{color:r,backgroundColor:"transparent"};default:return{color:r,backgroundColor:l||Ti(r,.1)}}})(),children:[u&&n&&a(n,{size:c.icon,strokeWidth:2}),e]})}function Qh(e){return a=>e[a]}var Xh,Jh,Zh,ef,af,tf,rf,nf,of,sf,lf,df,cf,uf,mf,pf,hf,ff,gf,vf,bf,xf,yf,Nf,wf,_f,Cf,kf,Sf,Af,Ef,Df,Pf,If,Tf,Rf,Mf,Lf,zf,Ff,Uf,jf,Of,Bf,$f,Vf,qf,Wf,Hf,Gf,Kf;(Jh=Xh||(Xh={})).Count="valuecount",Jh.Sum="sum",Jh.Average="average",Jh.DistinctCount="valuecount_distict",Jh.Max="max",Jh.Min="min",(Zh||(Zh={})).ViewAllAnalysis="nes3j6wn",(af=ef||(ef={})).RegisterDashboards="EeKs7CYA",af.RemoveDashboards="3GKZYOQ9",af.ViewAllDashboards="wYBdQNvZ",af.EditDashboards="bMFcbwv4",(rf=tf||(tf={}))[rf.Default=1]="Default",rf[rf.Compact=2]="Compact",(of=nf||(nf={}))[of.FiveSeconds=1]="FiveSeconds",of[of.TenSeconds=2]="TenSeconds",of[of.FifteenSeconds=3]="FifteenSeconds",of[of.ThirtySeconds=4]="ThirtySeconds",of[of.OneMinute=5]="OneMinute",of[of.ThreeMinutes=6]="ThreeMinutes",of[of.FiveMinutes=7]="FiveMinutes",of[of.TenMinutes=8]="TenMinutes",(lf=sf||(sf={}))[lf.Day=1]="Day",lf[lf.Month=2]="Month",lf[lf.Year=3]="Year",(cf=df||(df={}))[cf.Ascending=1]="Ascending",cf[cf.Descending=2]="Descending",(mf=uf||(uf={}))[mf.Label=1]="Label",mf[mf.Value=2]="Value",(hf=pf||(pf={}))[hf.LastSevenDays=1]="LastSevenDays",hf[hf.LastWeek=2]="LastWeek",hf[hf.LastMonth=3]="LastMonth",hf[hf.PreviousQuarter=4]="PreviousQuarter",hf[hf.PreviousSemester=5]="PreviousSemester",hf[hf.LastYear=6]="LastYear",hf[hf.SpecificPeriod=7]="SpecificPeriod",hf[hf.CurrentMonth=8]="CurrentMonth",hf[hf.CurrentSemester=9]="CurrentSemester",hf[hf.CurrentWeek=10]="CurrentWeek",hf[hf.CurrentYear=11]="CurrentYear",(gf=ff||(ff={}))[gf.Text=1]="Text",gf[gf.Area=2]="Area",gf[gf.Bar=3]="Bar",gf[gf.Column=4]="Column",gf[gf.StackedColumn=5]="StackedColumn",gf[gf.Line=6]="Line",gf[gf.List=7]="List",gf[gf.Numeric=8]="Numeric",gf[gf.Pareto=9]="Pareto",gf[gf.Pie=10]="Pie",gf[gf.RiskMatrix=11]="RiskMatrix",gf[gf.Burndown=12]="Burndown",gf[gf.PerformanceColumns=13]="PerformanceColumns",gf[gf.EvolutionLine=14]="EvolutionLine",(bf=vf||(vf={}))[bf.NotUpdate=1]="NotUpdate",bf[bf.FiveMinutes=2]="FiveMinutes",bf[bf.TenMinutes=3]="TenMinutes",bf[bf.FifteenMinutes=4]="FifteenMinutes",bf[bf.ThirtyMinutes=5]="ThirtyMinutes",bf[bf.OneHour=6]="OneHour",(yf=xf||(xf={}))[yf.NormalPage=1]="NormalPage",yf[yf.Carousel=2]="Carousel",(wf=Nf||(Nf={}))[wf.General=0]="General",wf[wf.Share=1]="Share",(Cf=_f||(_f={}))[Cf.NotShared=1]="NotShared",Cf[Cf.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",Cf[Cf.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(Sf=kf||(kf={})).PtBr="pt-br",Sf.EnUs="en",Sf.EsEs="es",(Ef=Af||(Af={}))[Ef.Quantity=0]="Quantity",Ef[Ef.AllRisksList=1]="AllRisksList",(Pf=Df||(Df={}))[Pf.Five=5]="Five",Pf[Pf.Ten=10]="Ten",Pf[Pf.Fifteen=15]="Fifteen",Pf[Pf.Twenty=20]="Twenty",Pf[Pf.All=0]="All",Pf[Pf.Custom=-1]="Custom",(Tf=If||(If={}))[Tf.AlphabeticalAsc=1]="AlphabeticalAsc",Tf[Tf.AlphabeticalDesc=2]="AlphabeticalDesc",Tf[Tf.CountAsc=3]="CountAsc",Tf[Tf.CountDesc=4]="CountDesc",Tf[Tf.DateAsc=5]="DateAsc",Tf[Tf.DateDesc=6]="DateDesc",(Mf=Rf||(Rf={}))[Mf.Loading=0]="Loading",Mf[Mf.Loaded=1]="Loaded",Mf[Mf.Error=3]="Error",Mf[Mf.NoData=4]="NoData",Mf[Mf.Unavailable=5]="Unavailable",(zf=Lf||(Lf={}))[zf.Quantity=1]="Quantity",zf[zf.Percentage=2]="Percentage",zf[zf.QuantityPercentage=3]="QuantityPercentage",(Uf=Ff||(Ff={}))[Uf.Program=1]="Program",Uf[Uf.Project=2]="Project",Uf[Uf.Action=3]="Action",Uf[Uf.PerformanceProject=4]="PerformanceProject",Uf[Uf.PerformanceAction=5]="PerformanceAction",(Of=jf||(jf={})).OccurrenceActionPlans="xebGnSSq",Of.OccurrenceGeneral="UFws4AvH",Of.PlansActionPlans="Kux6CcVC",Of.PlansProgramProjects="UWjrp6Dw",Of.PlansIdeas="3g7vNm2w",Of.RisksGeneral="PZ4b6FhP",Of.RisksActionPlans="xZErDg57",Of.RisksAnalysis="UxsioMbH",Of.RisksIncidences="gNt5IJ2F",Of.MetrologyGeneral="4MfEPbRY",Of.MetrologyActivities="hdFM9XQW",Of.MetrologyServiceOrders="cIrVPdMv",Of.DecisionsGeneral="CopsnHDB",Of.DecisionsItems="qLFAayjx",Of.DecisionsActionPlans="RiQFpxdb",Of.FlowGeneral="AFV98JoG",Of.AuditGeneral="gON8LJPi",Of.AuditPlans="SsCNVOvr",Of.AuditPlansItems="OpPkCCFm",Of.AuditActionPlans="P1oGePhh",Of.CommonGeneral="VVfEzgMQ",Of.ActionPlans="C6Z4MgGa",Of.SuppliersEvaluations="fSCeS4mH",Of.SuppliersGeneral="8qPThkrD",Of.SuppliersEvaluationsCriteria="RiSIStdY",Of.SuppliersDocuments="Riua4jMa",Of.SuppliersMaterialsServices="UpEkatXH",Of.DocumentsGeneral="FRhhEX2J",Of.DocumentsPhysicalCopies="PZLtJ23h",Of.DocumentsObsolete="XDjbga14",Of.FmeaGeneral="aPwf4uPr",Of.FmeaActionPlans="vQ8PMrVX",($f=Bf||(Bf={}))[$f.NotShared=1]="NotShared",$f[$f.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",$f[$f.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(qf=Vf||(Vf={}))[qf.All=1]="All",qf[qf.OnlyMine=2]="OnlyMine",qf[qf.Favorites=3]="Favorites",(Hf=Wf||(Wf={}))[Hf.Current=1]="Current",Hf[Hf.Inherent=2]="Inherent",(Kf=Gf||(Gf={}))[Kf.Default=1]="Default",Kf[Kf.Pastel=2]="Pastel",Kf[Kf.Vibrant=3]="Vibrant",Kf[Kf.Earth=4]="Earth",Kf[Kf.Ocean=5]="Ocean",Kf[Kf.Floral=6]="Floral",Kf[Kf.Night=7]="Night",Kf[Kf.Winter=8]="Winter",Kf[Kf.Spring=9]="Spring",Kf[Kf.Summer=10]="Summer",Kf[Kf.Fall=11]="Fall",Kf[Kf.Gray=12]="Gray",Kf[Kf.Brown=13]="Brown",Kf[Kf.Blue=14]="Blue",Kf[Kf.Yellow=15]="Yellow",Kf[Kf.Green=16]="Green",Kf[Kf.Purple=17]="Purple",Kf[Kf.Orange=18]="Orange",Kf[Kf.Pink=19]="Pink",Kf[Kf.Red=20]="Red";const Yf={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},Qf={advancedFilter:"analysisDashboardsListFilter"},Xf=["total_calibration_cost","total_verification_cost","total_maintenance_cost","last_calibration_cost","last_verification_cost","last_maintenance_cost","total_cost","total_reported_cost","estimated_cost","last_report_cost_reported_cost","occurrence_reported_cost","task_estimated_cost"],Jf=["link","link_risk","risk_link","link_group","group_link","link_occurrence","occurrence_link","link_audit","link_project","link_program","link_ideia","flow_link","decision_link","link_supplier","auditing_link","fmea_link"];function Zf(e){return e?.sort((e,a)=>{if(!e?.items?.length||!a?.items?.length)return 0;return eg(e.items[0]?.keyDate)-eg(a.items[0]?.keyDate)})}function eg(e){if(!e)return 0;const[a,t]=e.split("/"),r=Yf[a?.toLowerCase()]??0;return 12*(parseInt(t)||0)+r}function ag(e){return null==e?.value||""===e.value.trim()}function tg(e){const a=e.split("/"),t=a[a.length-1];return`${a.slice(0,-1).join("/")}/${encodeURIComponent(t.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function rg(e){for(const a of Jf)if(e[a])return e[a];return null}function ng(e){return e?ig(e).join("&"):null}function ig(e){const a=[];for(const t of Object.keys(e)){const r=e[t];null!=r&&(r instanceof Date?a.push(`${t}=${r.toISOString()}`):Array.isArray(r)?r.forEach(e=>{a.push(...ig({[t]:e}))}):"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||a.push(`${t}=${r}`))}return a}const og=/^-?\d+(,\d{3})*(\.\d+)?$/;function sg(e){return!!og.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))}function lg(e){const a=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(a)}const dg=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});function cg(e){e.forEach(a=>{a.children=e.filter(e=>e.parentId===a.id)});const a=e.filter(e=>!e.parentId);return function e(a,t){a?.forEach(a=>{t(a),a.children&&e(a.children,t)})}(a,a=>{a.children=e.filter(e=>e.parentId===a.id)}),a}const ug=new Set([ff.Text]),mg=new Set([ff.Text,ff.Numeric,ff.RiskMatrix,ff.Burndown,ff.PerformanceColumns]),pg=new Set([ff.Text,ff.RiskMatrix,ff.Burndown,ff.PerformanceColumns]);function hg({config:e,viewOnly:n=!1,complement:i,complementPosition:d="before-options",queryUrlBuilder:c,onRefresh:u,onExport:m,onToggleOnlyMine:p,className:h}){const{t:f}=Ga(),[g,v]=o(e.onlyMine??!1),b=ug.has(e.typeId),x=!mg.has(e.typeId),y=!pg.has(e.typeId),N=s(()=>{if(!e.jsonRules||e.typeId===ff.PerformanceColumns)return!1;try{const a=JSON.parse(e.jsonRules);return a?.rules?.rules?.length>0}catch{return!1}},[e.jsonRules,e.typeId]),w=s(()=>c?.(e)??"#",[c,e]),_=l(()=>{const e=!g;v(e),p?.(e)},[g,p]),C=[];return g&&C.push(f("dashboard_only_mine")),e.onlyLate&&C.push(f("dashboard_only_overdue")),N&&C.push(f("dashboard_advanced_filter")),t("div",{className:Fi("flex items-center justify-between gap-2 border-b bg-muted/30 px-2.5 py-1 text-sm font-medium",h),children:[t("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:["before-title"===d&&i,t("div",{className:"flex min-w-0 flex-col",children:[t(hs,{children:[a(fs,{asChild:!0,children:a("span",{className:"block truncate",children:e.title})}),a(gs,{children:e.title})]}),C.length>0&&a("span",{className:"text-[9px] font-normal text-muted-foreground truncate",children:C.join(" | ")})]}),"after-title"===d&&i]}),!n&&t("div",{className:"flex shrink-0 items-center gap-0.5",children:["before-options"===d&&i,t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-6 w-6",children:a(ra,{className:"h-3.5 w-3.5"})})}),t(os,{align:"end",className:"w-48",children:[e.canUpdate&&t(ss,{onClick:()=>e.onEdit?.(e.id),children:[a(G,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!b&&t(ss,{onClick:u,children:[a(ue,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),x&&t(ss,{disabled:e.noData,onClick:m,children:[a(Je,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!b&&t(ss,{disabled:!e.openQueryEnabled,onClick:()=>window.open(w,"_blank"),children:[a(pe,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),y&&t(r,{children:[a(us,{}),t(ss,{onClick:_,children:[g&&a(I,{className:"mr-2 h-3.5 w-3.5"}),!g&&a("span",{className:"mr-2 w-3.5"}),"Somente meus"]})]}),e.canUpdate&&t(r,{children:[a(us,{}),t(ss,{onClick:()=>e.onDuplicate?.(e.id),children:[a(me,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),t(ss,{className:"text-destructive",onClick:()=>e.onRemove?.(e.id),children:[a(H,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===d&&i]})]})}function fg({config:e,queryUrl:r,className:n}){return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[a(de,{className:"h-12 w-12 text-muted-foreground/50"}),a("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"Erro ao exibir os dados."}),a("p",{className:"text-sm text-muted-foreground",children:"A consulta não pôde ser realizada."}),t("p",{className:"mt-2 text-xs",children:[r&&a("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:"Verificar a consulta"}),r&&e.canUpdate&&a("span",{className:"text-muted-foreground",children:" ou "}),e.canUpdate&&a("button",{type:"button",className:"underline hover:text-foreground",onClick:()=>e.onEdit?.(e.id),children:"revisar o painel"})]})]})}function gg({panelType:e,className:r}){const n=e===ff.Burndown;return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-2 p-4",r),children:[a(Yo,{className:"h-10 w-10 text-muted-foreground/40"}),n&&a("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function vg({hasRemovedColumn:r=!1,className:n}){return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[a("h2",{className:"text-lg font-normal text-foreground/80 lg:text-base",children:e.t("no_data_to_display")}),a("p",{className:"text-sm text-muted-foreground lg:text-xs",children:e.t("dashboard_no_data")})]})}function bg({onRemove:e,className:r}){return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[a(de,{className:"h-12 w-12 text-muted-foreground/50"}),a("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"A consulta não pôde ser realizada."}),a("p",{className:"text-sm text-muted-foreground",children:"Este recurso não está disponível."}),e&&a("p",{className:"mt-2 text-xs",children:a("button",{type:"button",className:"underline hover:text-foreground",onClick:e,children:"Remover painel"})})]})}const xg={[Xh.Count]:e.t("dashboard_distinct_count").replace("distinta","").trim()||"Count",[Xh.Sum]:"Sum",[Xh.Average]:e.t("dashboard_average"),[Xh.DistinctCount]:e.t("dashboard_distinct_count"),[Xh.Max]:e.t("dashboard_max_value"),[Xh.Min]:e.t("dashboard_min_value")};function yg({config:e,state:r,value:n,label:i,viewOnly:o=!1,onClick:s,onRefresh:l,queryUrl:d,queryUrlBuilder:c,className:u}){const{t:m}=Ga(),p=i??xg[e.aggregationType??""]??"",h=function(e,a){if(null==e)return"—";const t=Xf.includes(a.field),r=a.aggregationType===Xh.Count||a.aggregationType===Xh.DistinctCount;return t&&!r?dg.format("string"==typeof e?parseFloat(e):e):"number"==typeof e?r?String(e):e.toLocaleString("pt-BR",{maximumFractionDigits:2}):String(e)}(n,e);return t("div",{className:Fi("flex h-full flex-col",u),children:[a(hg,{config:e,viewOnly:o,onRefresh:l,queryUrlBuilder:c}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&t("div",{className:Fi("flex flex-1 flex-col items-center justify-center",s&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:s,children:[a("span",{className:"text-[clamp(1.5rem,7vh,5rem)] font-bold text-foreground leading-tight",children:h}),p&&a("span",{className:"text-xs text-muted-foreground mt-1",children:p})]}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:d}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Ng({config:e,state:r,htmlContent:n,viewOnly:i=!1,onRefresh:o,queryUrl:s,queryUrlBuilder:l,className:d}){const c=n??e.textTypeString??"";return t("div",{className:Fi("flex h-full flex-col",d),children:[a(hg,{config:e,viewOnly:i,onRefresh:o,queryUrlBuilder:l}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:c}}),r===Rf.Error&&a(fg,{config:e,queryUrl:s})]})}function wg({config:e,state:r,data:n=[],columns:i=[],viewOnly:o=!1,onRowClick:d,onRefresh:c,onExport:u,queryUrl:m,queryUrlBuilder:p,enableRowLinks:h=!0,className:f}){const g=s(()=>i.filter(e=>!1!==e.visible),[i]),v=l(e=>{if(d)d(e);else if(h){const a=rg(e);a&&window.open(tg(a),"_blank")}},[d,h]);return t("div",{className:Fi("flex h-full flex-col",f),children:[a(hg,{config:e,viewOnly:o,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 overflow-auto",children:t("table",{className:"w-full text-sm",children:[a("thead",{className:"sticky top-0 z-10 bg-muted/60 backdrop-blur-sm",children:a("tr",{children:g.map(e=>a("th",{className:"px-2 py-1.5 text-left text-xs font-medium text-muted-foreground whitespace-nowrap border-b",children:e.header||e.columnLabel||e.columnName},e.columnName))})}),a("tbody",{children:n.map((e,t)=>{const r=h&&!!rg(e);return a("tr",{className:Fi("border-b border-border/50 transition-colors hover:bg-muted/30",(r||d)&&"cursor-pointer"),onClick:()=>v(e),children:g.map(t=>a("td",{className:"px-2 py-1.5 text-foreground whitespace-nowrap truncate max-w-[200px]",children:t.render?t.render(e[t.columnName],e):_g(e[t.columnName],t)},t.columnName))},t)})})]})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function _g(e,a){return null==e?"":e instanceof Date?"datetime"===a.columnType?e.toLocaleString("pt-BR"):e.toLocaleDateString("pt-BR"):"number"==typeof e?e.toLocaleString("pt-BR"):String(e)}const Cg=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))","#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3"];function kg({config:e,variant:r,state:n,data:i=[],series:o,colors:l,categoryKey:d="key",yAxisFormat:c,viewOnly:u=!1,onPointClick:m,onRefresh:p,onExport:h,queryUrl:f,queryUrlBuilder:g,className:v}){const b=l?.length?l:e.hexColors?.length?e.hexColors:Cg,x=s(()=>o?.length?o:[{dataKey:"value",name:e.title}],[o,e.title]),y="bar"===r,N="stacked-column"===r,w=s(()=>{if(c)return e=>c.replace("{value}",e.toLocaleString("pt-BR"))},[c]);return t("div",{className:Fi("flex h-full flex-col",v),children:[a(hg,{config:e,viewOnly:u,onRefresh:p,onExport:h,queryUrlBuilder:g}),n===Rf.Loading&&a(gg,{}),n===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:Sg({variant:r,data:i,series:x,colors:b,categoryKey:d,isHorizontalBar:y,isStacked:N,yAxisTickFormatter:w,tooltipFormatter:e=>"number"==typeof e?e.toLocaleString("pt-BR"):String(e??""),onPointClick:m})})}),n===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),n===Rf.Error&&a(fg,{config:e,queryUrl:f}),n===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Sg({variant:e,data:r,series:n,colors:i,categoryKey:o,isHorizontalBar:s,isStacked:l,yAxisTickFormatter:d,tooltipFormatter:c,onPointClick:u}){const m={tick:{fontSize:11},tickLine:!1,axisLine:!1},p=a(Et,{dataKey:s?void 0:o,type:s?"number":"category",...m,angle:s?0:-45,textAnchor:s?"middle":"end",height:s?void 0:60,tickFormatter:s?d:void 0}),h=a(Dt,{dataKey:s?o:void 0,type:s?"category":"number",...m,width:s?100:60,tickFormatter:s?void 0:d}),f=a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),g=a(It,{formatter:c,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),v=n.length>1?a(Tt,{wrapperStyle:{fontSize:"11px"}}):null,b=u?(e,a)=>u(r[a],a):void 0;return"bar"===e||"column"===e||"stacked-column"===e?t(Rt,{data:r,layout:s?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(Mt,{dataKey:e.dataKey,name:e.name||e.dataKey,fill:e.color||i[t%i.length],stackId:l?e.stackId||"stack":void 0,radius:l?void 0:[2,2,0,0],onClick:b,cursor:u?"pointer":void 0},e.dataKey))]}):"area"===e?t(Lt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>{const r=e.color||i[t%i.length];return a(zt,{type:"monotone",dataKey:e.dataKey,name:e.name||e.dataKey,stroke:r,fill:r,fillOpacity:.15,strokeWidth:2,dot:!1,activeDot:{r:4,cursor:u?"pointer":void 0}},e.dataKey)})]}):t(Ft,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(Ut,{type:"monotone",dataKey:e.dataKey,name:e.name||e.dataKey,stroke:e.color||i[t%i.length],strokeWidth:2,dot:{r:3},activeDot:{r:5,cursor:u?"pointer":void 0}},e.dataKey))]})}const Ag=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function Eg({config:e,state:r,data:n=[],colors:i,viewOnly:o=!1,onSliceClick:l,onRefresh:d,onExport:c,queryUrl:u,queryUrlBuilder:m,className:p}){const h=i?.length?i:e.hexColors?.length?e.hexColors:Ag,f=s(()=>n.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[n]),g=s(()=>f.reduce((e,a)=>e+(a.value??0),0),[f]);return t("div",{className:Fi("flex h-full flex-col",p),children:[a(hg,{config:e,viewOnly:o,onRefresh:d,onExport:c,queryUrlBuilder:m}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t(jt,{children:[a(Ot,{data:f,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"80%",label:({name:e,percent:a})=>`${e??""}: ${(100*(a??0)).toFixed(0)}%`,labelLine:!0,onClick:l?(e,a)=>l(n[a],a):void 0,cursor:l?"pointer":void 0,children:f.map((e,t)=>a(Bt,{fill:h[t%h.length]},t))}),a(It,{formatter:e=>{const a="number"==typeof e?e:0,t=g>0?(a/g*100).toFixed(1):"0";return`${a.toLocaleString("pt-BR")} (${t}%)`}}),a(Tt,{wrapperStyle:{fontSize:"11px"}})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:u}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Dg({config:e,state:r,data:n=[],barColor:i,lineColor:o="#e31a1c",viewOnly:l=!1,onPointClick:d,onRefresh:c,onExport:u,queryUrl:m,queryUrlBuilder:p,className:h}){const f=e.hexColors?.length?e.hexColors:["#1f78b4"],g=i??f[0],v=s(()=>{const e=[...n].sort((e,a)=>(a.value??0)-(e.value??0)),a=e.reduce((e,a)=>e+(a.value??0),0);let t=0;return e.map(e=>(t+=e.value??0,{key:String(e.key??""),value:e.value??0,cumulativePercent:a>0?Math.round(t/a*100):0}))},[n]);return t("div",{className:Fi("flex h-full flex-col",h),children:[a(hg,{config:e,viewOnly:l,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t($t,{data:v,margin:{top:5,right:30,left:0,bottom:5},children:[a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Et,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),a(Dt,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),a(Dt,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),a(It,{formatter:(e,a)=>"% Acumulado"===a?`${e}%`:"number"==typeof e?e.toLocaleString("pt-BR"):e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(Tt,{wrapperStyle:{fontSize:"11px"}}),a(Mt,{yAxisId:"left",dataKey:"value",name:"Quantidade",fill:g,radius:[2,2,0,0],onClick:d?(e,a)=>d(n[a],a):void 0,cursor:d?"pointer":void 0}),a(Ut,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:o,strokeWidth:2,dot:{r:3,fill:o}})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Pg({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:o,executedColor:s="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:d=!1,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){const{t:h}=Ga(),f=i??h("dashboard_work_done"),g=o??h("dashboard_work_planned");return t("div",{className:Fi("flex h-full flex-col",p),children:[a(hg,{config:e,viewOnly:d,onRefresh:c,queryUrlBuilder:m}),r===Rf.Loading&&a(gg,{panelType:ff.Burndown}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t(Lt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Et,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),a(Dt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),a(It,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(Tt,{wrapperStyle:{fontSize:"11px"}}),a(zt,{type:"monotone",dataKey:"executedPercentage",name:f,stroke:s,fill:s,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),a(zt,{type:"monotone",dataKey:"plannedPercentage",name:g,stroke:l,fill:l,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:u}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Ig({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:o,executedColor:s="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:d=!1,onPointClick:c,onRefresh:u,queryUrl:m,queryUrlBuilder:p,className:h}){const{t:f}=Ga(),g=i??f("dashboard_work_done"),v=o??f("dashboard_work_planned");return t("div",{className:Fi("flex h-full flex-col",h),children:[a(hg,{config:e,viewOnly:d,onRefresh:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t(Rt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Et,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),a(Dt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),a(It,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(Tt,{wrapperStyle:{fontSize:"11px"}}),a(Mt,{dataKey:"executedWork",name:g,fill:s,radius:[2,2,0,0],onClick:c?(e,a)=>c(n[a],a):void 0,cursor:c?"pointer":void 0}),a(Mt,{dataKey:"plannedWork",name:v,fill:l,radius:[2,2,0,0]})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Tg({config:e,state:r,rule:n,risks:i=[],matrixViewType:o=Af.Quantity,viewOnly:l=!1,onCellClick:d,onRiskClick:c,onRefresh:u,queryUrl:m,queryUrlBuilder:p,className:h}){const f=s(()=>[...n?.parametersY??[]].sort((e,a)=>a.position-e.position),[n?.parametersY]),g=n?.parametersX??[],v=s(()=>{const e={};return i.forEach(a=>{const t=`${a.parameterYPosition}-${a.parameterXPosition}`;e[t]||(e[t]=[]),e[t].push(a)}),e},[i]);return t("div",{className:Fi("flex h-full flex-col",h),children:[a(hg,{config:e,viewOnly:l,onRefresh:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&n&&a("div",{className:"flex-1 overflow-auto p-4",children:t("div",{className:"flex gap-4 items-stretch min-w-fit",children:[a("div",{className:"flex items-center justify-center",children:a("span",{className:"text-xs font-medium text-muted-foreground [writing-mode:vertical-lr] rotate-180",children:n.name_y})}),t("div",{className:"flex-1",children:[t("div",{className:"flex mb-1",children:[a("div",{className:"w-16 shrink-0"}),a("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.threat_strategy_type_name}),!n.disable_opportunities&&a("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.opportunity_strategy_type_name})]}),f.map((e,r)=>t("div",{className:"flex",children:[a("div",{className:"w-16 shrink-0 flex items-center justify-center border border-border/50 text-xs font-medium p-1 text-center",children:e.name}),g.map((i,s)=>{const l=((e,a)=>v[`${a.position}-${e.position}`]??[])(i,e),u=((e,a)=>n?.colorMatrix?.[a]?.[e]??"hsl(var(--muted))")(s,r);return t("div",{className:Fi("flex-1 min-w-[60px] min-h-[40px] border border-border/50 flex flex-col items-center justify-center gap-0.5 p-1",(d||c)&&l.length>0&&"cursor-pointer hover:opacity-80"),style:{backgroundColor:u},onClick:()=>l.length>0&&d?.(i,e,l),children:[o===Af.Quantity&&l.length>0&&t("span",{className:"text-xs font-semibold",children:[l.length," risco",1!==l.length?"s":""]}),o===Af.AllRisksList&&l.map(e=>t(hs,{children:[a(fs,{asChild:!0,children:a("button",{type:"button",className:"text-[10px] text-primary underline hover:text-primary/80",onClick:a=>{a.stopPropagation(),c?.(e)},children:e.code})}),t(gs,{className:"max-w-[250px]",children:[t("p",{className:"font-medium",children:[e.code," - ",e.name]}),e.analysisDate&&t("p",{className:"text-xs mt-1",children:["Última análise: ",a("strong",{children:e.analysisDate})]}),e.strategy&&t("p",{className:"text-xs",children:["Estratégia: ",a("strong",{children:e.strategy})]}),e.resultName&&t("p",{className:"text-xs",children:["Criticidade: ",a("strong",{style:{backgroundColor:u},className:"px-1 rounded",children:e.resultName})]})]})]},e.code))]},i.position)})]},e.position)),t("div",{className:"flex",children:[a("div",{className:"w-16 shrink-0"}),g.map(e=>a("div",{className:"flex-1 min-w-[60px] border border-border/50 text-xs font-medium p-1 text-center",children:e.name},e.position))]}),a("div",{className:"text-center text-xs font-medium text-muted-foreground mt-2",children:n.name_x})]})]})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}const Rg=Object.freeze({Translate:{toString(e){if(!e)return;const{x:a,y:t}=e;return"translate3d("+(a?Math.round(a):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:a,scaleY:t}=e;return"scaleX("+a+") scaleY("+t+")"}},Transform:{toString(e){if(e)return[Rg.Translate.toString(e),Rg.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:a,duration:t,easing:r}=e;return a+" "+t+"ms "+r}}});function Mg(e){switch(e){case ff.Bar:case ff.Column:case ff.Pie:case ff.List:case ff.Line:case ff.Area:case ff.Text:case ff.StackedColumn:return{x:4,y:2};case ff.Pareto:case ff.RiskMatrix:case ff.Burndown:case ff.PerformanceColumns:return{x:8,y:2};case ff.Numeric:return{x:1,y:1};default:return{x:2,y:2}}}function Lg(e){switch(Number(e)){case ff.Area:case ff.Bar:case ff.Column:case ff.Line:case ff.Numeric:case ff.Pie:case ff.Text:return{x:1,y:1};default:return{x:2,y:2}}}function zg({panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:o,children:l}){const{attributes:d,listeners:c,setNodeRef:u,transform:m,transition:p,isDragging:h}=nr({id:e.id,disabled:!o}),f=s(()=>({gridColumn:`${e.col+1} / span ${e.sizeX}`,gridRow:`${e.row+1} / span ${e.sizeY}`,minHeight:e.sizeY*n+(e.sizeY-1)*i+"px",transform:Rg.Transform.toString(m),transition:p,zIndex:h?50:void 0,opacity:h?.85:1}),[e,r,n,i,m,p,h]);return t("div",{ref:u,style:f,className:Fi("rounded-lg border border-border bg-card shadow-sm overflow-hidden","transition-shadow duration-200",h&&"shadow-lg ring-2 ring-primary/20"),...d,children:[a("div",{className:Fi("dashboard-panel-drag-handle",o&&"cursor-grab active:cursor-grabbing"),...o?c:{}}),a("div",{className:"h-full",children:l})]})}function Fg({panels:e,columns:r=8,cellHeight:n=160,cellGap:i=10,allowDragging:d=!1,showGridLines:c=!1,renderPanel:u,onLayoutChange:m,className:p}){const[h,f]=o(e);s(()=>{f(e)},[e]);const g=Xt(Jt(Zt,{activationConstraint:{distance:8}})),v=s(()=>0===h.length?1:Math.max(...h.map(e=>e.row+e.sizeY)),[h]),b=s(()=>h.map(e=>e.id),[h]),x=l(e=>{const{active:a,over:t}=e;if(!t||a.id===t.id)return;const r=h.findIndex(e=>e.id===a.id),n=h.findIndex(e=>e.id===t.id);if(-1===r||-1===n)return;const i=[...h],o={...i[r]},s={...i[n]},l=o.col,d=o.row;o.col=s.col,o.row=s.row,s.col=l,s.row=d,i[r]=o,i[n]=s,f(i),m?.(i)},[h,m]),y=s(()=>({display:"grid",gridTemplateColumns:`repeat(${r}, 1fr)`,gridTemplateRows:`repeat(${v}, ${n}px)`,gap:`${i}px`}),[r,v,n,i]);return 0===h.length?t("div",{className:Fi("flex flex-col items-center justify-center py-16 text-center",p),children:[a("h2",{className:"text-lg font-semibold text-foreground mb-2",children:"Nenhum painel adicionado"}),a("p",{className:"text-sm text-muted-foreground",children:"Adicione painéis para visualizar seus dados aqui."})]}):a(er,{sensors:g,collisionDetection:ar,onDragEnd:x,children:a(tr,{items:b,strategy:rr,children:a("div",{style:y,className:Fi("relative w-full",c&&"bg-muted/30",p),children:h.map(e=>a(zg,{panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:d,children:u(e.id)},e.id))})})})}const Ug={[ff.Bar]:"bar",[ff.Column]:"column",[ff.StackedColumn]:"stacked-column",[ff.Area]:"area",[ff.Line]:"line",[ff.EvolutionLine]:"evolution-line"};function jg({config:e,state:r,data:n,numericValue:i,listColumns:o,cartesianData:s,cartesianSeries:l,burndownData:d,performanceData:c,matrixRule:u,matrixRisks:m,onPanelClick:p}){const h=Ug[e.typeId];if(h)return a(kg,{config:e,variant:h,state:r,data:s,series:l});switch(e.typeId){case ff.Numeric:return a(yg,{config:e,state:r,value:i});case ff.Text:return a(Ng,{config:e,state:r});case ff.List:return a(wg,{config:e,state:r,data:n,columns:o??[]});case ff.Pie:return a(Eg,{config:e,state:r,data:n});case ff.Pareto:return a(Dg,{config:e,state:r,data:n});case ff.Burndown:return a(Pg,{config:e,state:r,data:d});case ff.PerformanceColumns:return a(Ig,{config:e,state:r,data:c});case ff.RiskMatrix:return a(Tg,{config:e,state:r,rule:u,risks:m??[]});default:return t("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:["Tipo de painel não suportado (",e.typeId,")"]})}}function Og({dashboard:e,panels:r,pages:n,activePageId:i,canEdit:d=!1,isFullscreen:c=!1,isLoading:u=!1,getPanelData:m,onRefresh:p,onToggleFullscreen:h,onToggleFavorite:f,onEdit:g,onShare:v,onAddPanel:b,onEditPanel:x,onRemovePanel:y,onDuplicatePanel:N,onLayoutChange:w,onPageChange:_,toolbarActions:C,className:k}){const{t:S}=Ga(),[A,E]=o(!1),D=e.idViewType===xf.Carousel,P=s(()=>r,[r,D,i]),I=s(()=>P.map(e=>{const a=Lg(e.typeId);return{id:e.id,col:e.col,row:e.row,sizeX:e.sizeX,sizeY:e.sizeY,minSizeX:a.x,minSizeY:a.y}}),[P]),T=l(e=>({id:e.id,title:e.titlePtBr||e.titleEnUs||e.titleEsEs,typeId:e.typeId,queryId:e.queryId,queryContextId:e.queryContextId,queryTitle:e.queryTitle,querySelectedColumns:e.querySelectedColumns,field:e.field??"",fieldType:e.fieldType??"",fieldAuxAxis:e.fieldAuxAxis,fieldAuxAxisType:e.fieldAuxAxisType,aggregationType:e.aggregationType,textTypeString:e.textTypeString,referenceDate:e.referenceDate,period:e.period,initialDate:e.initialDate,finalDate:e.finalDate,dimension:e.dimension,yAxis:e.yAxis,yAxisType:e.yAxisType,orderBy:e.orderBy,orderByType:e.orderByType,secondaryGrouping:e.secondaryGrouping,secondaryGroupingType:e.secondaryGroupingType,onlyLate:e.onlyLate,jsonRules:e.jsonRules,ignoreRules:e.ignoreRules,visualizationType:e.visualizationType,sortType:e.sortType,itemsPerPanel:e.itemsPerPanel,secondaryItemsPerPanel:e.secondaryItemsPerPanel,matrixViewRule:e.matrixViewRule,listPanelColumns:e.listPanelColumns,listPanelListType:e.listPanelListType,paletteId:e.paletteId,hexColors:e.hexColors,showNotInformedData:e.showNotInformedData,fieldAnalysisRule:e.fieldAnalysisRule,fieldCriticality:e.fieldCriticality,fieldPlansType:e.fieldPlansType,fieldPlansSelected:e.fieldPlansSelected,fieldPlansBurndown:e.fieldPlansBurndown,fieldPlansBurndownGroup:e.fieldPlansBurndownGroup,analysisCriteriaId:e.analysisCriteriaId,analysisCriteriaParameter:e.analysisCriteriaParameter,evolutionSecondaryGrouping:e.evolutionSecondaryGrouping,canUpdate:d,hasRemovedColumn:e.hasRemovedColumn,panelSize:{x:e.sizeX,y:e.sizeY},onEdit:x,onRemove:y,onDuplicate:N}),[d,x,y,N]),R=l(()=>{A||u||(E(!0),p?.(),setTimeout(()=>E(!1),3e4))},[A,u,p]),M=l(e=>{const r=P.find(a=>a.id===e);if(!r)return null;const n=T(r),i=m?.(e)??{state:Rf.Loaded};return t("div",{className:"flex flex-col h-full",children:[a(hg,{config:n,onRefresh:()=>{}}),a("div",{className:"flex-1 min-h-0 p-2",children:a(jg,{config:n,...i})})]})},[P,T,m,d,x,y,N]);return t("div",{className:Fi("flex flex-col h-full",c&&"fixed inset-0 z-50 bg-background",k),children:[t("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-card",children:[t("div",{className:"flex items-center gap-3 min-w-0",children:[a("h1",{className:"text-lg font-semibold text-foreground truncate",children:e.title}),e.responsibleName&&!c&&a("span",{className:"text-xs text-muted-foreground truncate hidden sm:inline",children:e.responsibleName})]}),t("div",{className:"flex items-center gap-1",children:[C,p&&a("button",{onClick:R,disabled:A||u,className:Fi("inline-flex items-center justify-center rounded-md p-2 text-sm","hover:bg-accent hover:text-accent-foreground transition-colors","disabled:opacity-50 disabled:pointer-events-none"),title:A?S("dashboard_wait_refresh"):"Atualizar",children:a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M21 12a9 9 0 0 1-9 9m9-9a9 9 0 0 0-9-9m9 9H3m0 0a9 9 0 0 1 9-9m-9 9a9 9 0 0 0 9 9"})})}),h&&a("button",{onClick:h,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:c?S("dashboard_exit_fullscreen"):"Fullscreen",children:a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",c?{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"}:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),d&&!c&&v&&a("button",{onClick:v,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:"Compartilhar",children:t("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),a("circle",{cx:"9",cy:"7",r:"4"}),a("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),a("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),f&&!c&&a("button",{onClick:f,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:e.isFavorite?S("dashboard_remove_favorite"):"Favoritar",children:a("svg",{className:Fi("h-4 w-4",e.isFavorite&&"fill-yellow-400 text-yellow-400"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})]})]}),D&&n&&n.length>1&&a("div",{className:"flex items-center gap-1 px-4 py-1 border-b border-border bg-card overflow-x-auto",children:n.map(e=>a("button",{onClick:()=>_?.(e.id),className:Fi("px-3 py-1.5 text-sm rounded-md whitespace-nowrap transition-colors",i===e.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:e.name||`Dashboard ${e.position}`},e.id))}),d&&!c&&b&&a("div",{className:"flex justify-center py-3",children:t("button",{onClick:b,className:Fi("inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M12 5v14M5 12h14"})}),"Adicionar painel"]})}),u&&a("div",{className:"flex-1 flex items-center justify-center",children:a("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!u&&a("div",{className:"flex-1 overflow-auto p-4 bg-muted/30",children:a(Fg,{panels:I,allowDragging:d,showGridLines:d,renderPanel:M,onLayoutChange:w})})]})}function Bg(e,a=kf.PtBr){const{t:t}=Ga();switch(a){case kf.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case kf.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function $g(e){const{t:a}=Ga();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const Vg=[{value:Vf.All,label:"Todos"},{value:Vf.OnlyMine,label:e.t("dashboard_my")},{value:Vf.Favorites,label:"Favoritos"}];function qg({dashboards:e,limit:n,isLoading:i=!1,language:d=kf.PtBr,canAdd:c=!1,canEdit:u=!1,canRemove:m=!1,onOpen:p,onEdit:h,onShare:f,onDuplicate:g,onRemove:v,onAdd:b,onToggleFavorite:x,onRefresh:y,onSearch:N,onQuickFilterChange:w,toolbarExtra:_,className:C}){const{t:k}=Ga(),[S,A]=o(""),[E,D]=o(Vf.All),[P,I]=o(null),T=l(e=>{A(e),N?.(e)},[N]),R=l(e=>{D(e),w?.(e)},[w]),M=s(()=>{let a=e;if(S){const e=S.toLowerCase();a=a.filter(a=>a.code?.toLowerCase().includes(e)||Bg(a,d).toLowerCase().includes(e)||a.responsibleName?.toLowerCase().includes(e))}switch(E){case Vf.OnlyMine:break;case Vf.Favorites:a=a.filter(e=>e.isFavorite)}return a},[e,S,E,d]);return t("div",{className:Fi("flex flex-col h-full",C),children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[t("div",{className:"flex items-center gap-3",children:[a("h1",{className:"text-lg font-semibold text-foreground",children:"Dashboards"}),n&&t("span",{className:"text-xs text-muted-foreground",children:["(",n.countDashboards,"/",n.maxDashboards,")"]})]}),t("div",{className:"flex items-center gap-2",children:[t("div",{className:"relative",children:[t("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("circle",{cx:"11",cy:"11",r:"8"}),a("path",{d:"m21 21-4.3-4.3"})]}),a("input",{type:"text",placeholder:"Buscar...",value:S,onChange:e=>T(e.target.value),className:Fi("h-9 w-48 rounded-md border border-input bg-background pl-9 pr-3 text-sm","placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")})]}),_,c&&b&&t("button",{onClick:b,className:Fi("inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M12 5v14M5 12h14"})}),"Novo"]})]})]}),a("div",{className:"flex items-center gap-1 px-4 py-2 border-b border-border bg-card",children:Vg.map(e=>a("button",{onClick:()=>R(e.value),disabled:i,className:Fi("px-3 py-1.5 text-sm rounded-md transition-colors",E===e.value?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground","disabled:opacity-50"),children:e.label},e.value))}),i&&a("div",{className:"flex-1 flex items-center justify-center",children:a("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!i&&a("div",{className:"flex-1 overflow-auto",children:t("table",{className:"w-full text-sm",children:[a("thead",{className:"sticky top-0 bg-muted/80 backdrop-blur-sm border-b border-border",children:t("tr",{children:[a("th",{className:"w-12 px-3 py-2 text-left font-medium text-muted-foreground",children:a("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Código"}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Título"}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Responsável"}),a("th",{className:"w-12 px-3 py-2 text-center font-medium text-muted-foreground",children:t("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),a("circle",{cx:"9",cy:"7",r:"4"}),a("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),a("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Última modificação"}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Situação"}),a("th",{className:"w-12 px-3 py-2"})]})}),t("tbody",{children:[0===M.length&&a("tr",{children:a("td",{colSpan:8,className:"px-3 py-12 text-center text-muted-foreground",children:"Nenhum dashboard encontrado."})}),M.map(e=>t("tr",{onClick:()=>p?.(e),className:Fi("border-b border-border cursor-pointer transition-colors","hover:bg-accent/50"),children:[a("td",{className:"px-3 py-2",children:a("button",{onClick:a=>{a.stopPropagation(),x?.(e)},className:"p-1 hover:bg-accent rounded transition-colors",children:a("svg",{className:Fi("h-4 w-4",e.isFavorite?"fill-yellow-400 text-yellow-400":"text-muted-foreground"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})}),a("td",{className:"px-3 py-2 font-mono text-xs text-foreground",children:e.code}),a("td",{className:"px-3 py-2 text-foreground font-medium",children:Bg(e,d)}),a("td",{className:"px-3 py-2 text-muted-foreground",children:e.responsibleName}),a("td",{className:"px-3 py-2 text-center",children:e.hasSharedIcon&&t("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),a("circle",{cx:"9",cy:"7",r:"4"}),a("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),a("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),a("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:$g(e.lastModified)}),a("td",{className:"px-3 py-2",children:a("span",{className:Fi("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",e.isActive?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"),children:e.isActive?"Ativo":"Inativo"})}),a("td",{className:"px-3 py-2",children:t("div",{className:"relative",children:[a("button",{onClick:a=>{a.stopPropagation(),I(P===e.id?null:e.id)},className:"p-1 hover:bg-accent rounded transition-colors",children:t("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("circle",{cx:"12",cy:"5",r:"1"}),a("circle",{cx:"12",cy:"12",r:"1"}),a("circle",{cx:"12",cy:"19",r:"1"})]})}),P===e.id&&t(r,{children:[a("div",{className:"fixed inset-0 z-40",onClick:()=>I(null)}),t("div",{className:"absolute right-0 top-8 z-50 min-w-[160px] rounded-md border border-border bg-popover shadow-md py-1",children:[a("button",{onClick:a=>{a.stopPropagation(),I(null),p?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Abrir"}),u&&a("button",{onClick:a=>{a.stopPropagation(),I(null),h?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Editar"}),u&&a("button",{onClick:a=>{a.stopPropagation(),I(null),f?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Compartilhar"}),a("button",{onClick:a=>{a.stopPropagation(),I(null),g?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Duplicar"}),m&&t(r,{children:[a("div",{className:"my-1 border-t border-border"}),a("button",{onClick:a=>{a.stopPropagation(),I(null),v?.(e)},className:"w-full px-3 py-1.5 text-left text-sm text-destructive hover:bg-destructive/10 transition-colors",children:"Remover"})]})]})]})]})})]},e.id))]})]})})]})}const Wg=[{value:vf.NotUpdate,label:e.t("dashboard_no_refresh")},{value:vf.FiveMinutes,label:"5 minutos"},{value:vf.TenMinutes,label:"10 minutos"},{value:vf.FifteenMinutes,label:"15 minutos"},{value:vf.ThirtyMinutes,label:"30 minutos"},{value:vf.OneHour,label:"1 hora"}],Hg=[{value:xf.NormalPage,label:e.t("dashboard_normal_page")},{value:xf.Carousel,label:"Carrossel"}],Gg=[{value:nf.FiveSeconds,label:"5 segundos"},{value:nf.TenSeconds,label:"10 segundos"},{value:nf.FifteenSeconds,label:"15 segundos"},{value:nf.ThirtySeconds,label:"30 segundos"},{value:nf.OneMinute,label:"1 minuto"},{value:nf.ThreeMinutes,label:"3 minutos"},{value:nf.FiveMinutes,label:"5 minutos"},{value:nf.TenMinutes,label:"10 minutos"}],Kg=[{value:_f.NotShared,label:e.t("dashboard_not_shared"),description:e.t("dashboard_only_responsible")},{value:_f.SharedWithAllCollaborators,label:e.t("dashboard_shared_unit"),description:e.t("dashboard_all_access")},{value:_f.SharedWithUsersGroupsPlacesCollaborators,label:e.t("dashboard_select_groups"),description:e.t("dashboard_select_groups")}],Yg=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function Qg({dashboard:e,initialTab:r=Nf.General,isSaving:n=!1,isQualitfy:i=!1,users:d=[],groups:c=[],places:u=[],collaborators:m=[],onSave:p,onCancel:h,className:f}){const{t:g}=Ga(),v=!!e,[b,x]=o(r),[y,N]=o({"pt-br":!!e?.titlePtBr||!v,en:!!e?.titleEnUs,es:!!e?.titleEsEs}),[w,_]=o(e?.titlePtBr??""),[C,k]=o(e?.titleEnUs??""),[S,A]=o(e?.titleEsEs??""),[E,D]=o(e?.responsibleId??""),[P,I]=o(e?.isActive??!0),[T,R]=o(e?.idUpdateTime??vf.NotUpdate),[M,L]=o(e?.idViewType??xf.NormalPage),[z,F]=o(e?.idPageTime??nf.FifteenSeconds),[U,j]=o(e?.idShare??_f.NotShared),[O,B]=o(e?.groups??[]),[$,V]=o(e?.places??[]),[q,W]=o(e?.collaborators??[]),H=M===xf.Carousel,G=y["pt-br"]||y.en||y.es,K=s(()=>!!G&&(!(y["pt-br"]&&!w.trim())&&(!(y.en&&!C.trim())&&!(y.es&&!S.trim()))),[G,y,w,C,S]),Y=l(e=>{N(a=>({...a,[e]:!a[e]}))},[]),Q=l(()=>{K&&!n&&p?.({titlePtBr:y["pt-br"]?w:"",titleEnUs:y.en?C:"",titleEsEs:y.es?S:"",responsibleId:E||void 0,isActive:P,idUpdateTime:T,idViewType:M,idPageTime:H?z:null,idShare:U,groups:U===_f.SharedWithUsersGroupsPlacesCollaborators?O:[],places:U===_f.SharedWithUsersGroupsPlacesCollaborators?$:[],collaborators:U===_f.SharedWithUsersGroupsPlacesCollaborators?q:[]})},[K,n,p,y,w,C,S,E,P,T,M,z,H,U,O,$,q]);return t("div",{className:Fi("flex flex-col h-full bg-background",f),children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[t("div",{className:"flex items-center gap-3",children:[a("h2",{className:"text-lg font-semibold text-foreground",children:g(v?"dashboard_edit":"dashboard_new")}),v&&e&&a("span",{className:"text-sm text-muted-foreground",children:e.code})]}),t("div",{className:"flex items-center gap-2",children:[a("button",{onClick:h,className:"px-3 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors",children:"Cancelar"}),t("button",{onClick:Q,disabled:!K||n,className:Fi("inline-flex items-center gap-1.5 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","disabled:opacity-50 disabled:pointer-events-none"),children:[n?a("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"}):a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polyline",{points:"20 6 9 17 4 12"})}),"Salvar"]})]})]}),t("div",{className:"flex border-b border-border bg-card",children:[a("button",{onClick:()=>x(Nf.General),className:Fi("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===Nf.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),a("button",{onClick:()=>x(Nf.Share),className:Fi("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===Nf.Share?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Compartilhamento"})]}),t("div",{className:"flex-1 overflow-auto p-6",children:[b===Nf.General&&t("div",{className:"max-w-2xl space-y-6",children:[t("div",{className:"space-y-2",children:[a("label",{className:"text-sm font-medium text-foreground",children:"Título *"}),a("div",{className:"flex gap-2",children:Yg.map(e=>a("button",{onClick:()=>Y(e.key),className:Fi("px-3 py-1 text-xs rounded-md border transition-colors",y[e.key]?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:bg-accent"),children:e.label},e.key))}),!G&&a("p",{className:"text-xs text-destructive",children:"Selecione pelo menos um idioma"})]}),y["pt-br"]&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Título em Português (BR)"}),a("input",{value:w,onChange:e=>_(e.target.value),maxLength:200,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),t("p",{className:"text-xs text-muted-foreground text-right",children:[w.length,"/200"]})]}),y.en&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Título em Inglês (US)"}),a("input",{value:C,onChange:e=>k(e.target.value),maxLength:200,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),t("p",{className:"text-xs text-muted-foreground text-right",children:[C.length,"/200"]})]}),y.es&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Título em Espanhol (ES)"}),a("input",{value:S,onChange:e=>A(e.target.value),maxLength:200,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),t("p",{className:"text-xs text-muted-foreground text-right",children:[S.length,"/200"]})]}),!e?.isStandard&&d.length>0&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Responsável"}),t("select",{value:E,onChange:e=>D(e.target.value),disabled:!v,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:[a("option",{value:"",children:"Selecione..."}),d.map(e=>a("option",{value:e.id,children:e.name},e.id))]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Intervalo de atualização"}),a("select",{value:T,onChange:e=>R(Number(e.target.value)),disabled:i,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Wg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]}),t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Situação"}),t("div",{className:"flex items-center gap-3 h-10",children:[a("button",{onClick:()=>I(!P),disabled:e?.isGeneralViewUse,className:Fi("relative inline-flex h-6 w-11 items-center rounded-full transition-colors",P?"bg-primary":"bg-muted","disabled:opacity-50"),children:a("span",{className:Fi("inline-block h-4 w-4 rounded-full bg-white transition-transform",P?"translate-x-6":"translate-x-1")})}),a("span",{className:"text-sm text-foreground",children:P?"Ativo":"Inativo"})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Tipo de visualização"}),a("select",{value:M,onChange:e=>L(Number(e.target.value)),disabled:i||H,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Hg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]}),H&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Trocar página a cada"}),a("select",{value:z??"",onChange:e=>F(Number(e.target.value)),className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:Gg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]})]})]}),b===Nf.Share&&t("div",{className:"max-w-2xl space-y-6",children:[t("div",{className:"flex items-start gap-2 p-3 rounded-md bg-muted/50 border border-border",children:[t("svg",{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("circle",{cx:"12",cy:"12",r:"10"}),a("path",{d:"M12 16v-4"}),a("path",{d:"M12 8h.01"})]}),a("p",{className:"text-sm text-muted-foreground",children:"Configure quem pode visualizar este dashboard. O responsável sempre terá acesso."})]}),a("div",{className:"space-y-3",children:Kg.map(r=>t("label",{className:Fi("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",U===r.value?"border-primary bg-primary/5":"border-border hover:bg-accent/50",e?.isGeneralViewUse&&"opacity-50 pointer-events-none"),children:[a("input",{type:"radio",name:"shareType",value:r.value,checked:U===r.value,onChange:()=>j(r.value),disabled:e?.isGeneralViewUse,className:"mt-1 accent-primary"}),t("div",{children:[a("p",{className:"text-sm font-medium text-foreground",children:r.label}),a("p",{className:"text-xs text-muted-foreground",children:r.description})]})]},r.value))}),U===_f.SharedWithUsersGroupsPlacesCollaborators&&t("div",{className:"space-y-4 pl-4 border-l-2 border-primary/20",children:[t("div",{className:"space-y-1",children:[t("label",{className:"text-sm font-medium text-foreground",children:["Grupos de usuários (",O.length,")"]}),a("select",{multiple:!0,value:O,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);B(a)},className:Fi("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:c.map(e=>a("option",{value:e.id,children:e.name},e.id))})]}),t("div",{className:"space-y-1",children:[t("label",{className:"text-sm font-medium text-foreground",children:["Locais (",$.length,")"]}),a("select",{multiple:!0,value:$,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);V(a)},className:Fi("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:u.map(e=>a("option",{value:e.id,children:e.name},e.id))})]}),t("div",{className:"space-y-1",children:[t("label",{className:"text-sm font-medium text-foreground",children:["Colaboradores (",q.length,")"]}),a("select",{multiple:!0,value:q,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);W(a)},className:Fi("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:m.map(e=>a("option",{value:e.id,children:e.name},e.id))})]})]})]})]})]})}function Xg({dashboards:e,limit:r,generalView:n,language:i=kf.PtBr,isLoading:d=!1,canAdd:c=!1,canEdit:u=!1,canRemove:p=!1,canEditStandard:h=!1,activePanels:f=[],activePages:g=[],getPanelData:v,users:b=[],groups:x=[],places:y=[],collaborators:N=[],isSaving:w=!1,onOpen:_,onBackToList:C,onRefresh:k,onRefreshList:S,onToggleFavorite:A,onSave:E,onUpdate:D,onRemove:P,onDuplicate:I,onShare:T,onAddPanel:R,onEditPanel:M,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onSearch:U,onQuickFilterChange:j,onSetGeneralView:O,viewState:B,onViewStateChange:$,listToolbarExtra:V,viewToolbarActions:q,className:W}){const[H,G]=o({mode:"list"}),K=B??H,Y=l(e=>{$?$(e):G(e)},[$]),Q=s(()=>"view"===K.mode||"edit"===K.mode||"share"===K.mode?e.find(e=>e.id===K.dashboardId)??null:null,[e,K]),[X,J]=o(!1),[Z,ee]=o(g[0]?.id);m(()=>{g.length>0&&!Z&&ee(g[0]?.id)},[g,Z]),m(()=>{if("view"!==K.mode||!Q||Q.idViewType!==xf.Carousel||g.length<=1)return;const e=function(e){switch(e){case nf.FiveSeconds:return 5e3;case nf.TenSeconds:return 1e4;case nf.FifteenSeconds:return 15e3;case nf.ThirtySeconds:return 3e4;case nf.OneMinute:return 6e4;case nf.ThreeMinutes:return 18e4;case nf.FiveMinutes:return 3e5;case nf.TenMinutes:return 6e5;default:return 15e3}}(Q.idPageTime),a=setInterval(()=>{ee(e=>{const a=(g.findIndex(a=>a.id===e)+1)%g.length;return g[a]?.id})},e);return()=>clearInterval(a)},[K,Q,g]);const ae=l(e=>{Y({mode:"view",dashboardId:e.id}),ee(void 0),_?.(e)},[Y,_]),te=l(()=>{Y({mode:"list"}),J(!1),C?.()},[Y,C]),re=l(()=>{Y({mode:"create"})},[Y]),ne=l(e=>{Y({mode:"edit",dashboardId:e.id})},[Y]),ie=l(e=>{Y({mode:"share",dashboardId:e.id})},[Y]),oe=l(e=>{"edit"===K.mode||"share"===K.mode?D?.(K.dashboardId,e):E?.(e)},[K,E,D]),se=l(()=>{"edit"===K.mode||"share"===K.mode?Y({mode:"view",dashboardId:K.dashboardId}):Y({mode:"list"})},[K,Y]),le=l(()=>{Q&&A?.(Q)},[Q,A]),de=l(()=>{Q&&ne(Q)},[Q,ne]),ce=l(()=>{Q&&ie(Q)},[Q,ie]);return t("div",{className:Fi("flex flex-col h-full",W),children:["list"===K.mode&&a(qg,{dashboards:e,limit:r,isLoading:d,language:i,canAdd:c,canEdit:u,canRemove:p,onOpen:ae,onEdit:ne,onShare:ie,onDuplicate:I,onRemove:P,onAdd:re,onToggleFavorite:A,onRefresh:S,onSearch:U,onQuickFilterChange:j,toolbarExtra:V,className:"flex-1"}),"view"===K.mode&&Q&&t("div",{className:"flex flex-col h-full",children:[!X&&t("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:[t("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]}),n?.dashboardId===Q.id&&t("span",{className:"ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary",children:[t("svg",{className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),a("polyline",{points:"9 22 9 12 15 12 15 22"})]}),"Visão geral"]}),u&&O&&n?.dashboardId!==Q.id&&a("button",{onClick:()=>O(Q.id),className:"ml-auto text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Definir como visão geral"})]}),a(Og,{dashboard:Q,panels:f,pages:g,activePageId:Z,canEdit:u||h&&!!Q.isStandard,isFullscreen:X,isLoading:d,getPanelData:v,onRefresh:k,onToggleFullscreen:()=>J(e=>!e),onToggleFavorite:le,onEdit:de,onShare:ce,onAddPanel:R,onEditPanel:M,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onPageChange:ee,toolbarActions:q,className:"flex-1"})]}),"create"===K.mode&&t("div",{className:"flex flex-col h-full",children:[a("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:t("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]})}),a(Qg,{users:b,groups:x,places:y,collaborators:N,isSaving:w,onSave:oe,onCancel:se,className:"flex-1"})]}),("edit"===K.mode||"share"===K.mode)&&Q&&t("div",{className:"flex flex-col h-full",children:[a("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:t("button",{onClick:se,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"m15 18-6-6 6-6"})}),"Voltar"]})}),a(Qg,{dashboard:Q,initialTab:"share"===K.mode?Nf.Share:Nf.General,users:b,groups:x,places:y,collaborators:N,isSaving:w,isQualitfy:!!Q.isStandard&&!h,onSave:oe,onCancel:se,className:"flex-1"})]})]})}function Jg(){return`n_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Zg(e,a){return{id:a?.id??Jg(),text:e,children:a?.children,collapsed:a?.collapsed,color:a?.color,icon:a?.icon,note:a?.note,side:a?.side}}function ev(e,a){if(e.id===a)return{node:e,parent:null};const t=[];for(const r of e.children??[])t.push({node:r,parent:e});for(;t.length;){const e=t.pop();if(e.node.id===a)return{node:e.node,parent:e.parent};for(const a of e.node.children??[])t.push({node:a,parent:e.node})}return null}function av(e,a){const t=a(e);return t.children?.length?{...t,children:t.children.map(e=>av(e,a))}:t}function tv(e,a,t){return av(e,e=>e.id===a?t(e):e)}function rv(e){return{left:(e.children??[]).filter(e=>"left"===e.side).length,right:(e.children??[]).filter(e=>"left"!==e.side).length}}function nv(e,a,t){const r=Zg(t||"");let n=r.id;const i=av(e,t=>{if(t.id!==a)return t;let i=r;if(t.id===e.id){const a=rv(e);i={...i,side:a.left<=a.right?"left":"right"}}else i={...i,side:t.side};return n=i.id,{...t,collapsed:!1,children:[...t.children??[],i]}});return{root:i,newId:n}}function iv(e,a,t){if(e.id===a)return nv(e,a,t);const r=ev(e,a);if(!r||!r.parent)return{root:e,newId:a};const n=r.parent,i=Zg(t||"",{side:r.node.side}),o=i.id,s=av(e,e=>{if(e.id!==n.id)return e;const t=(e.children??[]).findIndex(e=>e.id===a),r=[...e.children??[]];return r.splice(t+1,0,i),{...e,children:r}});return{root:s,newId:o}}function ov(e,a){if(e.id===a)return{root:e,nextSelectedId:a};const t=ev(e,a);if(!t||!t.parent)return{root:e,nextSelectedId:null};const r=t.parent,n=r.children??[],i=n.findIndex(e=>e.id===a),o=n[i+1]?.id??n[i-1]?.id??r.id,s=av(e,e=>e.id!==r.id?e:{...e,children:(e.children??[]).filter(e=>e.id!==a)});return{root:s,nextSelectedId:o}}function sv(e,a,t){if(a===t)return e;if(a===e.id)return e;if(function(e,a,t){const r=ev(e,a);return!!r&&!!ev(r.node,t)}(e,a,t))return e;const r=ev(e,a);if(!r)return e;const n=(()=>{if(t===e.id){const a=rv(e);return{...r.node,side:a.left<=a.right?"left":"right"}}const a=ev(e,t)?.node;return{...r.node,side:a?.side}})(),i=av(e,e=>e.children?.length&&e.children.some(e=>e.id===a)?{...e,children:e.children.filter(e=>e.id!==a)}:e);return av(i,e=>e.id!==t?e:{...e,collapsed:!1,children:[...e.children??[],n]})}function lv(e,a){return tv(e,a,e=>({...e,collapsed:!e.collapsed}))}function dv(e,a){return av(e,t=>t.children?.length?t.id===e.id&&a?t:{...t,collapsed:a}:t)}function cv(e){const{value:a,defaultValue:t,onChange:r,readOnly:n}=e,i=void 0!==a,[d,c]=o(()=>t??a??Zg("Mapa Mental",{id:"root"})),m=i?a:d,[p,h]=o(m.id),f=u([]),g=u([]),v=l((e,a)=>{n||(f.current.push(a),f.current.length>50&&f.current.shift(),g.current=[],i||c(e),r?.(e))},[i,r,n]),b=l((e,a)=>{const t=tv(m,e,e=>({...e,text:a}));v(t,m)},[m,v]),x=l((e,a)=>{const t=tv(m,e,e=>({...e,...a}));v(t,m)},[m,v]),y=l((e,a="")=>{const{root:t,newId:r}=nv(m,e,a);return v(t,m),h(r),r},[m,v]),N=l((e,a="")=>{const{root:t,newId:r}=iv(m,e,a);return v(t,m),h(r),r},[m,v]),w=l(e=>{const{root:a,nextSelectedId:t}=ov(m,e);a!==m&&(v(a,m),h(t))},[m,v]),_=l((e,a)=>{const t=sv(m,e,a);t!==m&&v(t,m)},[m,v]),C=l(e=>{const a=ev(m,e);if(!a||!a.node.children?.length)return;const t=lv(m,e);v(t,m)},[m,v]),k=l(()=>{v(dv(m,!1),m)},[m,v]),S=l(()=>{v(dv(m,!0),m)},[m,v]),A=l(()=>{const e=f.current.pop();e&&(g.current.push(m),i||c(e),r?.(e))},[m,i,r]),E=l(()=>{const e=g.current.pop();e&&(f.current.push(m),i||c(e),r?.(e))},[m,i,r]),D=f.current.length>0,P=g.current.length>0,I=s(()=>p?ev(m,p)?.node??null:null,[m,p]),T=l(e=>{v(e,m)},[m,v]);return{root:m,setRoot:T,selectedId:p,selectedNode:I,setSelectedId:h,renameNode:b,updateNodeProps:x,addChild:y,addSibling:N,removeNode:w,moveNode:_,toggleNode:C,expandAll:k,collapseAll:S,undo:A,redo:E,canUndo:D,canRedo:P}}const uv=180,mv=80,pv=16,hv=60;function fv(e){const a=(e.collapsed?[]:e.children??[]).map(fv);if(!a.length)return{node:e,visibleChildren:a,height:44};const t=a.reduce((e,a)=>e+a.height,0)+pv*(a.length-1);return{node:e,visibleChildren:a,height:Math.max(44,t)}}function gv(e,a,t,r,n,i,o){const s=[],l={node:e.node,parent:a,x:t,y:r,width:180,height:44,side:n,depth:i,visibleChildren:s};if(o.push(l),!e.visibleChildren.length)return l;let d=r+22-(e.visibleChildren.reduce((e,a)=>e+a.height,0)+pv*(e.visibleChildren.length-1))/2;for(const c of e.visibleChildren){const a="right"===n?t+180+mv:t-mv-uv,r=d+c.height/2-22,l=gv(c,e.node,a,r,n,i+1,o);s.push(l),d+=c.height+pv}return l}function vv(e){return s(()=>function(e){const a=e.collapsed?[]:e.children??[],t=a.filter(e=>"left"!==e.side).map(fv),r=a.filter(e=>"left"===e.side).map(fv),n=t.reduce((e,a)=>e+a.height,0)+pv*Math.max(0,t.length-1),i=r.reduce((e,a)=>e+a.height,0)+pv*Math.max(0,r.length-1),o=Math.max(n,i,56),s=e=>e.visibleChildren.length?1+Math.max(...e.visibleChildren.map(s)):0,l=t.length?Math.max(...t.map(s))+1:0,d=260*(r.length?Math.max(...r.map(s))+1:0),c=220+260*l+d+120,u=o+120,m=hv+d,p=[],h={node:e,parent:null,x:m,y:hv+o/2-28,width:220,height:56,side:"root",depth:0,visibleChildren:[]};p.push(h);let f=hv+o/2-n/2;for(const b of t){const a=f+b.height/2-22,t=gv(b,e,m+220+mv,a,"right",1,p);h.visibleChildren.push(t),f+=b.height+pv}let g=hv+o/2-i/2;for(const b of r){const a=g+b.height/2-22,t=gv(b,e,m-mv-uv,a,"left",1,p);h.visibleChildren.push(t),g+=b.height+pv}const v=new Map(p.map(e=>[e.node.id,e]));return{nodes:p,byId:v,width:c,height:u}}(e),[e])}function bv(e,a){const{layout:t,selectedId:r,setSelectedId:n}=a;if(!r)return void n(t.nodes[0]?.node.id??null);const i=t.byId.get(r);if(!i)return;if("left"===e||"right"===e){if("root"===i.side){const a=i.visibleChildren.find(a=>a.side===e);return void(a&&n(a.node.id))}if(e===i.side){const e=i.visibleChildren[Math.floor(i.visibleChildren.length/2)];e&&n(e.node.id)}else i.parent&&n(i.parent.id);return}if(!i.parent)return;const o=t.byId.get(i.parent.id);if(!o)return;const s=o.visibleChildren.filter(e=>e.side===i.side),l=s.findIndex(e=>e.node.id===r),d="up"===e?s[l-1]:s[l+1];d&&n(d.node.id)}const xv=({layout:e,selected:r,editing:i,readOnly:o,onSelect:s,onStartEditing:l,onFinishEditing:d,onToggle:c,onDragStart:u,onDragOver:m,onDragLeave:p,onDrop:h,isDropTarget:f,renderNodeContent:g})=>{const v=e.node,b="root"===e.side,x=(y=v.icon)?S[y]??null:null;var y;const N=!!v.children?.length,w=n.useRef(null),[_,C]=n.useState(v.text);n.useEffect(()=>{if(i){C(v.text);const e=window.setTimeout(()=>{w.current?.focus(),w.current?.select()},0);return()=>window.clearTimeout(e)}},[i,v.text]);const k=()=>{d(_.trim()||v.text)},A=v.color;return t("div",{role:"treeitem","aria-selected":r,"aria-expanded":N?!v.collapsed:void 0,tabIndex:r?0:-1,"data-node-id":v.id,draggable:!o&&!b&&!i,onDragStart:u,onDragOver:m,onDragLeave:p,onDrop:h,onClick:e=>{e.stopPropagation(),s()},onDoubleClick:e=>{e.stopPropagation(),o||l()},className:Fi("absolute flex items-center gap-2 rounded-lg border bg-card text-card-foreground px-3 select-none transition-shadow","shadow-sm hover:shadow-md cursor-pointer",b&&"font-semibold border-primary/40 bg-primary text-primary-foreground",r&&!b&&"ring-2 ring-primary ring-offset-1",r&&b&&"ring-2 ring-primary-foreground/60 ring-offset-1",f&&"ring-2 ring-accent border-accent"),style:{left:e.x,top:e.y,width:e.width,height:e.height,backgroundColor:A},children:[x&&a(x,{className:Fi("h-4 w-4 shrink-0",b&&"text-primary-foreground")}),a("div",{className:"flex-1 min-w-0",children:i?a("input",{ref:w,value:_,onChange:e=>C(e.target.value),onBlur:k,onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),k()):"Escape"===e.key?(e.preventDefault(),d(null)):e.stopPropagation()},className:Fi("w-full bg-transparent outline-none text-sm",b&&"text-primary-foreground placeholder:text-primary-foreground/60")}):a("div",g?{className:"text-sm truncate",children:g(v)}:{className:"text-sm truncate",children:v.text||a("span",{className:"opacity-50",children:"—"})})}),v.note&&!i&&t(hs,{children:[a(fs,{asChild:!0,children:a("button",{type:"button",onClick:e=>e.stopPropagation(),className:Fi("shrink-0 rounded p-0.5 hover:bg-muted/40",b&&"hover:bg-primary-foreground/10"),"aria-label":v.note,children:a(Be,{className:"h-3.5 w-3.5 opacity-70"})})}),a(gs,{className:"max-w-xs whitespace-pre-line",children:v.note})]}),N&&a("button",{type:"button",onClick:e=>{e.stopPropagation(),c()},className:Fi("shrink-0 rounded-full border bg-background text-foreground h-5 w-5 flex items-center justify-center -mr-1","shadow-sm hover:bg-muted transition-colors",b&&"border-primary-foreground/30"),"aria-label":v.collapsed?"Expandir":"Colapsar",children:v.collapsed?a(Q,{className:"h-3 w-3"}):"left"===e.side?a(U,{className:"h-3 w-3 rotate-180"}):"right"===e.side?a(U,{className:"h-3 w-3"}):a(na,{className:"h-3 w-3"})})]})},yv=({parent:e,child:t})=>{const r=t.x+t.width/2<e.x+e.width/2,n=r?e.x:e.x+e.width,i=e.y+e.height/2,o=r?t.x+t.width:t.x,s=t.y+t.height/2,l=(n+o)/2;return a("path",{d:`M ${n} ${i} C ${l} ${i}, ${l} ${s}, ${o} ${s}`,fill:"none",stroke:"hsl(var(--border))",strokeWidth:2,strokeLinecap:"round"})},Nv=({label:e,icon:r,onClick:n,disabled:i})=>t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",onClick:n,disabled:i,"aria-label":e,className:"h-8 w-8",children:r})}),a(gs,{children:e})]}),wv=e=>{const{t:r}=Ga();return t("div",{className:"flex items-center gap-1 border-b bg-card px-2 py-1.5",children:[a(Nv,{label:r("mind_map_add_child"),icon:a(ia,{className:"h-4 w-4"}),onClick:e.onAddChild,disabled:!e.canAddChild}),a(Nv,{label:r("mind_map_add_sibling"),icon:a(Q,{className:"h-4 w-4"}),onClick:e.onAddSibling,disabled:!e.canAddSibling}),a(Nv,{label:r("mind_map_delete_node"),icon:a(H,{className:"h-4 w-4"}),onClick:e.onDelete,disabled:!e.canDelete}),a(Zi,{orientation:"vertical",className:"mx-1 h-5"}),a(Nv,{label:r("mind_map_expand_all"),icon:a(oa,{className:"h-4 w-4"}),onClick:e.onExpandAll}),a(Nv,{label:r("mind_map_collapse_all"),icon:a(sa,{className:"h-4 w-4"}),onClick:e.onCollapseAll}),a(Zi,{orientation:"vertical",className:"mx-1 h-5"}),a(Nv,{label:r("mind_map_zoom_out"),icon:a(la,{className:"h-4 w-4"}),onClick:e.onZoomOut}),a(Nv,{label:r("mind_map_zoom_in"),icon:a(da,{className:"h-4 w-4"}),onClick:e.onZoomIn}),a(Nv,{label:r("mind_map_fit_to_screen"),icon:a(ca,{className:"h-4 w-4"}),onClick:e.onFit}),a(Zi,{orientation:"vertical",className:"mx-1 h-5"}),a(Nv,{label:r("mind_map_undo"),icon:a(ua,{className:"h-4 w-4"}),onClick:e.onUndo,disabled:!e.canUndo}),a(Nv,{label:r("mind_map_redo"),icon:a(ma,{className:"h-4 w-4"}),onClick:e.onRedo,disabled:!e.canRedo}),a("div",{className:"flex-1"}),a(Nv,{label:r("mind_map_export_json"),icon:a(Je,{className:"h-4 w-4"}),onClick:e.onExportJson}),a(Nv,{label:r("mind_map_export_image"),icon:a(Ve,{className:"h-4 w-4"}),onClick:e.onExportImage})]})};function _v(e){return JSON.stringify(e,null,2)}function Cv(e){if(!e||"object"!=typeof e)throw new Error("Invalid mind map node: not an object");const a=e;if("string"!=typeof a.text)throw new Error('Invalid mind map node: missing "text"');const t=Array.isArray(a.children)?a.children.map(e=>Cv(e)):void 0;return Zg(a.text,{id:"string"==typeof a.id?a.id:void 0,collapsed:"boolean"==typeof a.collapsed?a.collapsed:void 0,color:"string"==typeof a.color?a.color:void 0,icon:"string"==typeof a.icon?a.icon:void 0,note:"string"==typeof a.note?a.note:void 0,side:"left"===a.side||"right"===a.side?a.side:void 0,children:t})}function kv(e){return Cv(JSON.parse(e))}const Sv=({value:e,defaultValue:r,onChange:i,onNodeSelect:s,readOnly:d=!1,hideToolbar:c=!1,extraShortcuts:p,renderNodeContent:h,className:f,height:g=600})=>{const{t:v}=Ga(),b=cv({value:e,defaultValue:r,onChange:i,readOnly:d}),x=vv(b.root),y=function(){const[e,a]=o({x:0,y:0,scale:1}),t=u(!1),r=u({x:0,y:0,tx:0,ty:0}),n=l(a=>{0!==a.button&&1!==a.button||(t.current=!0,r.current={x:a.clientX,y:a.clientY,tx:e.x,ty:e.y},a.currentTarget.setPointerCapture(a.pointerId))},[e.x,e.y]),i=l(e=>{t.current&&a(a=>({...a,x:r.current.tx+(e.clientX-r.current.x),y:r.current.ty+(e.clientY-r.current.y)}))},[]),s=l(e=>{if(t.current){t.current=!1;try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}}},[]),d=l((e,t,r)=>{a(a=>{const n=Math.min(2.5,Math.max(.3,a.scale+e));if(n===a.scale)return a;if(void 0===t||void 0===r)return{...a,scale:n};const i=n/a.scale;return{scale:n,x:t-(t-a.x)*i,y:r-(r-a.y)*i}})},[]),c=l(()=>d(.15),[d]),p=l(()=>d(-.15),[d]),h=l(()=>a({x:0,y:0,scale:1}),[]),f=l((e,t,r,n)=>{const i=Math.min((r-64)/e,(n-64)/t,1.5),o=Math.max(.3,i);a({scale:o,x:(r-e*o)/2,y:(n-t*o)/2})},[]),g=l(e=>{if(!e.ctrlKey&&!e.metaKey)return;e.preventDefault();const a=e.currentTarget.getBoundingClientRect(),t=e.clientX-a.left,r=e.clientY-a.top;d(e.deltaY>0?-.1:.1,t,r)},[d]);return m(()=>{const e=()=>t.current=!1;return window.addEventListener("pointerup",e),()=>window.removeEventListener("pointerup",e)},[]),{transform:e,setTransform:a,zoomIn:c,zoomOut:p,reset:h,fitTo:f,onBackgroundPointerDown:n,onPointerMove:i,onPointerUp:s,onWheel:g}}(),N=n.useRef(null),w=n.useRef(null),_=n.useRef(null),[C,k]=n.useState(null),[S,A]=n.useState(null);n.useEffect(()=>{s?.(b.selectedNode)},[b.selectedNode,s]),function({api:e,layout:a,containerRef:t,onStartEditing:r,readOnly:n,extraShortcuts:i}){m(()=>{const o=o=>{const s=t.current;if(!s)return;if(!s.contains(document.activeElement))return;const l=o.target;if(l?.isContentEditable)return;if(l&&("INPUT"===l.tagName||"TEXTAREA"===l.tagName))return;const d={layout:a,selectedId:e.selectedId,setSelectedId:e.setSelectedId},c=e.selectedId;for(const a of i??[])if(a.key.toLowerCase()===o.key.toLowerCase()&&!!a.ctrl===(o.ctrlKey||o.metaKey)&&!!a.shift===o.shiftKey&&!!a.alt===o.altKey)return o.preventDefault(),void a.handler({selectedId:e.selectedId,root:e.root,setRoot:e.setRoot,select:e.setSelectedId});if((o.ctrlKey||o.metaKey)&&"z"===o.key.toLowerCase())return o.preventDefault(),void(o.shiftKey?e.redo():e.undo());if("ArrowUp"===o.key)return o.preventDefault(),void bv("up",d);if("ArrowDown"===o.key)return o.preventDefault(),void bv("down",d);if("ArrowLeft"===o.key)return o.preventDefault(),void bv("left",d);if("ArrowRight"===o.key)return o.preventDefault(),void bv("right",d);if(c){if(" "===o.key)return o.preventDefault(),void e.toggleNode(c);if("F2"===o.key){if(n)return;return o.preventDefault(),void r(c)}if(!n){if("Enter"===o.key&&!o.shiftKey)return o.preventDefault(),c===e.root.id?e.addChild(c,""):e.addSibling(c,""),void setTimeout(()=>{e.selectedId&&r(e.selectedId)},0);if("Insert"===o.key||"Tab"===o.key)return o.preventDefault(),e.addChild(c,""),void setTimeout(()=>{e.selectedId&&r(e.selectedId)},0);if("Delete"===o.key||"Backspace"===o.key){if(c===e.root.id)return;return o.preventDefault(),void e.removeNode(c)}}}};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[e,a,t,r,n,i])}({api:b,layout:x,containerRef:N,onStartEditing:e=>{d||k(e)},readOnly:d,extraShortcuts:p});const E=n.useRef(!1);n.useEffect(()=>{if(E.current)return;const e=w.current;if(!e)return;const{clientWidth:a,clientHeight:t}=e;a>0&&t>0&&x.width>0&&(y.fitTo(x.width,x.height,a,t),E.current=!0)},[x.width,x.height,y]);const D=b.selectedId,P=b.selectedNode,I=D===b.root.id,T=n.useRef(null),R=e=>a=>{if(d)return;const t=T.current;if(!t||t===e)return;const r=ev(b.root,t);r&&ev(r.node,e)||(a.preventDefault(),a.dataTransfer.dropEffect="move",A(e))},M=()=>A(null),L=e=>a=>{a.preventDefault();const t=T.current;A(null),T.current=null,t&&t!==e&&b.moveNode(t,e)};return a(ps,{children:t("div",{ref:N,tabIndex:0,role:"tree","aria-label":v("mind_map_aria_label"),className:Fi("relative flex flex-col rounded-lg border bg-muted/20 overflow-hidden focus:outline-none",f),style:{height:g},onClick:()=>N.current?.focus(),children:[!c&&a(wv,{canAddChild:!!P&&!d,canAddSibling:!!P&&!d,canDelete:!!P&&!I&&!d,canUndo:b.canUndo&&!d,canRedo:b.canRedo&&!d,onAddChild:()=>{if(!D)return;const e=b.addChild(D,"");k(e)},onAddSibling:()=>{if(!D)return;if(I){const e=b.addChild(D,"");return void k(e)}const e=b.addSibling(D,"");k(e)},onDelete:()=>{D&&!I&&b.removeNode(D)},onExpandAll:b.expandAll,onCollapseAll:b.collapseAll,onFit:()=>{const e=w.current;e&&y.fitTo(x.width,x.height,e.clientWidth,e.clientHeight)},onZoomIn:y.zoomIn,onZoomOut:y.zoomOut,onUndo:b.undo,onRedo:b.redo,onExportJson:()=>{!function(e,a,t="application/json"){const r=new Blob([e],{type:t}),n=URL.createObjectURL(r),i=document.createElement("a");i.href=n,i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(n)}(_v(b.root),"mind-map.json")},onExportImage:async()=>{if(_.current)try{await async function(e,a="mind-map.png"){const t=e.cloneNode(!0),r=(new XMLSerializer).serializeToString(t),n=`data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(r)))}`,i=new Image;await new Promise((e,a)=>{i.onload=()=>e(),i.onerror=()=>a(new Error("Failed to load SVG snapshot")),i.src=n});const o=e.clientWidth||Number(e.getAttribute("width"))||1200,s=e.clientHeight||Number(e.getAttribute("height"))||800,l=document.createElement("canvas");l.width=2*o,l.height=2*s;const d=l.getContext("2d");if(!d)throw new Error("Canvas 2D context unavailable");d.fillStyle="#ffffff",d.fillRect(0,0,l.width,l.height),d.drawImage(i,0,0,l.width,l.height);const c=await new Promise(e=>l.toBlob(e,"image/png"));if(!c)throw new Error("Failed to create PNG blob");const u=URL.createObjectURL(c),m=document.createElement("a");m.href=u,m.download=a,document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(u)}(_.current,"mind-map.png")}catch(e){}}}),a("div",{ref:w,className:"relative flex-1 overflow-hidden cursor-grab active:cursor-grabbing",onPointerDown:e=>{e.target===e.currentTarget&&(y.onBackgroundPointerDown(e),b.setSelectedId(null))},onPointerMove:y.onPointerMove,onPointerUp:y.onPointerUp,onWheel:y.onWheel,children:t("div",{className:"absolute origin-top-left",style:{transform:`translate(${y.transform.x}px, ${y.transform.y}px) scale(${y.transform.scale})`,width:x.width,height:x.height},children:[a("svg",{ref:_,width:x.width,height:x.height,className:"absolute inset-0 pointer-events-none",xmlns:"http://www.w3.org/2000/svg",children:x.nodes.map(e=>e.visibleChildren.map(t=>a(yv,{parent:e,child:t},`${e.node.id}-${t.node.id}`)))}),x.nodes.map(e=>{return a(xv,{layout:e,selected:D===e.node.id,editing:C===e.node.id,readOnly:d,onSelect:()=>b.setSelectedId(e.node.id),onStartEditing:()=>k(e.node.id),onFinishEditing:a=>{null!==a&&b.renameNode(e.node.id,a),k(null)},onToggle:()=>b.toggleNode(e.node.id),onDragStart:(t=e.node.id,e=>{d||t===b.root.id||(T.current=t,e.dataTransfer.setData("text/plain",t),e.dataTransfer.effectAllowed="move")}),onDragOver:R(e.node.id),onDragLeave:M,onDrop:L(e.node.id),isDropTarget:S===e.node.id,renderNodeContent:h},e.node.id);var t})]})})]})})},Av=({manager:n,columns:i,onEdit:o,onView:s,onToggleStatus:l,onDelete:d,renderActions:c,customRowActions:u,enableBulkActions:p=!1,onNew:h,newButtonLabel:f,showNewButton:g=!0,customActions:v=[],hideActionBar:b,showActionBar:x=!0,showSearch:y=!1,searchValue:N,onSearchChange:w,searchPlaceholder:_,bulkActions:C=[],onBulkDelete:k,filters:S,gridColumns:A=3,renderCard:E,viewMode:D,onViewModeChange:P,listCardRenderer:I,gridCardRenderer:T,showViewToggle:R=!1})=>{const{setSearchVisible:M}=kl(),L=void 0!==b?!b:x;m(()=>{if(!y)return M(!0),()=>M(!1)},[M,y]);const z=h||v.length>0||y||p||S||R,F=k||(()=>{n.bulkDelete?.(n.selectedIds)}),U=D||"grid",j="list"===U,O={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[j?1:A],B=L&&z?a(bd,{onNew:h,newButtonLabel:f,showNewButton:g,showSearch:y,searchValue:N,onSearchChange:w,searchPlaceholder:_,showBulkActions:p,selectedCount:n.selectedIds.length,bulkActions:C,onBulkDelete:F,onClearSelection:n.clearSelection,customActions:v,filters:S,viewMode:U,onViewModeChange:P,showViewToggle:R,availableViewModes:["list","grid"]}):null;return n.isLoading?t("div",{className:"flex flex-col h-full",children:[B,a("div",{className:"flex-1 overflow-auto p-4",children:a(jl,{count:6})})]}):0===n.entities.length?t("div",{className:"flex flex-col h-full",children:[B,a("div",{className:"flex-1 flex items-center justify-center",children:a(ql,{title:e.t("no_items_found_empty"),description:e.t("no_data_to_display"),variant:"search"})})]}):t("div",{className:"flex flex-col h-full",children:[B,a("div",{className:"flex-1 overflow-auto p-4",children:a("div",{className:Fi("grid gap-4",O),children:n.entities.map(e=>{const m=(e=>{const{t:a}=Ga();return j&&I?I(e):!j&&T?T(e):E?E(e):null})(e);return t(Gl,{children:[a(Kl,{asChild:!0,children:m?a("div",{className:"cursor-pointer",onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):o?.(e)},children:m}):a(Gi,{className:Fi("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",p&&n.selectedIds.includes(e.id)&&"bg-muted ring-2 ring-primary",j&&"flex-row"),onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):o?.(e)},children:t(Xi,{className:Fi("p-4",j&&"flex items-center gap-4 w-full"),children:[p&&a("div",{className:Fi(j?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:a(xd,{checked:n.selectedIds.includes(e.id),onCheckedChange:()=>n.selectItem(e.id)})}),j?t(r,{children:[a("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:i.map(r=>t("div",{className:"flex items-center gap-2 min-w-0",children:[t("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[r.header,":"]}),a("div",{className:"text-sm text-foreground truncate",children:r.render?r.render(e):String(e[r.key]??"")})]},String(r.key)))}),(o||s||c)&&a("div",{onClick:e=>e.stopPropagation(),children:c?c(e):a(dd,{onEdit:o?()=>o(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,customActions:u?u(e):[]})})]}):t("div",{className:"flex items-start gap-3",children:[p&&a("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:a(xd,{checked:n.selectedIds.includes(e.id),onCheckedChange:()=>n.selectItem(e.id)})}),t("div",{className:"flex-1 min-w-0",children:[i.map((r,n)=>t("div",{className:Fi("flex justify-between items-start gap-2",n!==i.length-1&&"mb-2"),children:[t("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[r.header,":"]}),a("div",{className:"text-sm text-foreground text-right truncate",children:r.render?r.render(e):String(e[r.key]??"")})]},String(r.key))),(o||s||c)&&a("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(e):a(dd,{onEdit:o?()=>o(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,customActions:u?u(e):[]})})]})]})]})})}),a(ad,{className:"w-[160px]",children:a(ld,{onEdit:o?()=>o(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,canDelete:!!d,customActions:u?u(e):[],renderAs:"context"})})]},e.id)})})})]})};function Ev({data:e,columns:r,sortField:n,sortDirection:d,onSort:c,onRowClick:u,renderActions:m,isLoading:p=!1,emptyMessage:h,className:f,enableSelection:g=!1,selectedIds:v=[],onSelectItem:b,onSelectAll:x,isAllSelected:y=!1,enableColumnResize:N=!0,onColumnResize:w,enableColumnReorder:_=!1,onReorderColumns:C,storageKey:k,enableExpandableRows:S=!1,renderExpandedContent:A,expandedRowIds:E,onToggleExpand:P,defaultExpandAll:I=!1,rowActionsVariant:T="default",hideActionsColumn:R=!1,actionsHeaderContent:M}){const{t:L}=Ga(),z=h||L("no_items_found",L("no_items_found_empty")),[F,j]=o(()=>I?new Set(e.map(e=>e.id)):new Set),O=void 0!==E,B=O?new Set(E):F,$=l(e=>{O&&P?P(e):j(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[O,P]),{columnWidths:V,isDragging:q,activeColumn:W,handleMouseDown:H}=md({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:k?`${k}-columns`:void 0,onResize:w,enabled:N}),G=wd({enabled:_&&!!C,onReorder:C??(()=>{})}),K=s(()=>{if(N){const e=r.map(e=>V[String(e.key)]??e.width??e.minWidth??150),a=e.reduce((e,a)=>e+a,0);return e.map(e=>e/a*100+"%")}const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.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}%`})},[r,N,V]);if(p)return a("div",{className:"flex-1 overflow-auto",children:a("div",{className:"p-4 space-y-3",children:[...Array(5)].map((e,t)=>a(Ps,{className:"h-12 w-full"},t))})});if(0===e.length)return a("div",{className:"flex-1 flex items-center justify-center",children:a("div",{className:"text-center text-muted-foreground",children:a("p",{children:z})})});const Y=m&&!R,Q=(g?1:0)+(S?1:0)+r.length+(Y?1:0);return a("div",{className:"flex-1 overflow-auto "+(q?"select-none":""),children:t(Pl,{className:Fi("table-fixed w-full",f),children:[a(Il,{className:"sticky top-0 bg-background z-10",children:t(Ml,{children:[S&&a(Ll,{className:"w-[40px]"}),g&&a(Ll,{className:"w-[40px]",children:a(qo,{checked:y,onCheckedChange:x,"aria-label":L("select_all","Selecionar todos")})}),r.map((e,r)=>{const i=N&&!1!==e.resizable,o=W===String(e.key),s=_&&!!C,l=s?G.getDragProps(r):{},u=G.dragFromIndex===r,m=G.dragOverIndex===r&&G.dragFromIndex!==r;return t(Ll,{className:Fi(e.className,"relative transition-opacity",e.sortable&&"cursor-pointer",s&&G.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:K[r]},...l,children:[!1!==e.sortable&&c?t("button",{onClick:()=>c(String(e.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[e.header,(p=String(e.key),n!==p?null:a("asc"===d?re:ne,{size:14,className:"ml-1"}))]}):a("span",{className:"font-medium",children:e.header}),i&&a(Hl,{direction:"horizontal",onMouseDown:a=>H(String(e.key),a),isDragging:o})]},String(e.key));var p}),Y&&a(Ll,{className:"w-[80px] text-right",children:M??L("actions","Ações")})]})}),a(Tl,{children:e.map(e=>{const n=S&&B.has(e.id);return t(i.Fragment,{children:[t(Ml,{onClick:()=>u?.(e),className:Fi(u?"cursor-pointer":"","relative","inline"===T&&"group"),children:[S&&a(zl,{className:"w-[40px] px-2",children:a("button",{onClick:a=>{a.stopPropagation(),$(e.id)},className:"p-1 rounded-sm hover:bg-muted transition-colors","aria-label":n?L("collapse_row","Recolher linha"):L("expand_row","Expandir linha"),children:a(n?D:U,{size:16,className:"text-muted-foreground"})})}),g&&a(zl,{children:a(qo,{checked:v.includes(e.id),onCheckedChange:()=>b?.(e.id),onClick:e=>e.stopPropagation(),"aria-label":`${L("select_all","Selecionar todos")} ${e.id}`})}),r.map(t=>a(zl,{className:t.className,children:a(Wl,{children:t.render?t.render(e):String(e[t.key]??"-")})},String(t.key))),Y&&a(zl,{className:"text-right",onClick:e=>e.stopPropagation(),children:"inline"===T?a("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:m(e)}):m(e)})]}),n&&A&&a(Ml,{className:"bg-muted/30 hover:bg-muted/30",children:a(zl,{colSpan:Q,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:A(e)})})})]},e.id)})})]})})}function Dv({onEdit:e,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:o=!0,canDelete:l=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=Ga(),p=s(()=>{const a=[];return e&&o&&a.push({key:"edit",icon:V,label:m("edit","Editar"),onClick:e,variant:"default"}),n&&a.push({key:"toggle-status",icon:i?q:W,label:i?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),d.forEach(e=>{!1!==e.show&&a.push({key:`custom-${e.label}`,icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default",disabled:e.disabled,disabledReason:e.disabledReason})}),r&&l&&a.push({key:"delete",icon:H,label:m("remove","Remover"),onClick:r,variant:"destructive"}),a},[e,r,n,i,o,l,d,m]);return 0===p.length?null:"dropdown"===c?a(ps,{delayDuration:200,children:t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:a(A,{size:"compact"===u?14:16})})}),a(os,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(e=>e.disabled?t(vs,{disabledReason:e.disabledReason,className:"destructive"===e.variant?"text-destructive":"",children:[e.icon&&a(e.icon,{className:"mr-2 h-4 w-4"}),e.label]},e.key):t(ss,{onClick:e.onClick,className:"destructive"===e.variant?"text-destructive":"",children:[e.icon&&a(e.icon,{className:"mr-2 h-4 w-4"}),e.label]},e.key))})]})}):a("div",{className:"flex items-center gap-1",children:p.map(e=>t($i,{variant:"destructive"===e.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:e.onClick,className:"compact"===u?"h-7 px-2":"",children:[e.icon&&a(e.icon,{size:"compact"===u?14:16}),"compact"!==u&&a("span",{className:"ml-1",children:e.label})]},e.key))})}function Pv({searchValue:e="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:o=!0,layout:s="horizontal"}){const{t:l}=Ga(),d=e||n.length>0;return t("div",{className:`flex ${"vertical"===s?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&t("div",{className:"relative flex-1 min-w-[200px]",children:[a(B,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{type:"text",placeholder:l("search","Pesquisar"),value:e,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((e,t)=>a("div",{className:"vertical"===s?"w-full":"",children:e},t)),o&&d&&i&&t($i,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[a(E,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function Iv(e,a){const{t:t}=Ga(),r=new Set;function n(e){if(e)for(const a of e)r.add(a.id),n(a.children)}return function e(t){for(const r of t){if(r.id===a)return n(r.children),!0;if(r.children&&e(r.children))return!0}return!1}(e),r}function Tv({children:e,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:o,onDropCell:s,className:l}){return a(zl,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},className:l,children:e})}function Rv({item:e,level:n,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:d,onRowClick:c,renderActions:u,rowActionsVariant:m="default",enableSelection:p,selectedIds:h,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:x,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:_}){const C=l.has(e.id),k=(e.children?.length??0)>0,S=24*n,A="inline"===m,E=v===e.id||h?.has(e.id)&&v&&h?.has(v),P=b===e.id&&v!==e.id,I=h?.has(e.id)??!1,T={itemId:e.id,enableDrag:g,onDragStartCell:x,onDragEndCell:y,onDragOverCell:N,onDropCell:w};return t(r,{children:[t(Ml,{className:Fi(c&&"cursor-pointer",A&&"group",E&&"opacity-40",P&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:c?()=>c(e):void 0,children:[a(Tv,{...T,children:t("div",{className:"flex items-center gap-2",style:{paddingLeft:`${S}px`},children:[p&&a(qo,{checked:I,onCheckedChange:()=>f?.(e.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),g&&a("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),k?a("button",{onClick:a=>{a.stopPropagation(),d(e.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:a(C?D:U,{className:"h-4 w-4"})}):a("div",{className:"w-6 shrink-0"}),s??a(ge,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"truncate",children:String(e[o]??e.id)}),v===e.id&&_&&_>1&&a("span",{className:"ml-1 inline-flex items-center rounded-full bg-primary px-1.5 py-0 text-xs font-semibold text-primary-foreground",children:_})]})}),i.map(r=>{const i=e[r.key],o=r.render?r.render(e,n):null!=i?String(i):"—";return a(Tv,{...T,className:Fi("text-center",r.className),children:r.hoverContent?t(Hu,{openDelay:200,children:[a(Gu,{asChild:!0,children:a("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:o})}),a(Ku,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:r.hoverContent(e)})]}):o},String(r.key))}),u&&a(Tv,{...T,className:"text-right",children:a("div",{onClick:e=>e.stopPropagation(),className:Fi("flex items-center justify-end gap-1",A&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(e)})})]}),k&&C&&e.children.map(e=>a(Rv,{item:e,level:n+1,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:d,onRowClick:c,renderActions:u,rowActionsVariant:m,enableSelection:p,selectedIds:h,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:x,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:_},e.id))]})}function Mv({onDrop:r,isDragOver:n,onDragOver:i,onDragLeave:o,label:s}){return t("div",{className:Fi("absolute top-0 left-0 right-0 z-10 flex items-center justify-center gap-2 py-2 px-4 border-2 border-dashed rounded-md text-sm transition-colors mx-2 mt-2",n?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:i,onDragEnter:i,onDragLeave:o,onDrop:r,children:[a(pa,{className:"h-4 w-4"}),s??e.t("leadership_make_root_short")]})}function Lv({data:r,columns:n,nameKey:s,nameHeader:d=e.t("ap_name"),iconComponent:c,expandedIds:m,onToggleExpand:p,onRowClick:h,renderActions:f,actionsHeader:g="",rowActionsVariant:v="default",isLoading:b,emptyMessage:x="Nenhum registro encontrado.",className:y,enableSelection:N,selectedIds:w,onSelectItem:_,onSelectAll:C,isAllSelected:k,enableRowDrag:S,onMoveNode:A,onMoveNodes:E,rootDropLabel:D,actionsWidth:P=20,nameMinWidth:I=200}){const[T,R]=o(null),[M,L]=o(null),[z,F]=o(!1),[U,j]=o(1),O=u(null),B=u([]),$=u(null),V=i.useMemo(()=>new Set(w??[]),[w]),q=i.useMemo(()=>{if(!T||!r)return new Set;const e=B.current.length>0?B.current:[T],a=function(e,a){const{t:t}=Ga(),r=new Set;for(const n of a)Iv(e,n).forEach(e=>r.add(e));return r}(r,e);return e.forEach(e=>a.add(e)),a},[T,r]),W=u(q);W.current=q;const H=l(()=>{O.current=null,B.current=[],$.current=null,R(null),L(null),F(!1),j(1)},[]),G=l((e,a)=>{e.length>1&&E?E(e,a):1===e.length&&A?.(e[0],a)},[A,E]),K=l((e,a)=>{const t=V.has(e)&&V.size>1?Array.from(V):[e];O.current=e,B.current=t,$.current=null,R(e),j(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[V]),Y=l((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",W.current.has(e)?L(null):($.current=e,L(e))},[]),Q=l((e,a)=>{a.preventDefault(),a.stopPropagation();const t=W.current.has(e)?$.current:e;if(!t)return void H();let r=B.current;if(0===r.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(r=a)}}catch{}if(0===r.length){const e=a.dataTransfer.getData("text/plain");e&&(r=[e])}}0===r.length||r.includes(t)||G(r,t),H()},[G,H]),X=l(e=>{e.preventDefault(),e.stopPropagation();let a=B.current;if(0===a.length){try{const t=e.dataTransfer.getData("application/x-tree-ids");if(t){const e=JSON.parse(t);Array.isArray(e)&&e.length>0&&(a=e)}}catch{}if(0===a.length){const t=e.dataTransfer.getData("text/plain");t&&(a=[t])}}0!==a.length?(G(a,null),H()):H()},[G,H]),J=l(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",F(!0)},[]),Z=l(e=>{S&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[S]),ee=l(e=>{if(!S)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??$.current;t&&Q(t,e)},[S,Q]);if(b)return a("div",{className:"flex items-center justify-center py-12",children:t("div",{className:"text-center space-y-2",children:[a("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),a("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(!r||0===r.length)return t("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[a(ge,{className:"h-10 w-10 text-muted-foreground/50"}),a("p",{className:"text-sm text-muted-foreground",children:x})]});const ae=null!==T;return t("div",{className:Fi("border rounded-lg overflow-hidden relative",y),onDragOver:Z,onDrop:ee,onDragLeave:S?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(L(null),F(!1))}:void 0,children:[S&&ae&&a(Mv,{onDrop:X,isDragOver:z,onDragOver:J,onDragLeave:()=>F(!1),label:D}),t(Pl,{children:[a(Il,{children:t(Ml,{children:[a(Ll,{className:"text-left",style:{minWidth:I},children:t("div",{className:"flex items-center gap-2",children:[N&&a(qo,{checked:k??!1,onCheckedChange:()=>C?.()}),d]})}),n.map(e=>a(Ll,{className:Fi("text-center",e.className),style:e.width?{width:e.width}:void 0,children:e.header},String(e.key))),f&&a(Ll,{className:"text-right",style:{width:P},children:g})]})}),a(Tl,{children:r.map(e=>a(Rv,{item:e,level:0,columns:n,nameKey:s,iconComponent:c,expandedIds:m,onToggleExpand:p,onRowClick:h,renderActions:f,rowActionsVariant:v,enableSelection:N,selectedIds:V,onSelectItem:_,enableRowDrag:S,draggedId:T,dragOverId:M,onDragStartCell:K,onDragEndCell:H,onDragOverCell:Y,onDropCell:Q,dragCount:U},e.id))})]})]})}function zv(e){const a=nt();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function Fv(e,a){const t=zv({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Uv=[{value:"pt-BR",label:"Português (Brasil)"},{value:"en-US",label:"English (US)"},{value:"es-ES",label:"Español"}],jv=({open:e,onOpenChange:r,user:n,userPhotoUrl:i,userInitials:s})=>{const{t:l,i18n:d}=Ga(),c=u(null),[m,p]=o(null),[h,f]=o(d.language||"pt-BR"),g=m||i,v=e=>{e||(p(null),f(d.language||"pt-BR")),r(e)};return a(mo,{open:e,onOpenChange:v,children:t(bo,{className:"sm:max-w-md",children:[a(xo,{children:a(wo,{children:l("edit_profile","Editar Perfil")})}),t("div",{className:"space-y-6 py-4",children:[t("div",{className:"flex items-center gap-4",children:[a("div",{className:"relative flex-shrink-0",children:t(bu,{className:"w-24 h-24",children:[g&&a(xu,{src:g,alt:n.name||""}),a(yu,{className:"bg-primary text-primary-foreground font-semibold text-2xl",children:s})]})}),t("div",{className:"space-y-1",children:[n.name&&a("p",{className:"text-base font-semibold",children:n.name}),n.email&&a("p",{className:"text-sm text-muted-foreground",children:n.email}),t($i,{variant:"outline",size:"sm",onClick:()=>c.current?.click(),children:[a(ha,{className:"mr-2 h-4 w-4"}),l("change_photo","Trocar foto")]}),a("input",{ref:c,type:"file",accept:"image/*",className:"hidden",onChange:e=>{const a=e.target.files?.[0];if(!a)return;const t=URL.createObjectURL(a);p(t)}})]})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:l("language","Idioma")}),t(Mo,{value:h,onValueChange:f,children:[a(Fo,{children:a(zo,{})}),a(Oo,{children:Uv.map(e=>a($o,{value:e.value,children:e.label},e.value))})]})]})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>v(!1),children:l("cancel","Cancelar")}),a($i,{onClick:()=>{h!==d.language&&d.changeLanguage(h),r(!1)},children:l("save","Salvar")})]})]})})},Ov="true"===import.meta.env.VITE_SHOW_EDIT_PROFILE,Bv=i.memo(({variant:e="card",className:n="",selectedUnit:l,onUnitChange:d})=>{const{t:c}=Ga(),{user:u,companies:m,alias:p,isAuthenticated:h,logout:f,switchUnit:g}=kl(),{role:v}=au(),b=v?.name||null,x=m?.[0]||null,y=p?m?.find(e=>e.alias===p):x,N=m||[],w=l||y||x||x,_=s(()=>{if(!u?.id)return null;const e=(new Date).toISOString().slice(0,10);return`https://login-api.qualiex.com/api/Users/Photo/${u.id}/${e}/1?size=48`},[u?.id]),C=s(()=>{if(!u?.name)return"";const e=u.name.trim().split(/\s+/);return 1===e.length?e[0].charAt(0).toUpperCase():(e[0].charAt(0)+e[e.length-1].charAt(0)).toUpperCase()},[u?.name]),k=i.useCallback(e=>{d?d(e):g(e)},[d,g]),S=i.useMemo(()=>{if(!N?.length)return[];const e=new Map;N.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===w?.alias),r=a.filter(e=>e.alias!==w?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[N,w?.alias]),[A,E]=o(!1);if(!h||!u)return null;return"dropdown"===e?t(r,{children:[t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",className:`h-auto p-2 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10 ${n}`,children:t("div",{className:"flex items-center space-x-2",children:[t("div",{className:"hidden md:block text-right",children:[t("p",{className:"text-sm font-medium",children:[u.name?.split(" ")[0],b?` [${b}]`:""]}),a("p",{className:"text-xs text-primary-foreground/70",children:w?.name||"N/A"})]}),t(bu,{className:"w-8 h-8 border border-primary-foreground/30",children:[_&&a(xu,{src:_,alt:u.name||c("user_photo")}),a(yu,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:C||a(ge,{className:"h-4 w-4"})})]}),a(D,{className:"h-4 w-4"})]})})}),t(os,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[t(ts,{children:[t(ns,{children:[a(ue,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),a(is,{children:S.map(e=>t(ss,{onClick:()=>k(e),className:e.alias===w?.alias?"bg-muted":"",children:[a(fe,{className:"mr-2 h-4 w-4"}),e.name,e.alias===w?.alias&&a(Go,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},e.alias))})]}),Ov&&t(r,{children:[a(us,{}),t(ss,{onClick:()=>E(!0),children:[a(fa,{className:"mr-2 h-4 w-4"}),c("edit_profile","Editar Perfil")]})]}),a(us,{}),t(ss,{onClick:f,children:[a(ve,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}),Ov&&a(jv,{open:A,onOpenChange:E,user:u,userPhotoUrl:_,userInitials:C})]}):t(Gi,{className:n,children:[a(Ki,{children:a(Yi,{className:"text-lg",children:c("user_info")})}),t(Xi,{className:"space-y-4",children:[a(()=>t(r,{children:[t("div",{className:"flex items-center space-x-3",children:[a("div",{className:"flex-shrink-0",children:t(bu,{className:"w-10 h-10",children:[_&&a(xu,{src:_,alt:u.name||c("user_photo")}),a(yu,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:C||a(ge,{className:"h-5 w-5"})})]})}),t("div",{className:"flex-1 min-w-0",children:[a("p",{className:"text-sm font-medium truncate",children:u.name}),t("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",w?.name||"N/A"]})]})]}),w&&a("div",{className:"mt-3",children:t("div",{className:"flex items-center space-x-2",children:[a(fe,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:w.name})]})}),S.length>1&&t("div",{className:"mt-2",children:[t("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",S.length]}),t("div",{className:"flex flex-wrap gap-1",children:[S.slice(0,3).map(e=>a(Go,{variant:e.alias===w?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>k(e),children:e.name},e.alias)),S.length>3&&t(Go,{variant:"outline",className:"text-xs",children:["+",S.length-3]})]})]})]}),{}),a(Zi,{}),t($i,{variant:"outline",onClick:f,size:"sm",className:"w-full",children:[a(ve,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),$v=d({});function Vv({children:e,config:t}){const r=s(()=>{const e=mr(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return a($v.Provider,{value:r,children:e})}function qv(){return c($v)}function Wv(){const e=it(),{navigation:a}=qv();return Hv(a,e.pathname)}function Hv(e,a){if(!e)return"";const t=e.find(e=>e.path===a);if(t)return t.label;const r=e.find(e=>a.startsWith(e.path+"/"));return r?.label||""}function Gv(e,a){const[t,r]=o(e),n=u(),i=l(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return m(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}function Kv({appName:e}){const[n,i]=o(!1);return t(r,{children:[t("div",{className:"flex items-center justify-between w-[258px]",children:[a("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>i(!0),children:a("img",{src:Sr.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),e&&a("button",{className:"min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground/80 hover:text-primary-foreground/60 transition-colors leading-tight py-1",onClick:()=>i(!0),children:a("span",{className:"line-clamp-2",children:(e=>{const n=e.split(" ");if(n.length<=1)return t("span",{className:"whitespace-nowrap",children:[e," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return t(r,{children:[o," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(e)})})]}),a(ru,{open:n,onOpenChange:i})]})}const Yv=p(function({actions:r}){const n=it(),i=nt(),{navigation:s,appName:d}=qv(),c=Hv(s,n.pathname),{metadata:u,headerActions:p}=cc(),{setOpenMobile:h}=Jm(),{companies:f,alias:g,isSearchVisible:v,clearSearch:b,refreshData:x,switchUnit:y}=kl(),N=g?f?.find(e=>e.alias===g)||f?.[0]||null:f?.[0]||null,[w,_]=tt(),C=l(e=>{const{pathname:a,search:t,hash:r}=n;if(g){const n=a.split("/"),o=n.indexOf(g);if(o>=0)return n[o]=e.alias,void i(n.join("/")+t+r)}y(e)},[g,n,i,y]),[k,S]=o(()=>w.get("search")||""),[A,D]=Gv(k,fr.debounceDelay);m(()=>{if(!v)return;const e=new URLSearchParams(w);A?(e.set("search",A),e.set("page","1")):e.delete("search"),_(e)},[A,_,v]);const P=s?.find(e=>e.path===n.pathname)||s?.find(e=>n.pathname.startsWith(e.path+"/")),I=u.title||c,T=u.subtitle||P?.complementaryText||"";return a("header",{className:"bg-primary border-b border-primary px-2 md:px-4 py-2",children:t("div",{className:"flex items-center gap-4",children:[a($i,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:()=>h(!0),children:a(ga,{size:20})}),a("div",{className:"hidden md:flex items-center flex-shrink-0",children:a(Kv,{appName:d})}),a("div",{className:"hidden md:block w-px h-8 bg-primary-foreground/20 flex-shrink-0"}),t("div",{className:"flex-shrink-0",children:[u.breadcrumbs&&u.breadcrumbs.length>0&&a("nav",{className:"flex items-center gap-1 text-xs text-primary-foreground/70 mb-0.5",children:u.breadcrumbs.map((e,r)=>t("span",{className:"flex items-center gap-1",children:[r>0&&a(U,{className:"h-3 w-3"}),e.href?a(st,{to:e.href,className:"hover:text-primary-foreground transition-colors",children:e.label}):a("span",{children:e.label})]},r))}),a("div",{className:"flex items-center gap-2 mb-1",children:a("h1",{className:"text-lg font-semibold text-primary-foreground truncate",children:I})}),T&&a("div",{className:"text-sm text-primary-foreground/70 truncate",children:T})]}),v&&t("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[t("div",{className:"relative flex-1",children:[a(B,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(qi,{placeholder:"Pesquisar",value:k,onChange:e=>{return a=e.target.value,void S(a);var a},className:"w-full pl-10 pr-8"}),k&&a($i,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-primary-foreground/10 text-primary-foreground/60",onClick:()=>{D(),S("");const e=new URLSearchParams(w);e.delete("search"),e.delete("page"),_(e)},title:e.t("clear_search"),children:a(E,{size:14})})]}),a($i,{variant:"outline",size:"sm",onClick:x,className:"flex-shrink-0 h-10 w-10 p-0 bg-primary-foreground/20 border-primary-foreground/30 text-primary-foreground hover:bg-primary-foreground/30 hover:text-primary-foreground",title:e.t("refresh_data"),children:a(ue,{size:14})})]}),t("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(p||r)&&a("div",{className:"flex items-center gap-2",children:p||r}),import.meta.env.VITE_WIKI_URL&&a($i,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>Li(import.meta.env.VITE_WIKI_URL,e),title:e.t("open_wiki"),children:"Wiki"}),a(xh,{}),a("div",{className:"text-sm",children:a(Bv,{variant:"dropdown",selectedUnit:N,onUnitChange:C})})]})]})})}),Qv=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>Ja({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function Xv({config:e,isCollapsed:n=!1,isDisabled:i=!1,className:o}){const{t:s}=Ga(),{actions:l,triggerLabel:d="Criar",triggerIcon:c=Q,variant:u="button"}=e;if(!l||0===l.length)return null;if("split-button"===u){const e=l[0],r=e.icon||c,s=l.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=a($i,{onClick:e.onClick,disabled:i||e.disabled,className:Fi("justify-center px-2 w-full",o),variant:"outline",size:"default",children:a(r,{className:"h-4 w-4 shrink-0"})});return t(hs,{children:[a(fs,{asChild:!0,children:n}),a(gs,{side:"right",children:a("p",{children:e.label})})]})}return a(oh,{label:e.label,onClick:e.onClick,icon:r,actions:s,variant:"outline",disabled:i||e.disabled,className:Fi("w-full",o),menuAlign:"start"})}const m=(e,i,o=!1)=>t(r,{children:[e,!n&&i&&a("span",{className:"truncate",children:i}),!n&&o&&a(D,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(l.length>1)){const e=l[0],r=e.icon||c,s=i||e.disabled,d=a($i,{onClick:e.onClick,disabled:s,className:Fi("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:m(a(r,{className:"h-4 w-4 shrink-0"}),e.label)});return n?t(hs,{children:[a(fs,{asChild:!0,children:d}),a(gs,{side:"right",children:a("p",{children:e.label})})]}):d}const p=a($i,{disabled:i,className:Fi("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:m(a(c,{className:"h-4 w-4 shrink-0"}),d,!0)});return t(Jo,{children:[a(Zo,{asChild:!0,children:n?t(hs,{children:[a(fs,{asChild:!0,children:p}),a(gs,{side:"right",children:a("p",{children:d})})]}):p}),a(os,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:l.map(e=>{const r=e.icon;return t(ss,{onClick:e.onClick,disabled:e.disabled,className:"cursor-pointer",children:[r&&a(r,{className:"mr-2 h-4 w-4"}),e.label]},e.id)})})]})}const Jv="forlogic-sidebar-pinned",Zv=()=>{try{const e=localStorage.getItem(Jv);return!!e&&JSON.parse(e)}catch{return!1}};function eb({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:i,isOpen:s=!0}={}){const[d,c]=o(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[p,h]=o(!1),f=u(null);m(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(s?e.style.setProperty("--sidebar-width",`${d}px`):e.style.setProperty("--sidebar-width","290px"))},[d,s]);const g=l(e=>{e.preventDefault(),h(!0)},[]);return m(()=>{if(!p)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),c(n),i?.(n)},o=()=>{h(!1),c(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",o),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",o)}},[p,e,a,t,d,n,i]),m(()=>(p?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[p,e]),{width:d,isDragging:p,dragRef:f,handleMouseDown:g}}const ab=d(void 0);function tb({children:e}){const[t,r]=o(new Set),[n,i]=o(!1),d=l(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),c=l(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=l(e=>{i(e)},[]),m=s(()=>t.size>0||n,[t,n]),p=s(()=>({openModals:t,hasOpenModal:m,registerModal:d,unregisterModal:c,setHasOpenModal:u}),[t,m,d,c,u]);return a(ab.Provider,{value:p,children:e})}function rb(){const e=c(ab);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function nb(){const{hasOpenModal:e}=rb();return e}function ib({config:e,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:s=384}={}){const{t:d}=Ga(),{open:c,setOpen:u,setOpenMobile:p}=Jm(),h=it(),{alias:f,user:g}=kl(),{appName:v}=qv(),{hasOpenModal:b}=rb(),[x,y]=o(Zv),N=Dl(),w=!!N||c,_=l(()=>{N&&p(!1)},[N,p]),C=n?eb({minWidth:i,maxWidth:s,storageKey:"app-sidebar-width",isOpen:c}):null;m(()=>{u(!!x)},[x,u]);const k=e=>h.pathname===e||h.pathname.startsWith(e+"/");return t(ep,{collapsible:"icon",className:Fi("app-sidebar bg-background border-r border-border flex flex-col",w?"px-3":"px-1.5"),style:C&&w?{width:`${C.width}px`,transition:"none"}:{transition:"width 300ms ease-in-out"},children:[e?.moduleActions&&e.moduleActions.actions.length>0&&a("div",{className:"py-3",children:a(ps,{children:a(Xv,{config:e.moduleActions,isCollapsed:!w,isDisabled:b})})}),a(lp,{className:Fi(e?.moduleActions&&e.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||a(dp,{className:"p-0",children:a(mp,{children:a(pp,{className:"gap-1",children:a(ps,{children:e?.navigation?.map((e,r)=>{if("separator"===e.type)return a(sp,{className:"my-2"},`sep-${r}`);const n=({item:e,index:r})=>{const i=`${e.path}-${r}-${f??"noalias"}-${g?.id??"nouser"}`,{data:o=!0,isLoading:s}=Qv({key:i,enabled:Boolean(e.permissionCheck&&f&&g?.id),checkFn:e.permissionCheck||(()=>Promise.resolve(!0))}),l=e.permissionCheck&&!o,c=s?T:l?He:e.icon;l?d("restricted_access"):e.complementaryText;return e.children&&e.children.length>0?w?a(Sc,{defaultOpen:!0,className:"group/collapsible",children:t(hp,{children:[a(Ac,{asChild:!0,children:a(gp,{size:"default",children:t("div",{className:"flex w-full items-center gap-3",children:[a("span",{className:"flex items-center justify-center h-8 w-8",children:a(c,{className:"h-4 w-4"})}),a("span",{className:"font-medium sidebar-text",children:e.label}),a(U,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),a(Ec,{children:a(yp,{children:e.children.map((e,t)=>a(n,{item:e,index:t},e.path))})})]})},e.path):a(hp,{children:t(hs,{children:[a(fs,{asChild:!0,children:a("div",{className:Fi("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:a(c,{className:"h-4 w-4"})})}),a(gs,{side:"right",children:a("p",{children:e.label})})]})},e.path):a(hp,{children:l||s?t(hs,{children:[a(fs,{asChild:!0,children:w?a(gp,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:t("div",{className:"flex w-full items-center gap-3",children:[a("span",{className:"flex items-center justify-center h-8 w-8",children:a(c,{className:"h-4 w-4 "+(s?"animate-spin":"")})}),a("span",{className:"font-medium sidebar-text",children:e.label})]})}):a("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a(c,{className:"h-4 w-4 "+(s?"animate-spin":"")})})}),a(gs,{side:"right",children:a("p",{children:s?"Verificando acesso...":d("restricted_access")})})]}):w?a(gp,{asChild:!0,isActive:k(e.path),size:"default",children:t(st,{to:e.path,className:"flex w-full items-center gap-3",onClick:_,children:[a("span",{className:"flex items-center justify-center h-8 w-8",children:a(c,{className:"h-4 w-4"})}),a("span",{className:"font-medium sidebar-text",children:e.label})]})}):t(hs,{children:[a(fs,{asChild:!0,children:a(st,{to:e.path,onClick:_,className:Fi("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",k(e.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:a(c,{className:"h-4 w-4"})})}),a(gs,{side:"right",children:a("p",{children:e.label})})]})},e.path)};return a(n,{item:e,index:r},e.path)})})})})})}),!N&&a("div",{className:Fi("mt-auto pb-4 pt-2 flex",c?"justify-end":"justify-center"),children:t(hs,{children:[a(fs,{asChild:!0,children:a("button",{id:"btn-expand-side-nav",onClick:()=>{const e=!x;y(e),(e=>{try{localStorage.setItem(Jv,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:a(c?oe:U,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),a(gs,{side:"right",children:a("p",{children:c?"Recolher":"Expandir"})})]})}),n&&C&&w&&a("div",{ref:C.dragRef,onMouseDown:C.handleMouseDown,className:Fi("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",C.isDragging&&"bg-primary/40")})]})}const ob=p(function({children:e,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const o=s(()=>r||a(ib,{config:n}),[r,n]),d=s(()=>({"--sidebar-width":"290px","--sidebar-width-icon":"58px"}),[]),c=u(null),p=u(null),h=l(()=>{if(c.current&&p.current){const e=c.current.offsetHeight;p.current.style.setProperty("--header-height",`${e}px`)}},[]);return m(()=>{h();const e=new ResizeObserver(h);return c.current&&e.observe(c.current),()=>e.disconnect()},[h]),a(Vv,{config:n,children:a(dc,{children:a(Zm,{defaultOpen:!1,style:d,children:t("div",{ref:p,className:"flex flex-col h-screen w-full overflow-hidden",children:[i&&a("div",{ref:c,className:"flex-shrink-0 sticky top-0 z-40 bg-primary",children:a(Yv,{})}),t("div",{className:"sidebar-container flex flex-1 overflow-hidden",children:[o,a("main",{className:"relative z-0 flex-1 flex flex-col overflow-hidden",children:a("div",{className:"flex-1 min-h-0 overflow-y-auto bg-muted/30",children:e})})]})]})})})})});function sb({open:e,appName:n}){const[i,s]=o(!1);return t(r,{children:[a(ip,{className:"p-0 gap-0",children:e?t("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[a("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:a("img",{src:Sr.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),n&&a("button",{className:"flex-1 min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground hover:text-primary-foreground/80 transition-colors leading-tight py-1",onClick:()=>s(!0),children:a("span",{className:"line-clamp-2",children:(e=>{const n=e.split(" ");if(n.length<=1)return t("span",{className:"whitespace-nowrap",children:[e," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return t(r,{children:[o," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(n)})})]}):a("div",{className:"flex flex-col items-center justify-center w-full",children:a("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>s(!0),children:a("img",{src:Sr.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),a(ru,{open:i,onOpenChange:s})]})}function lb({title:e,subtitle:r,children:n,className:i,hasHeader:o=!0}){const s=e||r;return t("div",{className:Fi("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",i),children:[o&&s&&t("div",{className:"px-6 py-4 border-b border-border/50",children:[e&&a("h2",{className:"text-xl font-semibold text-foreground",children:e}),r&&a("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&a("div",{className:Fi("p-6",!o&&s&&"pt-4"),children:n})]})}function db({breadcrumbs:e,children:r,className:i}){return t("div",{className:Fi("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[e&&e.length>0&&a(Nu,{className:"mb-4",children:a(wu,{children:e.map((r,i)=>{const o=i===e.length-1;return t(n.Fragment,{children:[i>0&&a(Su,{}),a(_u,{children:o||!r.href?a(ku,{children:r.label}):r.asChild&&r.children?a(Cu,{asChild:!0,children:r.children}):a(Cu,{asChild:!0,children:a(st,{to:r.href||"/",children:r.label})})})]},`${r.label}-${i}`)})})}),a("div",{className:"space-y-6",children:r})]})}const cb=(e={})=>{const{enabled:a=!0}=e,{alias:t}=kl();return Ja({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=rl(),{data:a,error:r}=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(r){if(!ol.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function ub({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:s=!0}){const[d,c]=o(()=>{if(!s||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[p,h]=o(!1),[f,g]=o(null),v=u(0),b=u(0),x=l(e=>d[e]??a,[d,a]),y=l((e,t)=>{s&&(t.preventDefault(),t.stopPropagation(),h(!0),g(e),v.current=t.clientY,b.current=d[e]??a)},[s,d,a]);m(()=>{if(!p||!f)return;const e=e=>{const a=e.clientY-v.current,n=Math.max(t,Math.min(r,b.current+a));c(e=>{const a={...e,[f]:n};return i?.(a),a})},a=()=>{h(!1),g(null),n&&c(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[p,f,t,r,n,i]),m(()=>(p?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[p]);const N=l(()=>{c({}),n&&localStorage.removeItem(n),i?.({})},[n,i]);return{rowHeights:d,isDragging:p,activeRow:f,handleMouseDown:y,resetHeights:N,getRowHeight:x}}function mb(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:i}=e,[d,c]=o(t),[u,m]=o(r),[p,h]=o(!1),[f,g]=o(!1),v=a.length,b=0===d,x=d===v-1,y=a[d],N=v>1?(d+1)/v*100:100,w=l(()=>!y?.canProceed||y.canProceed(),[y]),_=s(()=>w(),[w,u]),C=s(()=>!b&&!y?.disableBack,[b,y]),k=l(e=>{m(a=>({...a,...e}))},[]),S=l((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=l(()=>{c(t),m(r),h(!1),g(!1),i?.()},[t,r,i]),E=l(async()=>{if(w()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[w,f,u,n]),D=l(async()=>{w()&&!p&&(x?await E():c(e=>Math.min(e+1,v-1)))},[w,p,x,v,E]),P=l(()=>{C&&!p&&c(e=>Math.max(e-1,0))},[C,p]),I=l(e=>{e<0||e>=v||p||(e<=d||e===d+1)&&c(e)},[d,v,p]),T=l(e=>{h(e)},[]);return{currentStep:d,currentStepConfig:y,data:u,isFirstStep:b,isLastStep:x,isLoading:p,isCompleting:f,next:D,back:P,goTo:I,canProceed:_,canGoBack:C,setData:k,updateField:S,reset:A,complete:E,setLoading:T,progress:N,stepIndex:d,totalSteps:v}}function pb(...e){return Object.assign({},...e)}const hb=()=>{const{locale:e,timezone:a}=wc(),t=fi;return{formatDatetime:r=>Ei(r,t,a,e),formatDate:t=>Di(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class fb{static async sendEmail(e){const a=rl(),{data:t,error:r}=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(r)throw r;return t}}const gb=fb;function vb({open:e,onOpenChange:r,placeId:n,placeName:i,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const{t:m}=Ga(),[p,h]=o([]),[f,g]=o(!1),[v,b]=o(""),{data:x=[],isLoading:y}=Ld({enabled:e}),N=s(()=>{let e=[...x];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),v){const a=v.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[x,v]),w=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},_=1===p.length,C=p.length>0;return a(mo,{open:e,onOpenChange:r,children:t(bo,{className:"max-w-2xl",variant:"form",children:[a(xo,{showSeparator:!0,children:t(wo,{className:"flex items-center gap-2",children:[a(Ze,{className:"h-5 w-5"}),"Gerenciar Acessos - ",i]})}),t(yo,{children:[t("div",{className:"relative mb-4",children:[a(B,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{placeholder:"Pesquisar...",value:v,onChange:e=>b(e.target.value),className:"pl-9"})]}),a(Dd,{className:"h-[400px] pr-4",children:y?a("div",{className:"space-y-2",children:[...Array(5)].map((e,t)=>a(Ps,{className:"h-16 w-full"},t))}):0===N.length?t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[a(Ze,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),a("p",{className:"text-sm text-muted-foreground",children:m(v?"leadership_no_users_found":"leadership_no_users_available")})]}):a("div",{className:"space-y-2",children:N.map(e=>{const r=e.userId===c,n=u.includes(e.userId||""),i=p.includes(e.userId||"");return t("div",{className:Fi("flex items-center gap-3 p-3 rounded-lg border transition-colors",i&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>w(e.userId||""),children:[a(qo,{checked:i,onCheckedChange:()=>w(e.userId||""),onClick:e=>e.stopPropagation()}),t("div",{className:"flex-1",children:[t("div",{className:"flex items-center gap-2",children:[a("p",{className:"font-medium",children:e.userName}),r&&a(va,{className:"h-4 w-4 text-yellow-500"})]}),a("p",{className:"text-sm text-muted-foreground",children:e.userEmail})]}),(r||n)&&a("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},e.userId)})})})]}),t(No,{className:"flex gap-2 sm:gap-2",children:[a("div",{className:"flex-1 text-sm text-muted-foreground",children:p.length>0&&t("span",{children:[p.length," selecionado(s)"]})}),_&&l&&t($i,{onClick:async()=>{if(l&&1===p.length){g(!0);try{await l(p[0],n),h([])}finally{g(!1)}}},disabled:f,variant:"outline",children:[a(va,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&t($i,{onClick:async()=>{if(d&&0!==p.length){g(!0);try{await d(p,n),h([])}finally{g(!1)}}},disabled:f,children:[a(ba,{className:"h-4 w-4 mr-2"}),"Tornar ",p.length>1?"Membros":"Membro"]})]})]})})}function bb({place:e,level:r=0,manageAccessConfig:n}){const{t:i}=Ga(),[s,l]=o(!1),[d,c]=o(!1),u=e.subPlaces&&e.subPlaces.length>0,m=e.isActive??!0,p=e.usersCount??0;return t("div",{children:[t(Sc,{open:s,onOpenChange:l,children:[t("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[u?t(Ac,{className:"flex items-center gap-2 flex-1",children:[a(U,{className:Fi("h-4 w-4 transition-transform shrink-0",s&&"rotate-90")}),a(fe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"font-medium",children:e.name}),t("span",{className:"text-sm text-muted-foreground",children:["(",e.subPlaces.length,")"]})]}):t("div",{className:"flex items-center gap-2 flex-1",children:[a("div",{className:"w-4 shrink-0"}),a(fe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"font-medium",children:e.name})]}),t("div",{className:"flex items-center gap-3 ml-auto",children:[t("div",{className:"flex items-center gap-1.5",children:[a(Ze,{className:"h-3.5 w-3.5 text-muted-foreground"}),a("span",{className:"text-sm text-muted-foreground",children:p})]}),a(Go,{variant:m?"default":"secondary",className:"text-xs",children:m?"Ativo":"Inativo"}),n&&a(Dv,{customActions:[{label:i("manage_access"),icon:xa,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),u&&a(Ec,{children:e.subPlaces.map(e=>a(bb,{place:e,level:r+1,manageAccessConfig:n},e.id))})]}),0===r&&a(Zi,{}),n&&a(vb,{open:d,onOpenChange:c,placeId:e.id,placeName:e.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(e.id),currentMemberIds:n.getCurrentMemberIds?.(e.id)})]})}function xb({places:e,isLoading:r,manageAccessConfig:n}){return r?a("div",{className:"flex items-center justify-center py-12",children:t("div",{className:"text-center space-y-2",children:[a("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),a("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):e&&0!==e.length?t("div",{className:"space-y-1",children:[a("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),e.map(e=>a(bb,{place:e,manageAccessConfig:n},e.id))]}):t("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[a(fe,{className:"h-12 w-12 text-muted-foreground/50"}),t("div",{children:[a("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),a("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const yb=new class{get baseUrl(){return xr()}async makeApiCall(e,a,t){const r=sl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Ys.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await sl.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return Qs.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Qs.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Nb(e,a){const t=e.map(e=>({...e})),r=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let a=e.id_leader;for(;a&&r.has(a);){const e=t.find(e=>e.id_user===a);a=e?.id_leader||null}e.id_leader=a}}),t.filter(e=>a.has(e.id_user))}function wb(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const i=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&i(e.children))};return i(r),r}function _b(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Cb(){const{alias:a,isAuthenticated:t}=kl(),r=Ys.getAccessToken(),{data:n=[]}=Ld({enabled:!0,status:"all"});return Ja({queryKey:["leadership",a],queryFn:async()=>{if(!r||!a)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=rl(),{data:i,error:o}=await t.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",a);if(o)throw new Error("Erro ao buscar hierarquia de liderança");if(!i||0===i.length)return[];const s={};n.forEach(e=>{s[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const l=i.map(a=>{const t=i.filter(e=>e.id_leader===a.id_user);return{...a,name:s[a.id_user]?.name||e.t("inactive_user"),email:s[a.id_user]?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>s[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))}}),d=new Set(i.map(e=>e.id_user));return new Set(i.filter(e=>e.id_leader&&!d.has(e.id_leader)).map(e=>e.id_leader)).forEach(e=>{const a=s[e],t=i.filter(a=>a.id_leader===e);l.push({id:`virtual-${e}`,alias:i[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||"[Usuário inativo]",email:a?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>s[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),wb(l)},enabled:!!r&&!!a&&t})}import.meta.env.VITE_SUPABASE_URL,Js();const kb="common";function Sb(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Ib(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(kb).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(i)throw i;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{C.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function Ab(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one",r("leadership_select_subordinates")));const n=a.users.map(e=>e.id_user),{data:i}=await t.schema(kb).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(i&&i.length>0){const e=i.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const d of a.users){if(a.id_leader&&d.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Ib(t,e,d.id_user,a.id_leader)}const o=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:s,error:l}=await t.schema(kb).from("leaders").insert(o).select();if(l)throw l;return s},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{C.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function Eb(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(kb).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!n)throw new Error(r("leader_not_found","Líder não encontrado"));if(n.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Ib(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:o}=await t.schema(kb).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{C.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function Db(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(kb).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{C.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function Pb(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const i=n.map(e=>e.id_user),o=await Promise.all([t.schema(kb).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(kb).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:s,error:l},{data:d,error:c}]=o;if(l)throw l;if(c)throw c;const u=s||[],m=d||[],p=new Set(i),h=u.filter(e=>!p.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),v=n.filter(e=>!g.has(e.id_user));for(const r of f)await Ib(t,e,r.id_user,a,r.id);for(const y of v){if(y.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await Ib(t,e,y.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(t.schema(kb).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);b.push(t.schema(kb).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(v.length){const r=v.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(kb).from("leaders").insert(r))}const x=(await Promise.all(b)).find(e=>e?.error);if(x?.error)throw x.error;return{unlinked:h.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{C.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function Ib(a,t,r,n,i){const{data:o,error:s}=await a.schema(kb).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(s)throw s;const l=i?o.filter(e=>e.id!==i):o,d=new Set;let c=n;for(;c;){if(d.has(c))throw new Error(e.t("leadership_cycle_error"));if(c===r)throw new Error("Esta associação criaria um ciclo na hierarquia");d.add(c);const a=l.find(e=>e.id_user===c);c=a?.id_leader||null}}var Tb=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,o=r.path.join(".");if(!t[o])if("unionErrors"in r){var s=r.unionErrors[0].errors[0];t[o]={message:s.message,type:s.code}}else t[o]={message:i,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[o].types,d=l&&l[r.code];t[o]=Oa(o,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},Rb=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,o){try{var s=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&or({},i),{errors:{},values:t.raw?r:e}})}catch(l){return o(l)}return s&&s.then?s.then(void 0,o):s}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:sr(Tb(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(o){return Promise.reject(o)}}};const Mb=ir.object({id_leader:ir.string().nullable(),id_users:ir.array(ir.string()).min(1,e.t("leadership_select_subordinates"))}),Lb=ir.object({id_leader:ir.string().nullable(),id_users:ir.array(ir.string())});function zb({value:r,onChange:n,excludeUserIds:i=[],error:s}){const{data:l=[],isLoading:d}=Ld(),[c,p]=o(""),h=u(null),f=u(0),g=l.filter(e=>!i.includes(e.userId||"")).filter(e=>{const a=c.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const t=r.includes(e.userId),n=r.includes(a.userId);if(t&&!n)return-1;if(!t&&n)return 1;const i=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return i.localeCompare(o)});return m(()=>{h.current&&f.current>0&&(h.current.scrollTop=f.current)},[g]),t("div",d?{className:"flex items-center justify-center p-4",children:[a(T,{className:"h-6 w-6 animate-spin"}),a("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[a(qi,{placeholder:e.t("search_user_placeholder"),value:c,onChange:e=>p(e.target.value)}),a("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===g.length?a("p",{className:"text-sm text-muted-foreground",children:e.t("search_user_placeholder")}):a("div",{className:"space-y-2",children:g.map(e=>t("div",{className:"flex items-center space-x-2",children:[a(qo,{id:e.userId,checked:r.includes(e.userId),onCheckedChange:()=>{return a=e.userId,h.current&&(f.current=h.current.scrollTop),void(r.includes(a)?n(r.filter(e=>e!==a)):n([...r,a]));var a}}),a(Hi,{htmlFor:e.userId,className:"flex-1 cursor-pointer",children:e.userName||e.userEmail})]},e.userId))})}),r.length>0&&t("p",{className:"text-sm text-muted-foreground",children:[r.length," selecionado(s)"]}),s&&a("p",{className:"text-sm text-destructive",children:s})]})}function Fb({leader:n,prefilledLeaderId:i,onSuccess:s}){const{t:l}=Ga(),{alias:d}=kl(),c=!!n,u=n?.id.startsWith("virtual-"),p=Ab(),h=Sb(),f=Eb(),g=Pb(),v=Db(),{data:b=[]}=Cb(),{data:x=[]}=Ld(),[y,N]=o(""),w=_b(b).map(e=>e.id_user),_=c?_b(b).filter(e=>e.id_leader===n.id_user).map(e=>e.id_user):[],C=Ba({resolver:Rb(c?Lb:Mb),defaultValues:{id_leader:i||(c?n?.id_leader:null)||null,id_users:c?_:[]}});m(()=>{if(n){const e=_b(b).filter(e=>e.id_leader===n.id_user).map(e=>e.id_user);C.reset({id_leader:n.id_leader||null,id_users:e})}else i?C.reset({id_leader:i,id_users:[]}):C.reset({id_leader:null,id_users:[]})},[d,n?.id,n?.id_user,n?.id_leader,i,b]);const k=p.isPending||h.isPending||f.isPending||g.isPending||v.isPending,S=C.watch("id_leader"),A=C.watch("id_users"),E=c?[n.id_user,...w.filter(e=>e!==n.id_user&&!A.includes(e)&&!_.includes(e))]:[S,...w.filter(e=>!A.includes(e))].filter(Boolean);return t("form",{onSubmit:C.handleSubmit(async e=>{try{if(c)if(u){await h.mutateAsync({id_user:n.id_user,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await g.mutateAsync({leaderUserId:n.id_user,selectedUsers:a})}else{await f.mutateAsync({id:n.id,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await g.mutateAsync({leaderUserId:n.id_user,selectedUsers:a})}else{const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({id_leader:e.id_leader,users:a})}s?.()}catch(a){}}),className:"space-y-4",children:[c&&t("div",{children:[a(Hi,{children:e.t("leader")}),a(qi,{value:x.find(e=>e.userId===n.id_user)?.userName||n.name||e.t("inactive_user"),disabled:!0,className:"bg-muted"})]}),t("div",{children:[a(Hi,{children:l("leadership_immediate_superior")}),t(Mo,{value:S||"none",onValueChange:e=>C.setValue("id_leader","none"===e?null:e),children:[a(Fo,{children:a(zo,{placeholder:"Selecione..."})}),t(Oo,{children:[a("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:a(qi,{placeholder:"Buscar superior...",value:y,onChange:e=>N(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),t(Dd,{className:"h-[200px]",children:[a($o,{value:"none",children:"[Nenhum]"}),x.filter(e=>{const a=c?e.userId!==n.id_user:!A.includes(e.userId),t=!y||e.userName?.toLowerCase().includes(y.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(e=>a($o,{value:e.userId,children:e.userName},e.userId))]})]})]},`superior-select-${d}`),C.formState.errors.id_leader&&a("p",{className:"text-sm text-destructive mt-1",children:C.formState.errors.id_leader.message})]}),t("div",{children:[a(Hi,{children:"Subordinados *"}),a(zb,{value:A,onChange:e=>C.setValue("id_users",e),excludeUserIds:E,error:C.formState.errors.id_users?.message},`users-multiselect-${d}`)]}),t("div",{className:"flex items-center justify-between gap-2",children:[a($i,{type:"submit",disabled:k||!c&&0===A.length,children:k&&!v.isPending?t(r,{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),c?"Atualizando...":"Salvando..."]}):c?"Atualizar":"Criar"}),c&&!S&&0===A.length&&t(eo,{children:[a(ao,{asChild:!0,children:a($i,{type:"button",variant:"destructive",disabled:k,className:"ml-auto",children:v.isPending?t(r,{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):t(r,{children:[a(H,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),t(no,{children:[t(io,{children:[a(so,{children:l("confirm_removal")}),a(lo,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),t(oo,{children:[a(uo,{children:l("cancel")}),a(co,{onClick:async()=>{if(n)try{await v.mutateAsync(n.id),s?.()}catch(e){}},children:l("remove")})]})]})]})]})]})}function Ub({open:e,onOpenChange:r,leader:n,prefilledLeaderId:i,title:o}){return a(mo,{open:e,onOpenChange:r,children:t(bo,{variant:"form",className:"sm:max-w-[500px]",children:[a(xo,{showSeparator:!0,children:a(wo,{children:o})}),a(yo,{children:a(Fb,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const jb="leadership-expanded-nodes",Ob=(e,a)=>{try{localStorage.setItem(`${jb}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Bb({unassociatedUsers:n=[],onAssociateUser:i,onMoveNode:d,onMoveNodes:c,columns:u,nameHeader:p=e.t("leader"),rootDropLabel:h=e.t("leadership_make_root")}={}){const{alias:f}=kl(),{data:g,isLoading:v,error:b,refetch:x}=Cb(),y=Eb(),N=Sb(),[w,_]=o(()=>f?(e=>{try{const a=localStorage.getItem(`${jb}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(f):new Set),[C,k]=o([]),[S,A]=o(new Set),[E,P]=o(!0),[I,T]=o(!1),[R,M]=o(),[L,z]=o(null),F=s(()=>g?_b(g):[],[g]),j=s(()=>F.map(e=>e.id),[F]),O=j.length>0&&C.length===j.length,B=F.filter(e=>e.children.length>0).every(e=>w.has(e.id));m(()=>{if(g&&g.length>0&&f){if(!localStorage.getItem(`${jb}-${f}`)){const e=g.map(e=>e.id),a=new Set(e);_(a),Ob(f,a)}}},[g,f]);const $=l(e=>{_(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),f&&Ob(f,t),t})},[f]),V=l(()=>{if(B){const e=new Set;_(e),f&&Ob(f,e)}else{const e=new Set(F.filter(e=>e.children.length>0).map(e=>e.id));_(e),f&&Ob(f,e)}},[B,F,f]),q=l(e=>{k(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),W=l(()=>{k(O?[]:j)},[O,j]),H=l(e=>{A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),K=l(e=>F.find(a=>a.id===e),[F]),Y=l((e,a)=>{if(d)return void d(e,a);const t=n.find(a=>a.id===e);if(t){if(i){const e=a?K(a):null;i(t.id,e?.id_user||null)}else N.mutate({id_user:t.id,id_leader:a&&K(a)?.id_user||null});return}const r=K(e);if(!r)return;const o=a?K(a):null;y.mutate({id:r.id,id_leader:o?.id_user||null})},[d,n,i,K,y,N]),X=l((e,a)=>{c?c(e,a):(e.forEach(e=>Y(e,a)),k([]))},[c,Y]),J=l(e=>{M(e),z(null),T(!0)},[]),Z=l(()=>{M(void 0),z(null),T(!0)},[]),ee=l(()=>{T(!1),M(void 0),z(null)},[]),ae=l((e,a)=>{const t=S.has(e)&&S.size>1?Array.from(S):[e];a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t)),a.currentTarget.style.opacity="0.4"},[S]),te=s(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:e=>e.subordinateNames&&e.subordinateNames.length>0?t("div",{className:"space-y-1.5",children:[a("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...e.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(e=>t("div",{className:"flex items-center gap-2 text-sm",children:[a(ge,{className:"h-3 w-3 text-muted-foreground"}),a("span",{children:e})]},e))]}):a("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:e=>t("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[a(Ke,{className:"h-3.5 w-3.5"}),e.email||"—"]})}],[]),re=u??te;if(v)return a("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center space-y-2",children:[a("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),a("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(b)return a("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center",children:[a("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),a($i,{onClick:()=>x(),children:e.t("try_again")})]})});const ne=F.filter(a=>a.name!==e.t("inactive_user")).length;return t("div",{className:"flex flex-col h-full gap-3 p-4",children:[t("div",{className:"flex items-center justify-between",children:[t("div",{className:"flex gap-2 items-center",children:[t($i,{size:"sm",onClick:Z,children:[a(Q,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a($i,{size:"sm",variant:"outline",onClick:V,children:t(r,B?{children:[a(D,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[a(U,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),a("div",{className:"flex items-center gap-2 ml-4",children:t("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[a(Ze,{className:"h-4 w-4 text-muted-foreground"}),t("span",{className:"text-sm font-medium",children:[ne," usuário",1!==ne?"s":""," associado",1!==ne?"s":""]})]})})]}),a("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),a(Lv,{data:g||[],columns:re,nameKey:"name",nameHeader:p,expandedIds:w,onToggleExpand:$,iconComponent:a(Ze,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:q,onSelectAll:W,isAllSelected:O,onMoveNode:Y,onMoveNodes:X,rootDropLabel:h,emptyMessage:e.t("leadership_no_hierarchy"),renderActions:e=>a($i,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>J(e),children:a(G,{className:"h-4 w-4"})})}),n.length>0&&t("div",{className:"border rounded-lg overflow-hidden",children:[t("button",{type:"button",onClick:()=>P(e=>!e),className:"w-full px-4 py-2.5 bg-muted/50 border-b flex items-center gap-2 hover:bg-muted/70 transition-colors cursor-pointer",children:[a(E?D:U,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a(ba,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:"Usuários não associados"}),t("span",{className:"text-xs text-muted-foreground ml-1",children:["(",n.length,")"]}),S.size>0&&t("span",{className:"text-xs text-primary ml-1",children:["(",S.size," selecionado",S.size>1?"s":"",")"]}),a("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),E&&a("div",{className:"divide-y",children:n.map(e=>t("div",{draggable:!0,onDragStart:a=>ae(e.id,a),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Fi("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",S.has(e.id)&&"bg-primary/5"),children:[a(qo,{checked:S.has(e.id),onCheckedChange:()=>H(e.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),a("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),a(ge,{className:"h-4 w-4 text-muted-foreground shrink-0"}),t("div",{className:"flex flex-col min-w-0",children:[a("span",{className:"text-sm truncate",children:e.name}),a("span",{className:"text-xs text-muted-foreground truncate",children:e.email})]})]},e.id))})]}),t("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[t("span",{children:["Usuários associados: ",ne]}),n.length>0&&t("span",{children:["Usuários não associados: ",n.length]})]}),a(Ub,{open:I,onOpenChange:ee,leader:R,prefilledLeaderId:L,title:R?e.t("edit_name"):L?e.t("leadership_add_subordinate"):e.t("leadership_add_root")},`leadership-dialog-${f}`)]})}function $b(e){const[a,t]=o(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:i,onSuccess:s,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...i,...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 n=await r(e,t);return C.success("Sucesso",{description:"Arquivo enviado com sucesso"}),s?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw C.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),C.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw C.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Vb(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 qb(e,a){const t=Vb(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Wb(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Hb(e,a){const t=Wb(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Gb(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Kb(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Yb(e,a,t){switch(a||Kb(e)){case"youtube":return qb(e,t);case"vimeo":return Hb(e,t);default:return e}}function Qb({value:n,onChange:i,onSubmit:l,onCancel:d,uploadFunction:c,deleteFunction:m,uploadOptions:p}){const{t:h}=Ga(),[f,g]=o(n||{inputType:"url",controls:!0}),v=u(null),b=u(null),{upload:x,uploading:y}=$b({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["video/*"],maxSize:104857600}}),{upload:N,uploading:w}=$b({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["image/*"],maxSize:5242880}}),_=s(()=>Kb(f.videoUrl||Gb(f.embedCode)||""),[f.videoUrl,f.embedCode]),k=(e,a)=>{const t={...f,[e]:a};g(t),i(t)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:h("input_type")}),t(Mo,{value:f.inputType||"url",onValueChange:e=>k("inputType",e),children:[a(Fo,{children:a(zo,{})}),t(Oo,{children:[a($o,{value:"url",children:"URL"}),a($o,{value:"upload",children:h("file_upload")}),a($o,{value:"embed",children:h("embed_code")})]})]})]}),"upload"===f.inputType&&c&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Arquivo"}),t("div",{className:"flex gap-2",children:[a("input",{ref:v,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await x(a),t={...f,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:f.title||a.name.replace(/\.[^/.]+$/,"")};g(t),i(t)}catch(t){}finally{v.current&&(v.current.value="")}},className:"hidden"}),a($i,{type:"button",variant:"outline",onClick:()=>v.current?.click(),disabled:y,children:t(r,y?{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ya,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),f.videoFile&&t("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",f.videoFile," (",Math.round((f.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===f.inputType&&t("div",{className:"space-y-2",children:[a(Hi,{children:h("embed_code")}),a(Wo,{placeholder:h("paste_embed_code"),value:f.embedCode||"",onChange:e=>k("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Thumbnail"}),t("div",{className:"flex gap-2",children:[a(qi,{type:"url",placeholder:"URL da thumbnail",value:f.thumbnail||"",onChange:e=>k("thumbnail",e.target.value),className:"flex-1"}),a("input",{ref:b,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await N(a),t={...f,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};g(t),i(t)}catch(t){}finally{b.current&&(b.current.value="")}},className:"hidden"}),a($i,{type:"button",variant:"outline",onClick:()=>b.current?.click(),disabled:w,children:t(r,w?{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ya,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),f.thumbnailFile&&t("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",f.thumbnailFile]})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"title",children:"Título"}),a(qi,{id:"title",placeholder:h("video_title"),value:f.title||"",onChange:e=>k("title",e.target.value)})]}),t("div",{className:"flex gap-6",children:[t("div",{className:"flex items-center gap-2",children:[a(qo,{id:"autoplay",checked:f.autoplay||!1,onCheckedChange:e=>k("autoplay",!0===e)}),a(Hi,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),t("div",{className:"flex items-center gap-2",children:[a(qo,{id:"controls",checked:!1!==f.controls,onCheckedChange:e=>k("controls",!0===e)}),a(Hi,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:"Preview"}),a("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const r=f.videoUrl||Gb(f.embedCode)||"";if(!r)return a("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===_)return t("video",{controls:!1!==f.controls,autoPlay:f.autoplay,poster:f.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[a("source",{src:r}),"Seu navegador não suporta este vídeo."]});const n="youtube"===_?qb(r,f.autoplay):Hb(r,f.autoplay);return a("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:a("iframe",{title:f.title||e.t("video"),src:n,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[a($i,{variant:"outline",onClick:d,children:"Cancelar"}),a($i,{onClick:()=>{f.videoUrl||f.embedCode?l(f):C.error("Erro",{description:h("no_video_selected")})},disabled:!(f.videoUrl||f.embedCode),children:"Salvar"})]})]})}function Xb({content:r,className:n="",style:i}){const o=r.videoUrl||Gb(r.embedCode)||"";if(!o)return null;const s=Kb(o);return a(Gi,{className:`overflow-hidden my-4 ${n}`,style:i,children:t(Xi,{className:"p-0",children:["file"===s?t("video",{controls:!1!==r.controls,autoPlay:r.autoplay,poster:r.thumbnail,className:"w-full h-auto",playsInline:!0,muted:r.autoplay,children:[a("source",{src:o}),"Seu navegador não suporta vídeos HTML5."]}):a("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:a("iframe",{title:r.title||e.t("video"),src:"youtube"===s?qb(o,r.autoplay):Hb(o,r.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),r.title&&a("div",{className:"p-4",children:a("p",{className:"text-sm font-medium",children:r.title})})]})})}function Jb({value:e,onChange:n,onSubmit:i,onCancel:s,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const{t:m}=Ga(),[p,h]=o(e||{alignment:"center",allowDownload:!1}),f=u(null),{upload:g,uploading:v}=$b({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...p,[e]:a};h(t),n(t)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:"URL"}),t("div",{className:"flex gap-2",children:[a(qi,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:p.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&t(r,{children:[a("input",{ref:f,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await g(a),t={...p,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),a($i,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:t(r,v?{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ya,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),p.imageFile&&t("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",p.imageFile," (",Math.round((p.imageSize||0)/1024)," KB)"]})]}),p.imageUrl&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Preview"}),a("div",{className:"border rounded-lg p-4 bg-muted/30",children:a("div",{className:"flex "+("left"===p.alignment?"justify-start":"right"===p.alignment?"justify-end":"justify-center"),children:a("img",{src:p.imageUrl,alt:p.alt||"Preview",style:{width:p.width?`${p.width}px`:"auto",height:p.height?`${p.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"caption",children:"Legenda"}),a(Wo,{id:"caption",placeholder:"Legenda",value:p.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"alt",children:m("alt_text")}),a(qi,{id:"alt",placeholder:m("alt_text"),value:p.alt||"",onChange:e=>b("alt",e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:"Alinhamento"}),t(Mo,{value:p.alignment||"center",onValueChange:e=>b("alignment",e),children:[a(Fo,{children:a(zo,{})}),t(Oo,{children:[a($o,{value:"left",children:"Esquerda"}),a($o,{value:"center",children:"Centro"}),a($o,{value:"right",children:"Direita"})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"width",children:"Largura"}),a(qi,{id:"width",type:"number",placeholder:"px",value:p.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"height",children:"Altura"}),a(qi,{id:"height",type:"number",placeholder:"px",value:p.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),t("div",{className:"flex items-center gap-2",children:[a(qo,{id:"allowDownload",checked:p.allowDownload||!1,onCheckedChange:e=>b("allowDownload",!0===e)}),a(Hi,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[a($i,{variant:"outline",onClick:s,children:"Cancelar"}),a($i,{onClick:()=>{p.imageUrl?i(p):C.error("Erro",{description:m("no_image_selected")})},disabled:!p.imageUrl,children:"Salvar"})]})]})}function Zb({content:e,className:r="",style:n}){const{t:i}=Ga();if(!e.imageUrl)return null;const o={left:"justify-start",center:"justify-center",right:"justify-end"}[e.alignment||"center"];return a("div",{className:`flex ${o} my-4 ${r}`,style:n,children:t("div",{className:"space-y-2 max-w-full",children:[a("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&&a("p",{className:"text-sm text-muted-foreground text-center italic",children:e.caption}),e.allowDownload&&e.imageUrl&&t("a",{href:e.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[a(Je,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function ex(e,a){return e/a}function ax(e,a,t,r){const n=ex(e,a);return t&&!r?{width:t,height:Math.round(t/n)}:r&&!t?{width:Math.round(r*n),height:r}:{width:e,height:a}}function tx(e){const a=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const t=new URL(e);return a.some(e=>t.pathname.toLowerCase().endsWith(e))}catch{const t=e.toLowerCase();return a.some(e=>t.endsWith(e))}}function rx(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"}}function nx(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function ix(){const{alias:e}=kl(),[a,t]=o(null),[r,n]=o(!0);m(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=rl(),{data:n,error:i}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);return{config:a,isLoading:r,saveConfig:l(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=rl(),{data:i,error:o}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return t(i),i},[e])}}const ox=import.meta.env.VITE_SUPABASE_URL,sx=Js();async function lx(e,a,t){const r=Ys.getSupabaseToken(),n={"Content-Type":"application/json",apikey:sx};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${ox}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${i.status}`)}return i}const dx={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await lx(a,t,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const a="d4sign"===e.provider?"d4sign":"clicksign";return(await lx(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let cx=null;function ux(){return window.Clicksign?Promise.resolve():cx||(cx=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),cx)}const mx="clicksign-container";function px({signerId:e,environment:r="sandbox",onSign:n,onError:i,onClose:s}){const{t:l}=Ga(),d=u(null),[c,p]=o(!0),[h,f]=o(null);return m(()=>{let a=!1;return d.current&&(d.current.unmount(),d.current=null),f(null),p(!0),ux().then(()=>{if(a)return;const t=new window.Clicksign(e);t.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(mx),t.on("loaded",function(){p(!1)}),t.on("signed",function(){n?.()}),t.on("resized",function(e){const a=e,t=document.getElementById(mx);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),t.on("error",function(e){p(!1),i?.(e instanceof Error?e:new Error(l("sign_widget_error")))}),t.on("closed",function(){s?.()}),d.current=t}).catch(e=>{a||(f("Falha ao carregar o script de assinatura."),p(!1),i?.(e))}),()=>{a=!0,d.current&&(d.current.unmount(),d.current=null)}},[e,r]),t("div",{className:"relative h-full",children:[c&&a("div",{className:"absolute inset-0 flex items-center justify-center",children:t("div",{className:"flex items-center gap-2 text-muted-foreground",children:[a(T,{className:"h-5 w-5 animate-spin"}),a("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&a("div",{className:"absolute inset-0 flex items-center justify-center",children:a("p",{className:"text-sm text-destructive",children:h})}),a("div",{id:mx,style:{height:"600px"}})]})}function hx({documentKey:r,signerEmail:n,signerName:i,keySigner:s,environment:d,onSign:c,onError:p}){const h=u(null),[f,g]=o("loading"),[v,b]=o(null),x="production"===d?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",y=(()=>{const e=new URLSearchParams({email:n,display_name:i||"",disable_preview:"0"});return s&&e.set("key_signer",s),`${x}/${r}?${e.toString()}`})(),N=l(a=>"signed"===a.data?(g("ready"),void c?.()):"wrong-data"===a.data?(g("error"),b(e.t("sign_incorrect_data")),void p?.(new Error(e.t("sign_incorrect_data")))):void 0,[c,p]);m(()=>(window.addEventListener("message",N,!1),()=>{window.removeEventListener("message",N,!1)}),[N]);const w=l(()=>{"loading"===f&&g("ready")},[f]);return"error"===f?t(rc,{variant:"danger",className:"my-4",children:[a(nc,{children:e.t("sign_doc_load_error")}),a(ic,{children:v||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):t("div",{className:"relative h-full",children:["loading"===f&&a("div",{className:"absolute inset-0 flex items-center justify-center",children:t("div",{className:"flex items-center gap-2 text-muted-foreground",children:[a(T,{className:"h-5 w-5 animate-spin"}),a("span",{className:"text-sm",children:"Carregando documento..."})]})}),a("iframe",{ref:h,id:"d4sign-container",src:y,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:w})]})}function fx({file:r,onDocumentSigned:n,onError:i,showEventLog:s=!1}){const{user:d,alias:c}=kl(),{config:p,isLoading:h}=ix(),{t:f}=Ga(),[g,v]=o(null),[b,x]=o(!1),[y,N]=o(null),[w,_]=o("sandbox"),[k,S]=o("clicksign"),[A,E]=o(null),[D,P]=o(null),[I,R]=o(!1),[M,L]=o(0),[z,F]=o(!1),[U,j]=o([]),O=u(null),B=u(null),$=l(e=>{s&&j(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[s]),V=l(async a=>{if(v(a),N(null),E(null),P(null),$(`Arquivo selecionado: ${a.name}`),c&&d){x(!0);try{const t=p?.provider??"clicksign";S(t),$(`Provedor resolvido: ${t}`);const r=new FileReader,n=await new Promise((e,t)=>{r.onload=()=>{const a=r.result;e(a)},r.onerror=t,r.readAsDataURL(a)});$(`Criando envelope para assinatura via ${t}...`);const o=await dx.createEnvelopeWithSigner({alias:c,contentBase64:n,filename:a.name,signerEmail:d.email||"",signerName:d.name||"",provider:t});$(`Envelope criado: ${o.envelope_id}`),E({envelope_id:o.envelope_id,document_id:o.document_id,signer_email:o.signer_email,key_signer:o.signer_id}),_(o.environment),S(o.provider||t),"d4sign"===t?($("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),N(o.document_id),C.success(f("sign_doc_sent","Documento enviado! Assine abaixo."))):o.signer_id?($(`Signer ID obtido: ${o.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),N(o.signer_id),C.success(f("sign_doc_sent","Documento enviado! Assine abaixo."))):($(e.t("sign_signer_unavailable")),C.error(f("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),i?.(new Error(f("sign_signer_unavailable"))))}catch(t){const a=t instanceof Error?t:new Error(f("sign_process_error",f("sign_doc_process_error"))),r=a.message||"";r.includes("MONTHLY_LIMIT_REACHED")?($(e.t("sign_monthly_limit")),C.error(f("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):($(`Erro: ${r}`),C.error(r)),i?.(a)}finally{x(!1)}}},[c,d,$,i,p]);m(()=>{r&&c&&d&&!h&&r!==B.current&&(B.current=r,V(r))},[r,c,d,h,V]);const q=l(async()=>{if(!A||!c)return;R(!0),L(0),F(!1),$("Buscando documento assinado...");for(let t=1;t<=6;t++){L(t),$(`Tentativa ${t}/6...`);try{const a=await dx.getSignedDocument({alias:c,envelopeId:A.envelope_id,documentId:A.document_id,provider:k});if(a.download_url)return $(e.t("sign_doc_available")),P(a.download_url),void R(!1)}catch(a){$(`Erro na tentativa ${t}: ${a instanceof Error?a.message:f("unknown_error")}`)}t<6&&($("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}$(e.t("sign_fetch_failed")),R(!1),F(!0)},[A,c,$,k]),W=l(async()=>{$("Documento assinado com sucesso!"),C.success(f("sign_signed_success","Documento assinado com sucesso!")),N(null),A&&c&&(n?.({success:!0,provider:k,envelope_id:A.envelope_id,document_id:A.document_id,signer_id:y||"",environment:w}),await q())},[$,n,A,y,c,w,k,q]);if(!c)return a(Gi,{className:"border-amber-200 bg-amber-50",children:a(Xi,{className:"flex items-start gap-3 py-6",children:t("div",{children:[a("p",{className:"font-medium text-amber-800",children:f("sign_auth_required","Autenticação necessária")}),a("p",{className:"text-sm text-amber-700 mt-1",children:f("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const H="d4sign"===k?"D4Sign":"Clicksign",G=()=>s&&U.length>0?a("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:U.map((e,t)=>a("div",{children:e},t))}):null;return A&&!y&&(D||I||z)?t("div",{className:"space-y-4",children:[a(Gi,{className:"border-green-200 bg-green-50",children:t(Xi,{className:"flex flex-col items-center gap-4 py-8",children:[a(aa,{className:"h-12 w-12 text-green-600"}),t("div",{className:"text-center",children:[a("p",{className:"text-lg font-semibold text-green-800",children:f("sign_signed_success","Documento assinado com sucesso!")}),a("p",{className:"text-sm text-green-700 mt-1",children:g?.name})]}),I?t("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[t("div",{className:"flex items-center gap-2",children:[a(T,{className:"h-4 w-4 animate-spin"}),f("sign_preparing_doc","Preparando documento assinado...")," (",f("sign_attempt","tentativa")," ",M,"/6)"]}),a("p",{className:"text-xs text-muted-foreground",children:f("sign_waiting_provider",`Aguardando processamento pelo ${H}...`)})]}):D?a($i,{asChild:!0,variant:"default",className:"gap-2",children:t("a",{href:D,target:"_blank",rel:"noopener noreferrer",children:[a(Je,{className:"h-4 w-4"}),f("sign_download_signed","Baixar documento assinado")]})}):z?t("div",{className:"text-center space-y-3",children:[t("div",{className:"space-y-1",children:[a("p",{className:"text-sm text-muted-foreground",children:f("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),a("p",{className:"text-xs text-muted-foreground",children:f("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),t($i,{variant:"secondary",className:"gap-2",onClick:q,children:[a(ue,{className:"h-4 w-4"}),f("sign_try_again","Tentar novamente")]})]}):null]})}),a(G,{})]}):y?t("div",{className:"space-y-4",children:["d4sign"===k?a(hx,{documentKey:y,signerEmail:A?.signer_email||d?.email||"",signerName:d?.name,keySigner:A?.key_signer,environment:w,onSign:W,onError:i}):a(px,{signerId:y,environment:w,onSign:W,onError:i}),a(G,{})]}):r&&(b||h)?a(Gi,{children:t(Xi,{className:"flex items-center justify-center gap-3 py-10",children:[a(T,{className:"h-6 w-6 animate-spin text-primary"}),a("p",{className:"font-medium",children:f("sign_sending_doc","Enviando documento para assinatura...")})]})}):t("div",{className:"space-y-4",children:[a("input",{ref:O,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?V(a):C.error(f("sign_select_pdf","Selecione um arquivo PDF"))}}),a(Gi,b?{children:t(Xi,{className:"flex items-center justify-center gap-3 py-10",children:[a(T,{className:"h-6 w-6 animate-spin text-primary"}),a("p",{className:"font-medium",children:f("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>O.current?.click(),children:t(Xi,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[a(ya,{className:"h-8 w-8 text-muted-foreground"}),t("div",{className:"text-center",children:[a("p",{className:"font-medium",children:f("sign_select_pdf","Selecione um arquivo PDF")}),a("p",{className:"text-sm text-muted-foreground",children:f("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),a(G,{})]})}function gx({onSaved:e}){const{config:r,isLoading:n,saveConfig:i}=ix(),{t:s}=Ga(),[l,d]=o(""),[c,u]=o("sandbox"),[p,h]=o(!1);m(()=>{!n&&r&&(d(r.api_key),u(r.environment))},[r,n]);return n?a("div",{className:"flex items-center justify-center py-8",children:a(T,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t("div",{className:"space-y-4",children:[t("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[a(le,{className:"h-4 w-4"}),a("span",{children:s("sign_configured",s("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[a(O,{className:"h-4 w-4"}),a("span",{children:s("sign_not_configured",s("sign_not_configured_unit"))})]}),t(Gi,{children:[a(Ki,{children:a(Yi,{className:"text-base",children:s("sign_digital_config")})}),a(Xi,{children:t("form",{onSubmit:async a=>{if(a.preventDefault(),l.trim()){h(!0);try{await i(l.trim(),c),C.success(s("sign_config_saved",s("sign_config_saved_success"))),e?.()}catch(t){C.error(s("sign_config_save_error",s("sign_config_save_err")))}finally{h(!1)}}else C.error(s("sign_api_key_required",s("sign_api_key_info")))},className:"space-y-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"sign-api-key",children:"API Key"}),a(qi,{id:"sign-api-key",type:"password",placeholder:s("sign_api_key_placeholder",s("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:s("sign_environment","Ambiente")}),t(Mo,{value:c,onValueChange:e=>u(e),children:[a(Fo,{children:a(zo,{})}),t(Oo,{children:[a($o,{value:"sandbox",children:"Sandbox (Testes)"}),a($o,{value:"production",children:"Produção"})]})]})]}),t($i,{type:"submit",disabled:p,children:[p&&a(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?s("sign_update_config",s("sign_update_config_btn")):s("sign_save_config",s("sign_save_config_btn"))]})]})})]})]})}var vx,bx,xx,yx,Nx,wx,_x,Cx,kx,Sx;(bx=vx||(vx={}))[bx.waitingStart=1]="waitingStart",bx[bx.running=2]="running",bx[bx.effectivenessCheck=3]="effectivenessCheck",bx[bx.done=4]="done",bx[bx.suspended=5]="suspended",bx[bx.canceled=6]="canceled",(yx=xx||(xx={}))[yx.low=0]="low",yx[yx.medium=1]="medium",yx[yx.high=2]="high",(wx=Nx||(Nx={}))[wx.plan=2]="plan",wx[wx.occurrence=3]="occurrence",wx[wx.risk=4]="risk",wx[wx.decisions=5]="decisions",wx[wx.audit=6]="audit",wx[wx.strategyExtension=7]="strategyExtension",wx[wx.standardization=8]="standardization",wx[wx.supplier=9]="supplier",wx[wx.auditItems=10]="auditItems",(Cx=_x||(_x={}))[Cx.currentProgress=1]="currentProgress",Cx[Cx.cumulativeProgress=2]="cumulativeProgress",(Sx=kx||(kx={})).uploading="uploading",Sx.waiting="waiting",Sx.done="done",Sx.error="error",Sx.canceled="canceled",Sx.duplicateItem="duplicateItem";const Ax={[vx.waitingStart]:"#D6D6D6",[vx.running]:"#DAE9F4",[vx.effectivenessCheck]:"#1B75BB29",[vx.done]:"#DDEECA",[vx.suspended]:"#FFF2D6",[vx.canceled]:"#F4433629"},Ex={[vx.waitingStart]:"#666666",[vx.running]:"#1B75BB",[vx.effectivenessCheck]:"#1B75BB",[vx.done]:"#4CAF50",[vx.suspended]:"#FF9800",[vx.canceled]:"#F44336"},Dx={[vx.waitingStart]:"waiting-start",[vx.running]:"running",[vx.effectivenessCheck]:"effectiveness-check",[vx.done]:"done",[vx.suspended]:"suspended",[vx.canceled]:"canceled"};function Px(){return{[vx.waitingStart]:e.t("ap_status_waiting_start"),[vx.running]:e.t("ap_status_running"),[vx.effectivenessCheck]:e.t("ap_status_effectiveness_check"),[vx.done]:e.t("ap_status_done"),[vx.suspended]:e.t("ap_status_suspended"),[vx.canceled]:e.t("ap_status_canceled")}}const Ix=new Proxy({},{get:(e,a)=>{if("symbol"==typeof a)return;return Px()[a]}});function Tx(){return[{id:"immediate",label:e.t("ap_type_immediate")},{id:"corrective",label:e.t("ap_type_corrective")},{id:"preventive",label:e.t("ap_type_preventive")},{id:"improvement",label:e.t("ap_type_improvement")},{id:"standardization",label:e.t("ap_type_standardization")}]}const Rx=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}];function Mx(){return[{id:xx.low,label:e.t("ap_priority_low"),color:"#4CAF50"},{id:xx.medium,label:e.t("ap_priority_medium"),color:"#FF9800"},{id:xx.high,label:e.t("ap_priority_high"),color:"#F44336"}]}const Lx=[{id:xx.low,label:"Baixa",color:"#4CAF50"},{id:xx.medium,label:"Média",color:"#FF9800"},{id:xx.high,label:"Alta",color:"#F44336"}],zx=[vx.done,vx.canceled],Fx=[vx.waitingStart,vx.running,vx.effectivenessCheck,vx.suspended];function Ux(e){const{actionPlan:a,isNew:t=!1,config:r,onSave:n,onCancel:i,onDelete:s,onChangeStatus:d}=e,[c,u]=o({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});m(()=>{a&&u(e=>({...e,formData:a,isFormDisabled:r?.disableFields||zx.includes(a.statusId)}))},[a,r?.disableFields]),m(()=>{u(a=>({...a,isLoading:e.isLoading||!1}))},[e.isLoading]);const p=l((e,a)=>{u(t=>({...t,formData:{...t.formData,[e]:a}}))},[]),h=l(e=>{u(a=>({...a,activeTab:e}))},[]),f=l(async()=>{if(n){u(e=>({...e,isSaving:!0}));try{await n(c.formData)}finally{u(e=>({...e,isSaving:!1}))}}},[n,c.formData]),g=l(async e=>{if(d&&c.formData.id){u(e=>({...e,isLoading:!0}));try{await d(c.formData.id,e)}finally{u(e=>({...e,isLoading:!1}))}}},[d,c.formData.id]),v=l(async()=>{if(s&&c.formData.id){u(e=>({...e,isLoading:!0}));try{await s(c.formData.id)}finally{u(e=>({...e,isLoading:!1}))}}},[s,c.formData.id]);return{formData:c.formData,isLoading:c.isLoading,isSaving:c.isSaving,activeTab:c.activeTab,isFormDisabled:c.isFormDisabled,updateField:p,setActiveTab:h,save:f,changeStatus:g,remove:v,cancel:i}}const jx={[vx.waitingStart]:{label:"",color:"#8B7355",icon:We},[vx.running]:{label:"",color:"#2E7D5B",icon:wa},[vx.effectivenessCheck]:{label:"",color:"#4A6FA5",icon:Ge},[vx.done]:{label:"",color:"#3D7A40",icon:aa},[vx.suspended]:{label:"",color:"#6B7280",icon:Na},[vx.canceled]:{label:"",color:"#B44A4A",icon:E}};function Ox({status:e,labels:t,className:r,size:n,showIcon:i,variant:o}){const s=Px(),l=jx[e];if(!l)return null;const d=t?.[e]||s[e]||"";return a(Yh,{label:d,color:l.color,icon:l.icon,size:n,showIcon:i,variant:o,className:r})}function Bx({formData:e,updateField:r,disabled:n=!1,users:o=[],places:s=[],actionTypes:l,causes:d=[],parentActions:c=[],config:u}){const{t:m}=Ga(),p=u?.requiredFields,h=l||Rx,f=e=>{if(u?.hiddenFields?.includes(e))return!1;if(u?.visibleFields&&u.visibleFields.length>0)return u.visibleFields.includes(e);const a=`${e}Visible`;return!p||!(a in p)||!1!==p[a]},g=e=>p?!!p[e]:"name"===e,v=i.useMemo(()=>{if(e.startDate&&e.endDate){const a=new Date(e.startDate),t=new Date(e.endDate).getTime()-a.getTime();return Math.max(0,Math.ceil(t/864e5))}return e.duration||0},[e.startDate,e.endDate,e.duration]);return t("div",{className:"space-y-6 p-1",children:[t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),a(qi,{value:e.name||"",onChange:e=>r("name",e.target.value),maxLength:500,disabled:n,placeholder:m("ap_plan_name_placeholder")})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f("responsibleWho")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),t(Mo,{value:e.responsibleId||"",onValueChange:e=>r("responsibleId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_responsible")})}),a(Oo,{children:o.map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]}),f("checkerWho")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),t(Mo,{value:e.checkerId||"",onValueChange:e=>r("checkerId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_checker")})}),a(Oo,{children:o.map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f("place")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),t(Mo,{value:e.placeId||"",onValueChange:e=>r("placeId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_place")})}),a(Oo,{children:$x(s).map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]}),f("planType")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),t(Mo,{value:e.typeId||"",onValueChange:e=>r("typeId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_type")})}),a(Oo,{children:h.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f("priority")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),t(Mo,{value:e.priorityType?.toString()||"",onValueChange:e=>r("priorityType",Number(e)),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_priority")})}),a(Oo,{children:Lx.map(e=>a($o,{value:e.id.toString(),children:t("span",{className:"flex items-center gap-2",children:[a("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:e.color}}),e.label]})},e.id))})]})]}),c.length>0&&t("div",{className:"space-y-2",children:[a(Hi,{children:m("ap_belongs_to")}),t(Mo,{value:e.parentId||"",onValueChange:e=>r("parentId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_parent")})}),a(Oo,{children:c.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[f("startDate")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),a(Tu,{date:e.startDate?new Date(e.startDate):void 0,onDateChange:e=>r("startDate",e||null),disabled:n,placeholder:m("ap_select_date")})]}),f("endDate")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),a(Tu,{date:e.endDate?new Date(e.endDate):void 0,onDateChange:e=>r("endDate",e||null),disabled:n,placeholder:m("ap_select_date"),disabledDates:e.startDate?a=>a<new Date(e.startDate):void 0})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:m("ap_duration_days")}),a(qi,{type:"number",value:v,disabled:!0,className:"bg-muted"})]})]}),f("estimatedCost")&&t("div",{className:"space-y-2 max-w-xs",children:[a(Hi,{className:Fi(g("estimatedCost")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Custo Estimado"}),t("div",{className:"relative",children:[a("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm",children:"R$"}),a(qi,{type:"number",min:0,step:.01,value:e.estimatedCost||"",onChange:e=>r("estimatedCost",Number(e.target.value)),disabled:n,className:"pl-9",placeholder:"0,00"})]})]}),f("cause")&&d.length>0&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Causa"}),t(Mo,{value:e.causeId||"",onValueChange:e=>r("causeId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_cause")})}),a(Oo,{children:d.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]}),f("description")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),a(Wo,{value:e.description||"",onChange:e=>r("description",e.target.value),maxLength:4e3,disabled:n,rows:4,placeholder:m("ap_description_placeholder")})]}),f("justification")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),a(Wo,{value:e.justification||"",onChange:e=>r("justification",e.target.value),maxLength:4e3,disabled:n,rows:4,placeholder:m("ap_justification_placeholder")})]})]})}function $x(e,a=0){const t=[];for(const r of e)t.push({...r,depth:a}),r.children?.length&&t.push(...$x(r.children,a+1));return t}function Vx(e){const{progress:a,onReportProgress:t,onEditProgress:r,onDeleteProgress:n}=e,[i,s]=o(!1),[d,c]=o(null),u=!!a&&Fx.includes(a.status),m=l(async e=>{if(t&&a){s(!0);try{const r=100===e.percentProgress;await t({id:a.id,...e,conclude:r})}finally{s(!1)}}},[t,a]),p=l(async e=>{if(r){s(!0);try{await r(e)}finally{s(!1),c(null)}}},[r]),h=l(async e=>{if(n){s(!0);try{await n(e)}finally{s(!1)}}},[n]);return{progress:a,canReportProgress:u,isSubmitting:i,editingReport:d,setEditingReport:c,reportProgress:m,editProgress:p,deleteProgress:h}}function qx(e){if(!e)return"";let a=(e||"").trim();if(!a)return"00:00";if(a.includes(":")){const e=a.split(":");if(e.length>=2){const a=e[0].replace(/\D/g,""),t=e[1].replace(/\D/g,"");let r=parseInt(a)||0,n=parseInt(t)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}if(a=a.replace(/\D/g,""),!a)return"00:00";let t=0,r=0;return 4===a.length?(t=parseInt(a.substring(0,2))||0,r=parseInt(a.substring(2,4))||0,t+=Math.floor(r/60),r%=60):(t=parseInt(a)||0,r=0),`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}function Wx(e){if(null==e)return"00:00";const a=String(e).replace(/\D/g,"");if(a.length<3){let e=parseInt(a)||0;const t=Math.floor(e/60);return e%=60,`${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}{const e=a.slice(-2),t=a.slice(0,-2);let r=parseInt(t)||0,n=parseInt(e)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}function Hx(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function Gx({open:e,onOpenChange:r,report:n,onSave:s,isSubmitting:l=!1}){const{t:d}=Ga(),[c,u]=o(n?.percentProgress||0),[m,p]=o(n?.timeProgress||""),[h,f]=o(n?.comments||""),g=c!==(n?.percentProgress??0)||m!==(n?.timeProgress??"")||h!==(n?.comments??"");i.useEffect(()=>{n&&(u(n.percentProgress),p(n.timeProgress||""),f(n.comments||""))},[n]);return a(mo,{open:e,onOpenChange:r,children:t(bo,{className:"sm:max-w-md",variant:"form",isDirty:g,children:[a(xo,{children:a(wo,{children:d("ap_edit_progress")})}),t("div",{className:"space-y-4 py-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:d("ap_progress_percent")}),a(qi,{type:"number",min:0,max:100,value:c,onChange:e=>u(Number(e.target.value))})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:d("ap_time_spent")}),a(qi,{value:m,onChange:e=>p(e.target.value),onBlur:()=>p(qx(m)||""),placeholder:"00:00"})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:d("ap_comments")}),a(Wo,{value:h,onChange:e=>f(e.target.value),rows:3,maxLength:4e3})]})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancelar"}),a($i,{onClick:()=>{n&&s({...n,percentProgress:c,timeProgress:qx(m)||"00:00",comments:h})},disabled:l,children:l?"Salvando...":"Salvar"})]})]})})}function Kx(e){const{t:r}=Ga(),{progress:n,canReportProgress:i,isSubmitting:s,editingReport:l,setEditingReport:d,reportProgress:c,editProgress:u,deleteProgress:m}=Vx(e),[p,h]=o(""),[f,g]=o(""),[v,b]=o("");if(!n)return a("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Sem dados de progresso disponíveis"});const x=Hx(n.percentProgress),y=!p,N=!p&&!f&&!v;return t("div",{className:"space-y-6 p-1",children:[t("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[t("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"font-medium",children:r("ap_overall_progress")}),t("span",{className:"font-semibold",style:{color:x||void 0},children:[n.percentProgress,"%"]})]}),a(Tm,{value:n.percentProgress,className:"h-3"}),n.timeProgress&&t("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",Wx(n.timeProgress)]})]}),i&&t("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[a("h4",{className:"text-sm font-medium",children:r("ap_report_progress")}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:r("ap_progress_percent")}),a(qi,{type:"number",min:0,max:100,value:p,onChange:e=>h(e.target.value),placeholder:"0"})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:r("ap_time_spent")}),a(qi,{value:f,onChange:e=>g(e.target.value),onBlur:()=>g(qx(f)||""),placeholder:"00:00"})]})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:r("ap_comments")}),a(Wo,{value:v,onChange:e=>b(e.target.value),rows:3,maxLength:4e3,placeholder:r("ap_progress_comment_placeholder")})]}),t("div",{className:"flex gap-2 justify-end",children:[a($i,{variant:"outline",size:"sm",onClick:()=>{h(""),g(""),b("")},disabled:N||s,children:"Limpar"}),a($i,{size:"sm",onClick:async()=>{const e=Number(p);(e||0===e)&&(await c({percentProgress:e,timeProgress:qx(f)||"00:00",comments:v}),h(""),g(""),b(""))},disabled:y||s,children:s?"Reportando...":"Reportar"})]})]}),n.reports.length>0&&t("div",{className:"space-y-3",children:[a("h4",{className:"text-sm font-medium",children:r("ap_reports_history")}),a("div",{className:"space-y-2",children:n.reports.map(e=>a(Yx,{report:e,onEdit:()=>d(e),onDelete:()=>m(e.id),disabled:!i},e.id))})]}),a(Gx,{open:!!l,onOpenChange:e=>!e&&d(null),report:l,onSave:u,isSubmitting:s})]})}function Yx({report:r,onEdit:n,onDelete:i,disabled:o}){const s=r.date?new Date(r.date):null,l=Hx(r.percentProgress);return t("div",{className:"flex items-start gap-3 rounded-lg border bg-card p-3",children:[a("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:r.userName?.charAt(0)?.toUpperCase()||"?"}),t("div",{className:"flex-1 min-w-0 space-y-1",children:[t("div",{className:"flex items-center gap-2 text-sm",children:[a("span",{className:"font-medium truncate",children:r.userName}),s&&a("span",{className:"text-xs text-muted-foreground",children:s.toLocaleDateString("pt-BR")})]}),t("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[t("span",{style:{color:l||void 0},className:"font-semibold",children:[r.percentProgress,"%"]}),r.timeProgress&&t("span",{children:["Tempo: ",Wx(r.timeProgress)]})]}),r.comments&&a("p",{className:"text-xs text-muted-foreground mt-1",children:r.comments})]}),!o&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[a(ss,{onClick:n,children:e.t("edit")}),a(ss,{className:"text-destructive",onClick:i,children:e.t("ap_delete")})]})]})]})}function Qx({predecessors:e=[],availablePredecessors:r=[],onAdd:n,onRemove:o,disabled:s=!1}){const{t:l}=Ga(),[d,c]=i.useState(""),u=r.filter(a=>!e.some(e=>e.predecessorId===a.id));return t("div",{className:"space-y-6 p-1",children:[!s&&u.length>0&&t("div",{className:"flex items-end gap-3",children:[t("div",{className:"flex-1 space-y-2",children:[a(Hi,{children:l("ap_add_predecessor")}),t(Mo,{value:d,onValueChange:c,children:[a(Fo,{children:a(zo,{placeholder:l("ap_select_action")})}),a(Oo,{children:u.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]}),t($i,{size:"sm",onClick:()=>{d&&n&&(n(d),c(""))},disabled:!d,children:[a(Q,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]}),e.length>0?a("div",{className:"space-y-2",children:e.map(e=>t("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[t("div",{className:"flex items-center gap-3",children:[e.predecessorCode&&a("span",{className:"text-xs text-muted-foreground font-mono",children:e.predecessorCode}),a("span",{className:"text-sm font-medium",children:e.predecessorName}),null!=e.predecessorStatus&&a(Ox,{status:e.predecessorStatus})]}),!s&&o&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),a(os,{align:"end",children:a(ss,{className:"text-destructive",onClick:()=>o(e.predecessorId),children:"Remover"})})]})]},e.id))}):a("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum predecessor adicionado"})]})}function Xx({costs:e=[],onAdd:r,onEdit:n,onDelete:i,disabled:s=!1}){const{t:l}=Ga(),[d,c]=o(""),[u,m]=o(""),p=e.reduce((e,a)=>e+(a.value||0),0);return t("div",{className:"space-y-6 p-1",children:[t("div",{className:"rounded-lg border bg-card p-4 flex items-center justify-between",children:[a("span",{className:"text-sm font-medium",children:l("ap_total_cost")}),t("span",{className:"text-lg font-semibold text-foreground",children:["R$ ",p.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),!s&&r&&t("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[a("h4",{className:"text-sm font-medium",children:l("ap_add_cost")}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:"Descrição"}),a(qi,{value:d,onChange:e=>c(e.target.value),placeholder:l("ap_cost_description")})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:"Valor (R$)"}),a(qi,{type:"number",min:0,step:.01,value:u,onChange:e=>m(e.target.value),placeholder:"0,00"})]})]}),a("div",{className:"flex justify-end",children:t($i,{size:"sm",onClick:()=>{d&&u&&r&&(r({description:d,value:Number(u),date:(new Date).toISOString()}),c(""),m(""))},disabled:!d||!u,children:[a(Q,{className:"h-4 w-4 mr-1"}),"Adicionar"]})})]}),e.length>0?a("div",{className:"space-y-2",children:e.map(e=>t("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[t("div",{className:"flex-1 min-w-0",children:[a("p",{className:"text-sm font-medium truncate",children:e.description}),e.date&&a("p",{className:"text-xs text-muted-foreground",children:new Date(e.date).toLocaleDateString("pt-BR")})]}),t("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-semibold whitespace-nowrap",children:["R$ ",e.value.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!s&&(n||i)&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[n&&a(ss,{onClick:()=>n(e),children:l("edit")}),i&&a(ss,{className:"text-destructive",onClick:()=>i(e.id),children:l("ap_delete")})]})]})]})]},e.id))}):a("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum custo registrado"})]})}function Jx({comments:e=[],currentUserId:r,onAdd:n,onEdit:i,onDelete:s,disabled:l=!1,maxLength:d=4e3}){const{t:c}=Ga(),[u,m]=o(""),[p,h]=o(!1),[f,g]=o(null),[v,b]=o(""),x=()=>{g(null),b("")};return t("div",{className:"space-y-6 p-1",children:[!l&&n&&t("div",{className:"space-y-3",children:[a(Wo,{value:u,onChange:e=>m(e.target.value),placeholder:c("ap_add_comment_placeholder"),maxLength:d,rows:3}),t("div",{className:"flex items-center justify-between",children:[d&&t("span",{className:"text-xs text-muted-foreground",children:[u.length,"/",d]}),t("div",{className:"flex gap-2 ml-auto",children:[a($i,{variant:"outline",size:"sm",onClick:()=>m(""),disabled:!u||p,children:"Limpar"}),a($i,{size:"sm",onClick:async()=>{if(u.trim()&&n){h(!0);try{await n(u),m("")}finally{h(!1)}}},disabled:!u.trim()||p,children:p?"Enviando...":"Comentar"})]})]})]}),t("div",{className:"space-y-1",children:[e.length>0?t("div",{className:"flex items-center gap-2 mb-3",children:[a("span",{className:"text-sm font-medium",children:c("ap_comments")}),a(Go,{variant:"info",className:"text-[10px] px-1.5 py-0",children:e.length})]}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[a(_a,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:"Nenhum comentário adicionado"})]}),e.map(e=>t("div",{className:"flex gap-3 rounded-lg border bg-card p-3",children:[a("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground overflow-hidden",children:e.userPhotoUrl?a("img",{src:e.userPhotoUrl,alt:e.userName,className:"h-full w-full object-cover"}):e.userName?.charAt(0)?.toUpperCase()||"?"}),t("div",{className:"flex-1 min-w-0 space-y-1",children:[t("div",{className:"flex items-center gap-2 text-sm",children:[a("span",{className:"font-medium truncate",children:e.userName}),e.userEmail&&a("span",{className:"text-xs text-muted-foreground truncate",children:e.userEmail}),a("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:Zx(e.dateEdited||e.dateCreation)}),e.dateEdited&&a("span",{className:"text-xs text-muted-foreground italic",children:"editado"})]}),f===e.id?t("div",{className:"space-y-2",children:[a(Wo,{value:v,onChange:e=>b(e.target.value),maxLength:d,rows:3}),t("div",{className:"flex gap-2 justify-end",children:[a($i,{variant:"outline",size:"sm",onClick:x,disabled:p,children:"Cancelar"}),a($i,{size:"sm",onClick:()=>(async e=>{if(v.trim()&&i){h(!0);try{await i({...e,text:v,stringText:v}),g(null),b("")}finally{h(!1)}}})(e),disabled:!v.trim()||p,children:p?"Salvando...":"Salvar"})]})]}):a("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:e.stringText||e.text})]}),!l&&r===e.userId&&f!==e.id&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[i&&a(ss,{onClick:()=>(e=>{g(e.id),b(e.stringText||e.text)})(e),children:c("edit")}),s&&a(ss,{className:"text-destructive",onClick:()=>(async e=>{if(s){h(!0);try{await s(e)}finally{h(!1)}}})(e.id),children:"Excluir"})]})]})]},e.id))]})]})}function Zx(e){const{t:a}=Ga();if(!e)return"";const t=new Date(e);return`${t.toLocaleDateString("pt-BR")} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function ey({history:e=[],isLoading:r=!1}){const{t:n}=Ga();return r?a("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Carregando histórico..."}):0===e.length?t("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[a(We,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:n("ap_no_history")})]}):a("div",{className:"p-1",children:t("div",{className:"relative",children:[a("div",{className:"absolute left-4 top-0 bottom-0 w-px bg-border"}),a("div",{className:"space-y-0",children:e.map((e,r)=>t("div",{className:"relative flex gap-4 pb-6 last:pb-0",children:[a("div",{className:"relative z-10 flex-shrink-0 h-8 w-8 rounded-full bg-primary/10 border-2 border-primary/30 flex items-center justify-center",children:e.icon?a("span",{className:"text-xs text-primary",children:e.icon}):a("div",{className:"h-2 w-2 rounded-full bg-primary"})}),t("div",{className:"flex-1 min-w-0 rounded-lg border bg-card p-3 space-y-2",children:[t("div",{children:[a("h4",{className:"text-sm font-medium",children:e.translateEvent||e.eventName}),e.eventDescription&&a("p",{className:"text-xs text-muted-foreground",children:e.eventDescription})]}),t("div",{className:"flex items-center gap-2",children:[a("div",{className:"flex-shrink-0 h-6 w-6 rounded-full bg-muted overflow-hidden flex items-center justify-center text-[10px] font-medium text-muted-foreground",children:e.userPhotoUrl?a("img",{src:e.userPhotoUrl,alt:e.userName,className:"h-full w-full object-cover"}):e.userName?.charAt(0)?.toUpperCase()||"?"}),t("div",{className:"min-w-0",children:[a("span",{className:"text-xs font-medium truncate block",children:e.userName}),e.userEmail&&a("span",{className:"text-[10px] text-muted-foreground truncate block",children:e.userEmail})]})]}),t("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[t("div",{className:"flex items-center gap-1",children:[a(ye,{className:"h-3 w-3"}),a("span",{children:ay(e.date)})]}),t("div",{className:"flex items-center gap-1",children:[a(We,{className:"h-3 w-3"}),a("span",{children:ty(e.date)})]}),e.isMobileRequest&&t("div",{className:"flex items-center gap-1",children:[a(Ca,{className:"h-3 w-3"}),a("span",{children:n("ap_via_app")})]})]})]})]},e.id))})]})})}function ay(e){const{t:a}=Ga();return new Date(e).toLocaleDateString("pt-BR")}function ty(e){const{t:a}=Ga();return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function ry({attachments:e=[],onUpload:n,onDelete:i,onRename:s,onDownload:l,onView:d,disabled:c=!1}){const{t:m}=Ga(),p=u(null),[h,f]=o(null),[g,v]=o(""),b=async e=>{g.trim()&&s&&(await s(e.id,g),f(null),v(""))},x=()=>{f(null),v("")};return t("div",{className:"space-y-4 p-1",children:[!c&&n&&t(r,{children:[a("input",{ref:p,type:"file",multiple:!0,className:"hidden",onChange:e=>{const a=e.target.files;if(a&&n){for(let e=0;e<a.length;e++){const t=a.item(e);t&&n(t)}p.current&&(p.current.value="")}}}),t($i,{size:"sm",onClick:()=>p.current?.click(),children:[a(Q,{className:"h-4 w-4 mr-1"}),"Adicionar anexo"]})]}),e.length>0?a("div",{className:"space-y-2",children:e.map(e=>t("div",{className:Fi("flex items-center gap-3 rounded-lg border bg-card p-3",e.status===kx.error&&"border-destructive/50 bg-destructive/5",e.status===kx.canceled&&"opacity-50"),children:[a("div",{className:"flex-shrink-0 h-9 w-9 rounded bg-muted flex items-center justify-center",children:a("span",{className:"text-[10px] font-bold uppercase text-muted-foreground",children:e.extension.replace(".","").substring(0,4)})}),t("div",{className:"flex-1 min-w-0 space-y-1",children:[h===e.id?t("div",{className:"flex items-center gap-2",children:[a("input",{className:"flex-1 text-sm border rounded px-2 py-1 bg-background",value:g,onChange:e=>v(e.target.value),onKeyDown:a=>{"Enter"===a.key&&b(e),"Escape"===a.key&&x()},autoFocus:!0}),a($i,{size:"sm",variant:"outline",onClick:x,children:m("cancel")}),a($i,{size:"sm",onClick:()=>b(e),children:m("save")})]}):a("button",{type:"button",className:"text-sm font-medium truncate block text-left hover:underline cursor-pointer",onClick:()=>d?.(e.id),children:e.name}),(e.status===kx.uploading||e.status===kx.waiting)&&a(Tm,{value:e.progress||0,className:"h-1.5"}),e.status===kx.error&&a("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),e.status===kx.duplicateItem&&a("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),e.status===kx.canceled&&a("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),t("div",{className:"flex items-center gap-2",children:[e.status===kx.done&&t(r,{children:[a("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:ny(e.size)}),t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[s&&!c&&a(ss,{onClick:()=>(e=>{const a=e.name.replace(e.extension,"");f(e.id),v(a)})(e),children:"Renomear"}),d&&a(ss,{onClick:()=>d(e.id),children:"Visualizar"}),l&&a(ss,{onClick:()=>l(e.id),children:"Download"}),i&&!c&&t(r,{children:[a(us,{}),a(ss,{className:"text-destructive",onClick:()=>i(e.id),children:"Excluir"})]})]})]})]}),e.status===kx.uploading&&a($i,{variant:"outline",size:"sm",onClick:()=>i?.(e.id),children:"Cancelar"})]})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[a(ka,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function ny(e){const{t:a}=Ga();if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,t)).toFixed(1))} ${["B","KB","MB","GB"][t]}`}function iy(e){const{formData:r,isLoading:n,isSaving:i,activeTab:o,isFormDisabled:s,updateField:l,setActiveTab:d,save:c,changeStatus:u,remove:m,cancel:p}=Ux(e),{t:h}=Ga(),{isNew:f=!1,config:g,users:v,places:b,actionTypes:x,causes:y,parentActions:N,progress:w,predecessors:_,availablePredecessors:C,costs:k,comments:S,history:A,attachments:E,attachmentsSlot:D,commentsSlot:P,historySlot:I,onAddPredecessor:T,onRemovePredecessor:R,onAddCost:M,onEditCost:L,onDeleteCost:z,onAddComment:F,onEditComment:U,onDeleteComment:j,onUploadAttachment:O,onDeleteAttachment:B,onRenameAttachment:$,onDownloadAttachment:V,onViewAttachment:q}=e;if(n&&!r.id)return a(Qo,{isLoading:!0,children:a("div",{})});const W=function(e){const{t:a}=Ga();if(!e)return[];return{[vx.waitingStart]:[vx.running,vx.suspended,vx.canceled],[vx.running]:[vx.effectivenessCheck,vx.done,vx.suspended,vx.canceled],[vx.effectivenessCheck]:[vx.running,vx.done,vx.suspended,vx.canceled],[vx.done]:[vx.running],[vx.suspended]:[vx.running,vx.canceled],[vx.canceled]:[vx.waitingStart]}[e]||[]}(r.statusId);return t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex items-center justify-between border-b bg-card px-6 py-4",children:[t("div",{className:"flex items-center gap-4",children:[p&&a($i,{variant:"ghost",size:"icon",onClick:p,children:a(je,{className:"h-4 w-4"})}),t("div",{className:"space-y-1",children:[t("div",{className:"flex items-center gap-3",children:[a("h1",{className:"text-lg font-semibold",children:f?h("ap_new_action"):r.name||h("ap_action_plan")}),!f&&r.statusId&&a(Ox,{status:r.statusId})]}),r.code&&a("p",{className:"text-xs text-muted-foreground font-mono",children:r.code})]})]}),t("div",{className:"flex items-center gap-2",children:[!f&&W.length>0&&!s&&t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"outline",size:"sm",children:"Alterar Status"})}),a(os,{align:"end",children:W.map(e=>a(ss,{onClick:()=>u(e),children:Ix[e]},e))})]}),!f&&e.onDelete&&t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",children:a(ra,{className:"h-4 w-4"})})}),a(os,{align:"end",children:a(ss,{className:"text-destructive",onClick:m,children:"Excluir"})})]})]})]}),a("div",{className:"flex-1 min-h-0 overflow-y-auto",children:a("div",{className:"max-w-4xl mx-auto px-6 py-6",children:t(Pc,{value:o,onValueChange:d,children:[t(Ic,{className:"mb-6",children:[a(Tc,{value:"general",children:"Geral"}),!f&&a(Tc,{value:"progress",children:"Progresso"}),!f&&g?.enablePredecessors&&a(Tc,{value:"predecessors",children:h("ap_predecessors")}),!f&&g?.enableCosts&&a(Tc,{value:"costs",children:"Custos"}),!f&&g?.enableAttachments&&a(Tc,{value:"attachments",children:h("ap_attachments")}),!f&&g?.enableComments&&a(Tc,{value:"comments",children:h("ap_comments")}),!f&&g?.enableHistory&&a(Tc,{value:"history",children:"Histórico"})]}),a(Rc,{value:"general",children:a(Bx,{formData:r,updateField:l,disabled:s,users:v,places:b,actionTypes:x,causes:y,parentActions:N,config:g})}),!f&&a(Rc,{value:"progress",children:a(Kx,{...e})}),!f&&g?.enablePredecessors&&a(Rc,{value:"predecessors",children:a(Qx,{predecessors:_,availablePredecessors:C,onAdd:T,onRemove:R,disabled:s})}),!f&&g?.enableCosts&&a(Rc,{value:"costs",children:a(Xx,{costs:k,onAdd:M,onEdit:L,onDelete:z,disabled:s})}),!f&&g?.enableAttachments&&a(Rc,{value:"attachments",children:D||a(ry,{attachments:E,onUpload:O,onDelete:B,onRename:$,onDownload:V,onView:q,disabled:s})}),!f&&g?.enableComments&&a(Rc,{value:"comments",children:P||a(Jx,{comments:S,onAdd:F,onEdit:U,onDelete:j,disabled:s})}),!f&&g?.enableHistory&&a(Rc,{value:"history",children:I||a(ey,{history:A})})]})})}),t("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[p&&a($i,{variant:"outline",onClick:p,disabled:i,children:"Cancelar"}),a($i,{onClick:c,disabled:i||s,children:i?"Salvando...":"Salvar"})]})]})}const oy=["application/x-msdownload","application/x-msdos-program","application/x-executable","application/x-javascript","application/javascript","text/javascript","text/vbscript","application/sql","application/x-sh","application/x-shellscript","application/hta","application/vnd.ms-word.document.macroEnabled.12","application/vnd.ms-excel.sheet.macroEnabled.12","application/vnd.ms-powerpoint.presentation.macroEnabled.12"];function sy(e){if(!e)return"";if(e<1024)return`${e} Bytes`;const a=e/1024;if(a<1024)return`${Math.round(a)} KB`;const t=a/1024;if(t<1024)return`${Math.round(t)} MB`;const r=t/1024;return Math.round(100*r)/100+" GB"}function ly(e){const a=e.lastIndexOf(".");return-1===a?"":e.substring(a+1).toLowerCase()}function dy({storedFile:e,customFileName:r,allowedExtensions:n,customExtensionErrorMessage:i,minSizeInBytes:s=1,maxSizeInBytes:d=314572800,showDownloadButton:c=!0,showViewButton:m=!0,showReplaceButton:p=!0,showCloseButton:h=!0,required:f=!1,touched:g=!1,disabled:v=!1,error:b,onFileSelect:x,onFileRemove:y,onFileReplace:N,onDownload:w,onView:_,className:C}){const{t:k}=Ga(),S=u(null),[A,D]=o(null),[P,I]=o(null),[T,R]=o(!1),M=A||e,L=A?.name||e?.name||"",z=A?.size||e?.size;L&&ly(L);const F=r||L,U=c&&!A&&!!e,j=m&&!A&&!!e,O=!!P||!!b||f&&g&&!M,B=!!M,$=l(e=>{if(oy.includes(e.type))return{type:"forbidden-type"};if(e.size<=s)return{type:"min-size"};if(e.size>=d)return{type:"max-size"};if(n?.length){const a=ly(e.name);if(!n.includes(a))return{type:"extension",message:i}}return null},[s,d,n,i]),V=l(e=>{const a=e.target.files?.[0];if(!a)return;const t=$(a);if(t)return I(t),D(null),void(S.current&&(S.current.value=""));I(null),D(a),x?.(a),S.current&&(S.current.value="")},[$,x]),q=l(e=>{if(e.preventDefault(),e.stopPropagation(),v)return;const a=e.dataTransfer.files?.[0];if(!a)return;const t=$(a);if(t)return I(t),void D(null);I(null),D(a),x?.(a)},[v,$,x]),W=l(e=>{e.preventDefault(),e.stopPropagation()},[]),H=l(()=>{N?.(),S.current?.click()},[N]),G=l(()=>{D(null),I(null),y?.(),S.current&&(S.current.value="")},[y]),K=l(async()=>{if(!T&&e&&w){R(!0);try{await w(e)}finally{R(!1)}}},[T,e,w]),Y=l(()=>{e&&_&&_(e)},[e,_]),Q=l(()=>{v||S.current?.click()},[v]),X=(()=>{if(b)return b;if(!P)return f&&g&&!M?k("required_field"):null;switch(P.type){case"extension":return P.message||k("sign_file_not_allowed");case"forbidden-type":return k("sign_file_type_not_allowed");case"min-size":return`Tamanho mínimo: ${sy(s)}`;case"max-size":return`Tamanho máximo: ${sy(d)}`;default:return k("file_error")}})();return t("div",{className:Fi("space-y-1",C),children:[a("div",{className:Fi("rounded-md border border-dashed transition-colors",B&&"border-solid border-border",!B&&"border-muted-foreground/30 hover:border-primary/50 cursor-pointer",O&&"border-destructive border-solid",v&&"opacity-50 pointer-events-none"),children:t("div",B?{className:"flex items-center justify-between px-3 min-h-[36px]",children:[t("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[a(Be,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a("p",{className:"text-xs truncate",children:F})]}),t("div",{className:"flex items-center gap-2 shrink-0",children:[null!=z&&a("span",{className:"text-xs text-muted-foreground",children:sy(z)}),t("div",{className:"flex items-center gap-0.5",children:[U&&w&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:T,onClick:K,children:a(Je,{className:"h-3.5 w-3.5 text-primary"})})}),a(gs,{children:"Download"})]}),j&&_&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:Y,children:a(Ce,{className:"h-3.5 w-3.5 text-primary"})})}),a(gs,{children:"Visualizar"})]}),p&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:H,children:a(ue,{className:"h-3.5 w-3.5 text-primary"})})}),a(gs,{children:"Substituir"})]}),h&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:G,children:a(E,{className:"h-3 w-3 text-muted-foreground"})})}),a(gs,{children:k("remove")})]})]})]})]}:{className:"flex items-center justify-center gap-2 min-h-[36px] px-3",tabIndex:0,onClick:Q,onKeyDown:e=>"Enter"===e.key&&Q(),onDrop:q,onDragOver:W,children:[a(Sa,{className:"h-4 w-4 text-muted-foreground"}),t("p",{className:"text-xs font-medium text-muted-foreground",children:["Arraste ou ",a("span",{className:"text-primary",children:"selecione um arquivo"})]})]})}),X&&a("p",{className:"text-xs text-destructive",children:X}),a("input",{ref:S,type:"file",className:"hidden",accept:n?.map(e=>`.${e}`).join(","),onChange:V,disabled:v})]})}var cy,uy,my,py,hy,fy;function gy(e){switch(e.type){case cy.text:return e.textValue;case cy.number:return e.numberValue;case cy.date:return e.dateValue;case cy.time:return e.timeValue;case cy.url:case cy.singleSelection:case cy.multiSelection:return e.itemsValue;case cy.questions:return e.questionsValue;case cy.readOnlyText:return e.textValue;default:return null}}function vy(e,a){if(!a)return!0;const t=null!=gy(e)&&""!==gy(e)&&!(Array.isArray(gy(e))&&0===gy(e).length);return!1!==e.isActive||t}function by(e){return e.filter(e=>e.type!==cy.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===cy.text?e.textValue:void 0,numberValue:e.type===cy.number?e.numberValue:void 0,dateValue:e.type===cy.date?e.dateValue:void 0,timeValue:e.type===cy.time?e.timeValue:void 0,itemsValue:[cy.url,cy.singleSelection,cy.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===cy.questions?e.questionsValue:void 0}))}function xy(e,a){return a?.length?e.map(e=>{const t=a.find(a=>a.formFieldAssociationId===e.id);if(!t)return e;const r={...e};switch(e.type){case cy.text:r.textValue=t.textValue;break;case cy.number:r.numberValue=t.numberValue;break;case cy.date:r.dateValue=t.dateValue;break;case cy.time:r.timeValue=t.timeValue;break;case cy.url:case cy.singleSelection:case cy.multiSelection:r.itemsValue=t.itemsValue||[];break;case cy.questions:r.questionsValue=t.questionsValue||[]}return r}):e}function yy(e){const a=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===cy.readOnlyText)return;const t=gy(e);if((null==t||""===t||Array.isArray(t)&&0===t.length)&&a.push(e.id),e.type===cy.number&&null!=t){const r=e.config;null!=r?.min&&t<r.min&&a.push(e.id),null!=r?.max&&t>r.max&&a.push(e.id)}}),{valid:0===a.length,invalidFields:[...new Set(a)]}}function Ny({field:e}){return t("div",{className:"space-y-1",children:[e.name&&a("p",{className:"text-sm font-medium text-foreground",children:e.name}),e.description&&a("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:e.description}),e.textValue&&a("p",{className:"text-sm text-muted-foreground italic",children:e.textValue})]})}function wy({field:e,readOnly:r,onChange:n}){const i=e.config,o=i?.multiline??!1,s=r||e.readOnly,l=a=>{n?.({...e,textValue:a})};return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),o?a(Wo,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:s,rows:4}):a(qi,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:s})]})}function _y({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,o=e.dateValue?"string"==typeof e.dateValue?e.dateValue.substring(0,10):new Date(e.dateValue).toISOString().substring(0,10):"";return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a(qi,{type:"date",value:o,onChange:a=>{return t=a.target.value,void n?.({...e,dateValue:t||void 0});var t},placeholder:e.placeholder,disabled:i})]})}function Cy({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,o=e=>{if(!e)return;const[a,t]=e.split(":").map(Number);return 60*a+t};return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a(qi,{type:"time",value:(e=>{if(null==e)return"";const a=e%60;return`${Math.floor(e/60).toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`})(e.timeValue),onChange:a=>n?.({...e,timeValue:o(a.target.value)}),placeholder:e.placeholder,disabled:i})]})}function ky({field:e,readOnly:r,onChange:n}){const i=e.config,s=i?.multiple??!1,l=r||e.readOnly,[d,c]=o(""),u=e.itemsValue||[],m=()=>{if(!d.trim())return;const a={value:crypto.randomUUID(),text:d.trim()};n?.({...e,itemsValue:[...u,a]}),c("")};if(!s){const r=u[0]?.text||"";return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),t("div",{className:"flex items-center gap-2",children:[a(qi,{type:"url",value:r,onChange:a=>(a=>{const t={value:a,text:a};n?.({...e,itemsValue:a?[t]:[]})})(a.target.value),placeholder:e.placeholder||"https://",disabled:l}),r&&a($i,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:a("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:a(pe,{className:"h-4 w-4"})})})]})]})}return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),!l&&t("div",{className:"flex items-center gap-2",children:[a(qi,{type:"url",value:d,onChange:e=>c(e.target.value),placeholder:e.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),a($i,{variant:"outline",size:"icon",onClick:m,disabled:!d.trim(),className:"flex-shrink-0",children:a(Q,{className:"h-4 w-4"})})]}),u.length>0&&a("div",{className:"space-y-1",children:u.map((r,i)=>t("div",{className:"flex items-center gap-2 text-sm",children:[a("a",{href:r.text,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline truncate flex-1",children:r.text}),!l&&a($i,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>(a=>{const t=u.filter((e,t)=>t!==a);n?.({...e,itemsValue:t})})(i),children:a(H,{className:"h-3 w-3"})})]},r.value))})]})}function Sy({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=null!=i?.decimals&&i.decimals>0?(1/Math.pow(10,i.decimals)).toString():"1";return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a(qi,{type:"number",value:e.numberValue??"",onChange:a=>(a=>{if(""===a)return void n?.({...e,numberValue:void 0});const t=parseFloat(a);isNaN(t)||n?.({...e,numberValue:t})})(a.target.value),placeholder:e.placeholder,disabled:o,min:i?.min,max:i?.max,step:s}),null!=i?.min&&null!=i?.max&&t("p",{className:"text-xs text-muted-foreground",children:["Min: ",i.min," | Max: ",i.max]})]})}function Ay({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=i?.viewMode??my.dropdown,l=i?.data?.filter(a=>!1!==a.isActive||e.itemsValue?.some(e=>e.value===a.value))||[],d=e.itemsValue?.[0]?.value||"",c=a=>{const t=l.find(e=>e.value===a);if(!t)return;const r={value:t.value,text:t.text,isActive:t.isActive};n?.({...e,itemsValue:[r]})};return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),s===my.dropdown&&t(Mo,{value:d,onValueChange:c,disabled:o,children:[a(Fo,{children:a(zo,{placeholder:e.placeholder||"Selecione..."})}),a(Oo,{children:l.map(e=>t($o,{value:e.value,children:[e.text,!1===e.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},e.value))})]}),(s===my.radio||s===my.buttons)&&a(Rm,{value:d,onValueChange:c,disabled:o,className:Fi(s===my.buttons?"flex flex-wrap gap-2":"space-y-2"),children:l.map(r=>t("div",{className:"flex items-center gap-2",children:[a(Mm,{value:r.value,id:`${e.id}-${r.value}`}),t(Hi,{htmlFor:`${e.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))}),!o&&d&&!e.required&&a("button",{type:"button",onClick:()=>{n?.({...e,itemsValue:[]})},className:"text-xs text-muted-foreground hover:text-foreground underline",children:"Limpar seleção"})]})}function Ey({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=i?.viewMode??my.dropdown,l=i?.data?.filter(a=>!1!==a.isActive||e.itemsValue?.some(e=>e.value===a.value))||[],d=new Set(e.itemsValue?.map(e=>e.value)||[]);return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),(e.itemsValue?.length??0)>0&&a("div",{className:"flex flex-wrap gap-1.5",children:e.itemsValue.map(r=>t(Go,{variant:"secondary",className:"gap-1 pr-1",children:[a("span",{className:"text-xs",children:r.text}),!o&&a("button",{type:"button",onClick:()=>(a=>{const t=(e.itemsValue||[]).filter(e=>e.value!==a);n?.({...e,itemsValue:t})})(r.value),className:"rounded-full p-0.5 hover:bg-muted-foreground/20",children:a(E,{className:"h-3 w-3"})})]},r.value))}),!o&&a("div",{className:Fi(s===my.checkbox?"space-y-2":"grid grid-cols-2 gap-2 border rounded-md p-3 max-h-48 overflow-y-auto"),children:l.map(r=>t("div",{className:"flex items-center gap-2",children:[a(qo,{id:`${e.id}-${r.value}`,checked:d.has(r.value),onCheckedChange:()=>(a=>{const t=e.itemsValue||[],r=t.some(e=>e.value===a.value)?t.filter(e=>e.value!==a.value):[...t,{value:a.value,text:a.text,isActive:a.isActive}];n?.({...e,itemsValue:r})})(r),disabled:o}),t(Hi,{htmlFor:`${e.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))})]})}function Dy({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=i?.questions||[],l=i?.options||[],d=e.questionsValue||[];return 0===s.length||0===l.length?t("div",{className:"space-y-1.5",children:[a(Hi,{children:e.name}),a("p",{className:"text-xs text-muted-foreground",children:"Nenhuma questão configurada"})]}):t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a("div",{className:"border rounded-md overflow-x-auto",children:t("table",{className:"w-full text-sm",children:[a("thead",{children:t("tr",{className:"border-b bg-muted/50",children:[a("th",{className:"text-left p-2 font-medium min-w-[150px]",children:"Pergunta"}),l.map(e=>a("th",{className:"text-center p-2 font-medium min-w-[80px]",children:e.text},e.value))]})}),a("tbody",{children:s.map((r,i)=>t("tr",{className:Fi(i<s.length-1&&"border-b"),children:[a("td",{className:"p-2 text-muted-foreground",children:r.text}),l.map(t=>{return a("td",{className:"text-center p-2",children:a(Rm,{value:(i=r.value,d.find(e=>e.questionValue===i)?.optionValue||""),onValueChange:a=>((a,t,r,i)=>{const o={questionValue:a,questionText:t,optionValue:r,optionText:i},s=d.filter(e=>e.questionValue!==a);s.push(o),n?.({...e,questionsValue:s})})(r.value,r.text,a,t.text),disabled:o,className:"flex justify-center",children:a(Mm,{value:t.value,id:`${e.id}-${r.value}-${t.value}`})})},t.value);var i})]},r.value))})]})})]})}function Py({fields:e,readOnly:t=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:i}){const o=l(a=>{if(i?.(a),n){const t=e.map(e=>e.id===a.id?a:e);n(t)}},[e,n,i]),s=e.filter(e=>vy(e,r));return 0===s.length?null:a("div",{className:"space-y-4",children:s.map(e=>a(Iy,{field:e,readOnly:t,onChange:o},e.id))})}function Iy({field:e,readOnly:t,onChange:r}){const n={field:e,readOnly:t,onChange:r};switch(e.type){case cy.readOnlyText:return a(Ny,{...n});case cy.text:return a(wy,{...n});case cy.date:return a(_y,{...n});case cy.time:return a(Cy,{...n});case cy.url:return a(ky,{...n});case cy.number:return a(Sy,{...n});case cy.singleSelection:return a(Ay,{...n});case cy.multiSelection:return a(Ey,{...n});case cy.questions:return a(Dy,{...n});default:return null}}function Ty({queryParams:e,events:r,softwares:n,users:i=[],permissions:s={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:d=!1,onFilter:c,onReset:u,onExport:m,onSoftwareChange:p}){const[h,f]=o(e.softwareId),[g,v]=o(e.eventId),[b,x]=o(e.userId||"all"),[y,N]=o(Ry(e.startDate)),[w,_]=o(Ry(e.endDate)),C=l(e=>{const a=parseInt(e);f(a),p?.(a)},[p]),k=l(()=>{c({...e,softwareId:h,eventId:g,userId:"all"===b?void 0:b,startDate:new Date(y),endDate:new Date(w),software:n.find(e=>e.id===h)?.software||e.software,event:r.find(e=>e.id===g)?.name||e.event})},[e,h,g,b,y,w,n,r,c]),S=l(()=>{const a=new Date;a.setHours(0,0,0,0),N(Ry(a)),_(Ry(a)),v(e.eventId),s.viewAllEvents&&x("all"),u?.()},[e.eventId,s.viewAllEvents,u]),A=s.viewOnlyMyEvents&&!s.viewAllEvents,E=h&&g&&y&&w;return t("div",{className:"flex flex-wrap items-end gap-3 rounded-lg border border-border bg-card p-3",children:[t("div",{className:"flex flex-col gap-1 min-w-[180px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Módulo *"}),t(Mo,{value:String(h),onValueChange:C,disabled:d,children:[a(Fo,{className:"h-8 text-xs",children:a(zo,{placeholder:"Selecione..."})}),a(Oo,{children:n.map(e=>a($o,{value:String(e.id),className:"text-xs",children:e.translation},e.id))})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Evento *"}),t(Mo,{value:String(g),onValueChange:e=>v(parseInt(e)),disabled:d,children:[a(Fo,{className:"h-8 text-xs",children:a(zo,{placeholder:"Selecione..."})}),a(Oo,{children:r.map(e=>a($o,{value:String(e.id),className:"text-xs",children:e.translation},e.id))})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Usuário *"}),t(Mo,{value:b,onValueChange:x,disabled:d||A,children:[a(Fo,{className:"h-8 text-xs",children:a(zo,{placeholder:"Selecione..."})}),t(Oo,{children:[a($o,{value:"all",className:"text-xs",children:"Todos"}),i.map(e=>a($o,{value:e.id,className:"text-xs",children:e.name},e.id))]})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"De *"}),a(qi,{type:"date",value:y,onChange:e=>N(e.target.value),className:"h-8 text-xs",max:w,disabled:d})]}),t("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Até *"}),a(qi,{type:"date",value:w,onChange:e=>_(e.target.value),className:"h-8 text-xs",min:y,disabled:d})]}),t("div",{className:"flex items-center gap-2 ml-auto",children:[t($i,{variant:"outline",size:"sm",onClick:S,disabled:d,children:[a(Aa,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),s.download&&m&&t($i,{variant:"outline",size:"sm",onClick:()=>m("xlsx"),disabled:d,children:[a(Je,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),t($i,{size:"sm",onClick:k,disabled:d||!E,children:[a(Ea,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function Ry(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function My(e,a,t,r="Anônimo"){return e.map(e=>({...e,translatedSoftware:zy(e.software,t),user:e.userEmail||e.userName||r,translatedEvent:Ly(e.eventName,a),date:new Date(e.dateTime)})).sort((e,a)=>(a.date?.getTime()??0)-(e.date?.getTime()??0))}function Ly(e,a){const t=a.find(a=>a.name===e);return t?.translation||e}function zy(e,a){const t=e.includes(".")?e.split(".").pop():e,r=a.find(e=>e.software===t);return r?.translation||t}function Fy(e,a){const t=[],r={...qy,...a?.labels},n=e.eventName;t.push({name:r.event,value:n});const i=e.entities?.[0];if(i&&(t.push({name:r.entityName,value:Uy(i)}),i.description&&t.push({name:r.description,value:i.description}),i.justification&&t.push({name:r.justification,value:i.justification}),i.statusName&&t.push({name:r.status,value:i.statusName}),i.equipmentType&&t.push({name:r.type,value:i.equipmentType}),i.extra?.length)){[...new Set(i.extra.map(e=>e.property))].forEach(e=>{const a=i.extra.filter(a=>a.property===e).map(e=>e.value||"").join(", ");t.push({name:$y(e),value:a})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const i=jy(e,n,a?.translateProperty),o=Oy(e,null,n,r,a);o&&t.push({name:i,value:o})})}),e.entities?.forEach(e=>{if(e.association?.length){const a=e.association.filter(e=>""!==e.id).map(e=>{const a=Uy(e);return`(${e.softwareName||e.type}) ${a}`});a.length&&t.push({name:r.references,value:a.join(", ")})}}),i?.isElectronicSigned&&t.push({name:r.security,value:"🛡️ "+r.electronicSigned}),t.push({name:r.accomplishedBy,value:e.userName?`${e.userName} (${e.userEmail})`:e.userEmail});const o=a?.formatDate?a.formatDate(e.dateTime):Vy(e.dateTime);return t.push({name:r.accomplishedIn,value:o}),t}function Uy(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function jy(e,a,t){if(e.propertyCustomName)return e.propertyCustomName;const r=$y(e.property);return t?t(a,r):r}function Oy(e,a,t,r,n){if(e.propertyResource||(e.propertyResource=a?`${a.propertyResource}.${e.property}`:e.property),e.children?.length){if(e.newValue){const a=jy(e,t,n?.translateProperty),i=function(e,a){switch(e.state){case"Added":return a.stateAdded;case"Modified":return e.children?.some(e=>"Removed"===e.property)?a.stateRemoved:a.stateModified;default:return""}}(e,r);let o=`${a}: "${By(e,"newValue",r,n)}" ${i}`;const s=e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Oy(a,e,t,r,n)));return s.some(Boolean)&&(o+="\n"+s.filter(Boolean).join("\n")),o}return e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Oy(a,e,t,r,n))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const i=By(e,"oldValue",r,n),o=By(e,"newValue",r,n);return`${a?jy(e,t,n?.translateProperty)+": ":""}${r.changedFrom} "${i}" ${r.changedTo} "${o}"`}const i=By(e,"newValue",r,n);return a?`${jy(e,t,n?.translateProperty)}: ${i}`:i}function By(e,a,t,r){const n=e[a];return null==n||""===n?"Modified"===e.state||"Added"===e.state||"Unchanged"===e.state?t.uninformed:"":"string"==typeof n&&function(e){if("string"!=typeof e)return!1;if(!/^\d{4}[-/]\d{2}[-/]\d{2}/.test(e))return!1;const a=new Date(e);return!isNaN(a.getTime())}(n)?r?.formatDate?r.formatDate(n):Vy(n):String(n)}function $y(e){return e.replace(/([A-Z])/g,(e,a,t)=>`${t>0?"-":""}${a.toLowerCase()}`)}function Vy(e){try{return new Date(e).toLocaleString()}catch{return e}}(uy=cy||(cy={}))[uy.readOnlyText=1]="readOnlyText",uy[uy.text=2]="text",uy[uy.date=3]="date",uy[uy.time=4]="time",uy[uy.url=5]="url",uy[uy.number=6]="number",uy[uy.singleSelection=7]="singleSelection",uy[uy.multiSelection=8]="multiSelection",uy[uy.questions=9]="questions",(py=my||(my={}))[py.dropdown=1]="dropdown",py[py.buttons=2]="buttons",py[py.radio=3]="radio",py[py.checkbox=4]="checkbox",(fy=hy||(hy={}))[fy.custom=1]="custom",fy[fy.users=2]="users",fy[fy.usersLists=3]="usersLists";const qy={event:"Evento",entityName:"Item",description:e.t("audit_description"),justification:"Justificativa",status:"Status",type:"Tipo",references:e.t("audit_references"),security:e.t("audit_security"),electronicSigned:e.t("audit_esign"),accomplishedBy:"Realizado por",accomplishedIn:"Realizado em",changedFrom:"de",changedTo:"para",uninformed:e.t("audit_not_informed"),stateAdded:"(adicionado)",stateModified:"(modificado)",stateRemoved:"(removido)"};function Wy({documentId:e,onFetchDetails:r,onClose:n,labels:i,translateProperty:s,translatePropertyValue:d,formatDate:c}){const[u,p]=o(!1),[h,f]=o([]),[g,v]=o(null),b=l(async e=>{p(!0),v(null);try{const a=Fy(await r(e),{translateProperty:s,translatePropertyValue:d,formatDate:c,labels:i});f(a)}catch(a){v("Erro ao carregar detalhes da trilha de auditoria."),f([])}finally{p(!1)}},[r,s,d,c,i]);return m(()=>{e&&b(e)},[e,b]),e?t("div",{className:"flex flex-col h-full bg-background",children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30",children:[a("h3",{className:"text-sm font-semibold text-foreground",children:"Detalhes da Auditoria"}),a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:n,children:a(E,{className:"h-4 w-4"})})]}),a("div",{className:"flex-1 overflow-y-auto",children:u?t("div",{className:"flex items-center justify-center p-6",children:[a(Yo,{size:"md"}),a("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando detalhes..."})]}):g?a("div",{className:"p-6 text-sm text-destructive",children:g}):a("table",{className:"w-full text-xs",children:a("tbody",{children:h.map((e,r)=>t("tr",{className:r%2==0?"bg-background":"bg-muted/20",children:[a("td",{className:"px-4 py-2.5 font-semibold text-foreground whitespace-nowrap align-top w-[180px] border-b border-border/50",children:e.name}),a("td",{className:"px-4 py-2.5 text-muted-foreground break-words border-b border-border/50",children:a("span",{dangerouslySetInnerHTML:{__html:e.value.replace(/\n/g,"<br />")}})})]},r))})})})]}):null}function Hy({title:r,softwares:n,softwareId:i,permissions:s={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},callbacks:d,limit:c=2e3,currentUserId:p,labels:h,formatDate:f,anonymousLabel:g=e.t("anonymous")}){const{t:v}=Ga();r??v("audit_trail");const[b,x]=o(!0),[y,N]=o([]),[w,_]=o([]),[C,k]=o([]),[S,A]=o(null),[E,D]=o(!1),P=u(null),I=new Date;I.setHours(0,0,0,0);const[T,R]=o({software:n.find(e=>e.id===i)?.software||"",softwareId:i,event:"All",eventId:1,startDate:I,endDate:I,limit:c,softwares:n,userId:s.viewOnlyMyEvents&&!s.viewAllEvents?p:void 0});m(()=>{(async()=>{x(!0);try{const[e,a]=await Promise.all([d.onFetchEvents(T.softwareId),d.onFetchUsers?.()??Promise.resolve([])]);_(e),k(a),await M(T,e)}catch(e){}finally{x(!1)}})()},[]);const M=l(async(e,a)=>{try{const t=My((await d.onFetchTrails(e)).data,a||w,n,g);N(t)}catch(t){}},[d,w,n,g]),L=l(async e=>{x(!0),R(e);try{await M(e)}finally{x(!1)}},[M]),z=l(async e=>{try{const a=await d.onFetchEvents(e);_(a)}catch(a){}},[d]),F=l(e=>{A(e.documentId),D(!0)},[]),U=l(()=>{D(!1),A(null)},[]),j=l(async()=>{const e={...T,startDate:I,endDate:I,eventId:1,userId:s.viewAllEvents?void 0:p};R(e),x(!0);try{await M(e)}finally{x(!1)}},[T,M]),O=l(e=>{d.onExport?.(e,y)},[d,y]),B=l(e=>{try{return new Date(e).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return e}},[]);return t("div",{className:"flex flex-col h-full",children:[a("div",{className:"p-3",children:a(Ty,{queryParams:T,events:w,softwares:n,users:C,permissions:s,isLoading:b,onFilter:L,onReset:j,onExport:s.download?O:void 0,onSoftwareChange:z})}),t("div",{className:"flex flex-1 min-h-0 relative",children:[t("div",{className:Fi("flex-1 overflow-auto transition-all duration-300",E?"mr-[400px]":""),children:[b?t("div",{className:"flex items-center justify-center h-64",children:[a(Yo,{size:"md"}),a("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando trilha de auditoria..."})]}):0===y.length?t("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[a(Be,{className:"h-12 w-12 mb-3 opacity-30"}),a("p",{className:"text-sm",children:"Nenhum registro encontrado"}),a("p",{className:"text-xs mt-1",children:"Ajuste os filtros e tente novamente"})]}):t("table",{className:"w-full text-xs border-collapse",children:[a("thead",{className:"sticky top-0 z-10",children:t("tr",{className:"bg-muted/60 border-b border-border",children:[a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(Da,{className:"h-3 w-3"}),"Módulo"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(We,{className:"h-3 w-3"}),"Data"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(ge,{className:"h-3 w-3"}),"Usuário"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(Be,{className:"h-3 w-3"}),"Evento"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Item"}),a("th",{className:"px-3 py-2 w-10"})]})}),a("tbody",{children:y.map((e,r)=>t("tr",{onClick:()=>F(e),className:Fi("cursor-pointer border-b border-border/50 transition-colors","hover:bg-accent/50",S===e.documentId&&"bg-accent",r%2==0?"bg-background":"bg-muted/10"),children:[a("td",{className:"px-3 py-2 text-foreground",children:e.translatedSoftware}),a("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:e.date?B(e.date.toISOString()):"—"}),a("td",{className:"px-3 py-2 text-foreground",children:e.user}),a("td",{className:"px-3 py-2 text-foreground",children:e.translatedEvent}),a("td",{className:"px-3 py-2 text-foreground truncate max-w-[200px]",title:e.entityName,children:e.entityName}),a("td",{className:"px-3 py-2",children:a(Ce,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},e.documentId||r))})]}),!b&&y.length>0&&t("div",{className:"px-3 py-2 text-xs text-muted-foreground border-t border-border bg-muted/20",children:[y.length," registro",1!==y.length?"s":""]})]}),a("div",{ref:P,className:Fi("fixed right-0 top-0 h-full w-[400px] border-l border-border bg-background shadow-lg z-30","transition-transform duration-300 ease-in-out",E?"translate-x-0":"translate-x-full"),children:E&&a(Wy,{documentId:S,onFetchDetails:d.onFetchDetails,onClose:U,labels:h,translateProperty:d.translateProperty,translatePropertyValue:d.translatePropertyValue,formatDate:f||B})})]})]})}function Gy({open:r,onOpenChange:n,returnSteps:i,initialObservation:s="",title:l=e.t("approval_execute_action"),descriptions:d=[],setDefaultApproverOnInit:c=!0,onSubmit:u}){const[m,p]=o(!0),[h,f]=o(c&&i.length>0?i[0].id:null),[g,v]=o(s),b=e=>{p(e),e&&!c?f(null):!e&&!c&&i.length>0&&f(i[0].id)},x=g!==s||!m;return a(mo,{open:r,onOpenChange:n,children:t(bo,{className:"sm:max-w-[480px]",variant:"form",isDirty:x,children:[a(xo,{children:a(wo,{children:l})}),t("div",{className:"space-y-4",children:[d.length>0&&a("div",{className:"space-y-1 text-sm text-muted-foreground",children:d.map((e,t)=>a("p",{dangerouslySetInnerHTML:{__html:e}},t))}),t("div",{className:"flex gap-4",children:[t("label",{className:"flex items-center gap-2 cursor-pointer",children:[a("input",{type:"radio",name:"approved",checked:m,onChange:()=>b(!0),className:"accent-primary"}),a("span",{className:"text-sm",children:e.t("approval_approve")})]}),t("label",{className:"flex items-center gap-2 cursor-pointer",children:[a("input",{type:"radio",name:"approved",checked:!m,onChange:()=>b(!1),className:"accent-primary"}),a("span",{className:"text-sm",children:e.t("approval_reprove_radio")})]})]}),t("div",{className:"space-y-1.5",children:[a(Hi,{children:"Etapa"}),t(Mo,{value:h??void 0,onValueChange:f,disabled:m,children:[a(Fo,{children:a(zo,{placeholder:e.t("approval_select_step")})}),a(Oo,{children:i.map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]}),t("div",{className:"space-y-1.5",children:[a(Hi,{children:e.t("approval_opinion")}),a(Wo,{value:g,onChange:e=>v(e.target.value),maxLength:4e3,rows:4,autoFocus:!0}),t("p",{className:"text-xs text-muted-foreground text-right",children:[g.length,"/",4e3]})]})]}),t(No,{children:[a($i,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),a($i,{onClick:()=>{if(!g.trim())return void C.error("Formulário inválido. Preencha todos os campos obrigatórios.");const e=m?null:i.find(e=>e.id===h);u({approved:m,returnStepId:m?null:h,returnType:e?.type??null,observation:g})},disabled:!x,children:"Concluir"})]})]})})}function Ky({open:e,onOpenChange:r,approvers:n,isLoading:i=!1,ignoreUserIds:l=[],onSubmit:d}){const{t:c}=Ga(),[u,m]=o(null),p=s(()=>{const e=new Set(l);return n.filter(a=>!e.has(a.id))},[n,l]),h=s(()=>p.map(e=>({value:e.id,label:e.name})),[p]);return a(mo,{open:e,onOpenChange:r,children:t(bo,{className:"sm:max-w-[450px]",variant:"form",isDirty:!!u,children:[a(xo,{children:a(wo,{children:c("approval_select_approver")})}),a(Qo,{isLoading:i,type:"spinner",children:a("div",{className:"space-y-4",children:a(Rs,{options:h,value:u??void 0,onValueChange:e=>m("string"==typeof e?e:e?.[0]??null),placeholder:c("approval_select_approver_placeholder"),searchPlaceholder:c("approval_search_approver")})})}),t(No,{children:[a($i,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),a($i,{onClick:()=>{if(!u)return;const e=p.find(e=>e.id===u);e&&d(e)},disabled:!u||i,children:"Concluir"})]})]})})}function Yy(e){const{t:a}=Ga();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function Qy({text:e,maxLength:r=130}){const{t:n}=Ga(),[i,s]=o(!1);return e.length<=r?a("span",{children:e}):t("span",{children:[i?e:`${e.substring(0,r)}... `,a("button",{className:"text-primary hover:underline text-sm cursor-pointer",onClick:()=>s(!i),children:n(i?"approval_read_less":"approval_read_more")})]})}function Xy({approver:e}){if(1===e.type&&e.approverId)return t(bu,{className:"h-9 w-9 shrink-0",children:[a(xu,{src:e.photoUrl,alt:e.name}),a(yu,{className:"text-xs",children:e.name?.substring(0,2).toUpperCase()})]});const r=2===e.type?Ze:3===e.type?Pa:ge;return a("div",{className:"h-9 w-9 rounded-full bg-muted-foreground/30 flex items-center justify-center shrink-0",children:a(r,{className:"h-4 w-4 text-background"})})}function Jy({approver:e}){return e.date?t("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-green-500/10 text-foreground",children:[a(le,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:Yy(e.date)}),1!==e.type&&e.approvedUsername&&t("span",{className:"text-xs text-muted-foreground",children:["por ",e.approvedUsername]})]}):e.returnDate?t("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-red-500/10 text-foreground",children:[a(Ia,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:Yy(e.returnDate)})]}):t("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-muted text-muted-foreground",children:[a(O,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function Zy({approver:e}){const{t:r}=Ga(),n=1!==e.type||e.approverId?e.name:"A definir";return t("div",{children:[2===e.type&&a("p",{className:"text-xs text-muted-foreground",children:r("approval_user_group")}),3===e.type&&a("p",{className:"text-xs text-muted-foreground",children:"Local"}),a("p",{className:"text-sm font-medium break-words",children:n}),a(Jy,{approver:e})]})}function eN({config:e,isLoading:r=!1,onClose:n,onApprove:i,onDefineApprover:s,onRefreshSteps:d,availableApprovers:c=[],isLoadingApprovers:u=!1}){const{t:m}=Ga(),[p,h]=o(!1),[f,g]=o(!1),[v,b]=o(""),[x,y]=o(""),[N,w]=o(!1),[_,C]=o(""),k=r||p,S=l((e,a)=>{b(e),y(a??""),g(!0)},[]),A=l(async a=>{g(!1),h(!0);if(!await i(e.associationId,{stepApproverId:v,...a}))return S(v,a.observation),void h(!1);n(),h(!1)},[e.associationId,v,i,n,S]),D=l(e=>{C(e),w(!0)},[]),P=l(async a=>{w(!1),h(!0),await s(e.associationId,_,a),await(d?.(e.associationId)),h(!1)},[e.associationId,_,s,d]),I=e.approvalFlowSteps.find(e=>e.isCurrentStep)?.approvers.filter(e=>1===e.type&&e.approverId).map(e=>e.approverId)??[],T=(a,t)=>e.canApprove&&a.isCurrentStep&&t.approverId&&!t.date&&t.canApprove,R=(a,t)=>!e.flowReproved&&a.isCurrentStep&&1===t.type&&t.canApprove&&(!t.approverId||t.isToBeDefined);return t("div",{className:"w-[550px] max-w-[900px] min-w-[400px] h-full flex flex-col bg-background",children:[t("div",{className:"shrink-0 shadow-sm px-1 py-2 flex items-center gap-1 border-l-4",style:{borderLeftColor:e.color},children:[a($i,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0",children:a(E,{className:"h-5 w-5"})}),a("span",{className:"text-lg font-medium",children:e.title})]}),k?a(Qo,{isLoading:!0,type:"spinner",className:"flex-1",children:a("div",{})}):t("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[e.approvalFlowInfo.length>0&&a("div",{className:"space-y-1",children:e.approvalFlowInfo.map((e,t)=>a("div",{className:Fi("flex items-center gap-1.5 text-sm",e.color&&"rounded-lg px-2 py-1"),style:e.color?{color:e.color,backgroundColor:e.backgroundColor}:void 0,children:e.title?`${e.title}: ${e.value}`:e.value},t))}),a("hr",{className:"border-border"}),e.approvalFlowSteps.map(r=>t("div",{className:Fi("space-y-2",(!r.isCurrentStep||e.flowReproved)&&"opacity-50"),children:[t("p",{className:"font-semibold text-sm",children:[r.index,". Etapa: ",r.name]}),r.description&&a("p",{className:"text-sm text-muted-foreground break-words",children:a(Qy,{text:r.description})}),r.returnDate&&t("div",{className:"border-y border-border py-3 mt-3 space-y-1",children:[t("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-xs rounded px-1.5 py-0.5 bg-red-500/10 text-red-600",children:"Retorno de etapa"}),t("span",{className:"text-xs text-muted-foreground",children:[r.returnUserName," em ",Yy(r.returnDate)]})]}),r.returnObservation&&a("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:a(Qy,{text:r.returnObservation})})]}),r.approvers.map(e=>t("div",{className:"p-2 space-y-1",children:[t("div",{className:"flex items-center justify-between gap-2",children:[t("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[a(Xy,{approver:e}),a(Zy,{approver:e})]}),T(r,e)&&a($i,{size:"sm",onClick:()=>S(e.id),children:"Aprovar"}),R(r,e)&&a($i,{size:"sm",variant:"outline",onClick:()=>D(e.id),children:"Selecionar"})]}),e.observation&&a("p",{className:"text-sm text-muted-foreground break-words ml-11",children:a(Qy,{text:e.observation})}),e.returnObservation&&a("p",{className:"text-sm text-muted-foreground break-words ml-11",children:a(Qy,{text:e.returnObservation})})]},e.id))]},r.id))]}),a(Gy,{open:f,onOpenChange:g,returnSteps:e.returnSteps,initialObservation:x,title:e.approveDialogTitle,descriptions:e.approveDialogDescriptions,setDefaultApproverOnInit:e.approveDialogSetDefaultApproverOnInit,onSubmit:A}),a(Ky,{open:N,onOpenChange:w,approvers:c,isLoading:u,ignoreUserIds:I,onSubmit:P})]})}var aN,tN;function rN({users:e,value:r,onChange:n,disabled:i=!1,placeholder:d="Buscar membro da equipe...",confirmRemoval:c=!0,confirmTitle:u,confirmMessage:m="Tem certeza que deseja remover este membro da equipe?",emptyMessage:p,className:h}){const{t:f}=Ga(),g=u??f("leadership_remove_team"),v=p??f("leadership_no_members"),[b,x]=o(""),[y,N]=o(!1),[w,_]=o(null),C=s(()=>new Set(r),[r]),k=s(()=>e.filter(e=>C.has(e.id)),[e,C]),S=s(()=>e.filter(e=>!C.has(e.id)).map(e=>({value:e.id,label:e.name})),[e,C]),A=l(e=>{e&&!C.has(e)&&(n([...r,e]),x(""))},[r,n,C]),D=l(e=>{c?(_(e),N(!0)):n(r.filter(a=>a!==e))},[r,n,c]),P=l(()=>{w&&n(r.filter(e=>e!==w)),N(!1),_(null)},[w,r,n]);return t("div",{className:Fi("space-y-3",h),children:[a("div",{className:"flex items-start gap-3",children:a("div",{className:"flex-1",children:a(Rs,{options:S,value:b,onValueChange:e=>{const a="string"==typeof e?e:e?.[0]??"";x(a),a&&A(a)},placeholder:d,searchPlaceholder:"Buscar...",disabled:i})})}),t("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-sm text-muted-foreground",children:"Selecionados"}),a("span",{className:"text-xs bg-muted text-muted-foreground rounded-full px-2 py-0.5 font-medium",children:k.length})]}),k.length>0?a("div",{className:"space-y-2",children:k.map(e=>t("div",{className:"flex items-center border border-border rounded-lg p-2 gap-3",children:[t(bu,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(xu,{src:e.avatar,alt:e.name}),a(yu,{className:"text-xs",children:e.name?.substring(0,2).toUpperCase()})]}),a("div",{className:"flex-1 min-w-0",children:a("p",{className:"text-sm font-medium truncate",title:e.name,dangerouslySetInnerHTML:{__html:e.title||e.name}})}),t("div",{className:"flex items-center gap-2 shrink-0 text-xs text-muted-foreground",children:[e.roleName&&t("span",{className:"flex items-center gap-1",children:[a(Ta,{className:"h-3.5 w-3.5"}),a("span",{className:"truncate max-w-[120px]",children:e.roleName})]}),e.placeName&&t("span",{className:"flex items-center gap-1",children:[a(Pa,{className:"h-3.5 w-3.5"}),a("span",{className:"truncate max-w-[120px]",children:e.placeName})]}),a("button",{type:"button",className:Fi("text-muted-foreground hover:text-destructive transition-colors",i&&"opacity-50 pointer-events-none"),onClick:()=>!i&&D(e.id),title:f("remove"),children:a(E,{className:"h-4 w-4"})})]})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[a(ge,{className:"h-12 w-12 mb-2 opacity-30"}),a("p",{className:"text-sm",children:v})]}),a(mo,{open:y,onOpenChange:N,children:t(bo,{className:"sm:max-w-[400px]",children:[a(xo,{children:a(wo,{children:g})}),a("p",{className:"text-sm text-muted-foreground",children:m}),t(No,{children:[a($i,{variant:"ghost",onClick:()=>N(!1),children:"Cancelar"}),a($i,{variant:"destructive",onClick:P,children:"Remover"})]})]})})]})}(tN=aN||(aN={}))[tN.ApprovalFlow=1]="ApprovalFlow",tN[tN.Association=2]="Association";export{pr as AUTH_CONFIG,nu as AccessDeniedDialog,hu as Accordion,vu as AccordionContent,fu as AccordionItem,gu as AccordionTrigger,Vi as ActionButton,Vi as ActionMenu,ld as ActionMenuItems,ry as ActionPlanAttachmentsTab,Jx as ActionPlanCommentsTab,Xx as ActionPlanCostTab,Bx as ActionPlanGeneralTab,ey as ActionPlanHistoryTab,iy as ActionPlanPage,Qx as ActionPlanPredecessorsTab,Gx as ActionPlanProgressDialog,Kx as ActionPlanProgressTab,Ox as ActionPlanStatusBadge,Xh as AggregationType,rc as Alert,ic as AlertDescription,eo as AlertDialog,co as AlertDialogAction,uo as AlertDialogCancel,no as AlertDialogContent,lo as AlertDialogDescription,oo as AlertDialogFooter,io as AlertDialogHeader,ro as AlertDialogOverlay,to as AlertDialogPortal,so as AlertDialogTitle,ao as AlertDialogTrigger,nc as AlertTitle,ec as AliasRedirect,Zd as AliasRouteGuard,Zh as AnalysisFunctionality,Yv as AppHeader,ob as AppLayout,ib as AppSidebar,aN as ApprovalFlowReturnStep,eN as ApprovalSidenav,Gy as ApproveDialog,Wy as AuditTrailDetails,Ty as AuditTrailFilter,Hy as AuditTrailPage,ol as AuthErrorInterceptor,Cl as AuthProvider,yl as AuthService,Rs as AutoComplete,bu as Avatar,yu as AvatarFallback,xu as AvatarImage,Go as Badge,Fd as BaseForm,mm as Blockquote,db as BodyContent,Nu as Breadcrumb,Au as BreadcrumbEllipsis,_u as BreadcrumbItem,Cu as BreadcrumbLink,wu as BreadcrumbList,ku as BreadcrumbPage,Su as BreadcrumbSeparator,Pg as BurndownPanel,$i as Button,Du as ButtonGroup,zx as CLOSED_STATUSES,hr as CRUD_CONFIG,Xf as CURRENCY_FIELDS,Pu as Calendar,oc as CallbackPage,Gi as Card,Xi as CardContent,Qi as CardDescription,Ji as CardFooter,Ki as CardHeader,jl as CardSkeleton,Yi as CardTitle,kg as CartesianPanel,Hp as ChartContainer,Qp as ChartLegend,Xp as ChartLegendContent,Gp as ChartStyle,Kp as ChartTooltip,Yp as ChartTooltipContent,qo as Checkbox,Sc as Collapsible,Ec as CollapsibleContent,Ac as CollapsibleTrigger,Ed as ColorPicker,_d as ColumnSettingsPopover,js as ComboTree,Rs as Combobox,Ns as Command,ws as CommandDialog,ks as CommandEmpty,Ss as CommandGroup,_s as CommandInput,Es as CommandItem,Cs as CommandList,As as CommandSeparator,Ds as CommandShortcut,lb as ContentContainer,Gl as ContextMenu,rd as ContextMenuCheckboxItem,ad as ContextMenuContent,Yl as ContextMenuGroup,td as ContextMenuItem,id as ContextMenuLabel,Ql as ContextMenuPortal,Jl as ContextMenuRadioGroup,nd as ContextMenuRadioItem,od as ContextMenuSeparator,sd as ContextMenuShortcut,Xl as ContextMenuSub,ed as ContextMenuSubContent,Zl as ContextMenuSubTrigger,Kl as ContextMenuTrigger,uu as CoreProviders,bd as CrudActionBar,Dv as CrudActionMenu,Av as CrudGrid,Wd as CrudPageInternal,jd as CrudPagination,Pv as CrudPrimitiveFilterBar,Ud as CrudPrimitivePagination,Ev as CrudPrimitiveTable,kd as CrudTable,Py as CustomFormFields,hx as D4SignWidget,Qf as DASHBOARD_STORAGE_KEYS,mi as DATETIME_FORMATS,Rx as DEFAULT_ACTION_TYPES,fi as DEFAULT_DATETIME_FORMAT,hi as DEFAULT_LOCALE,gi as DEFAULT_TIMEZONE,Qg as DashboardForm,Nf as DashboardFormTab,ef as DashboardFunctionality,Xg as DashboardGeneralView,Fg as DashboardGrid,kf as DashboardLanguage,qg as DashboardList,tf as DashboardListType,nf as DashboardPageTime,sf as DashboardPanelDimension,uf as DashboardPanelOrderBy,df as DashboardPanelOrderByType,pf as DashboardPanelPeriod,jg as DashboardPanelRenderer,ff as DashboardPanelType,_f as DashboardShareType,vf as DashboardUpdateTime,Og as DashboardView,xf as DashboardViewType,Pv as DataFilterBar,Iu as DataList,Ud as DataPagination,Ev as DataTable,Tu as DatePicker,mo as Dialog,yo as DialogBody,fo as DialogClose,bo as DialogContent,_o as DialogDescription,No as DialogFooter,xo as DialogHeader,go as DialogOverlay,ho as DialogPortal,wo as DialogTitle,po as DialogTrigger,fh as DialogWizard,vs as DisabledMenuItem,fx as DocumentSigner,Ru as Drawer,zu as DrawerClose,Uu as DrawerContent,$u as DrawerDescription,Ou as DrawerFooter,ju as DrawerHeader,Fu as DrawerOverlay,Lu as DrawerPortal,Bu as DrawerTitle,Mu as DrawerTrigger,Jo as DropdownMenu,ls as DropdownMenuCheckboxItem,os as DropdownMenuContent,es as DropdownMenuGroup,ss as DropdownMenuItem,cs as DropdownMenuLabel,as as DropdownMenuPortal,rs as DropdownMenuRadioGroup,ds as DropdownMenuRadioItem,us as DropdownMenuSeparator,ms as DropdownMenuShortcut,ts as DropdownMenuSub,is as DropdownMenuSubContent,ns as DropdownMenuSubTrigger,Zo as DropdownMenuTrigger,kx as EAttachmentItemStatus,cy as ECustomFormFieldType,my as EFieldViewMode,hy as ESelectionFieldDataSource,Nx as ETaskPlanAssociationType,xx as ETaskPlanPriority,vx as ETaskPlanStatus,_x as ETaskPlanTypeProgress,ph as ElectronicSignatureDialog,Wl as EllipsisText,fb as EmailService,ql as EmptyState,Rs as EntitySelect,Dc as ErrorBoundary,uh as ExportDialog,sh as ExportFormat,oy as FORBIDDEN_FILE_TYPES,wh as FilePrintType,yh as FileViewerType,qd as FilterBar,Co as Form,Io as FormControl,_y as FormDateField,To as FormDescription,So as FormField,Do as FormItem,Po as FormLabel,Ro as FormMessage,Ey as FormMultiSelectionField,Sy as FormNumericField,Dy as FormQuestionsField,Ay as FormSingleSelectionField,Ol as FormSkeleton,wy as FormTextField,Cy as FormTimeField,ky as FormUrlField,Wu as Grid,tm as H1,rm as H2,nm as H3,im as H4,Bl as HeaderSkeleton,Hu as HoverCard,Ku as HoverCardContent,Gu as HoverCardTrigger,Rd as IconPicker,Rh as IframeDialog,Jb as ImageEditor,Zb as ImageRenderer,um as InlineCode,qi as Input,Yu as InputGroup,Xu as InputGroupAddon,Zu as InputGroupButton,em as InputGroupInput,am as InputGroupTextarea,Jf as LINK_PROPERTIES,wr as LOGO_CONFIG,Hi as Label,lm as Large,sm as Lead,Ub as LeadershipDialog,Fb as LeadershipForm,Bb as LeadershipPage,pm as List,wg as ListPanel,Qo as LoadingState,Nc as LocaleProvider,sc as LoginPage,_r as MESSAGES,Kc as MODULES_DATA,Yf as MONTHS_MAP,vb as ManageAccessModal,Tg as MatrixRiskPanel,Af as MatrixViewType,Tp as Menubar,Up as MenubarCheckboxItem,zp as MenubarContent,Ep as MenubarGroup,Fp as MenubarItem,Op as MenubarLabel,Ap as MenubarMenu,Dp as MenubarPortal,Ip as MenubarRadioGroup,jp as MenubarRadioItem,Bp as MenubarSeparator,$p as MenubarShortcut,Pp as MenubarSub,Lp as MenubarSubContent,Mp as MenubarSubTrigger,Rp as MenubarTrigger,Sv as MindMap,tb as ModalStateProvider,ou as ModuleAccessGuard,Xc as ModuleGrid,su as ModuleOfferContent,Cc as ModuleProvider,Jc as ModulesContent,ru as ModulesDialog,Gc as ModulesFooterCards,Rs as MultiSelect,Oh as MultiselectPermissions,cm as Muted,hm as NavigationMenu,xm as NavigationMenuContent,wm as NavigationMenuIndicator,gm as NavigationMenuItem,ym as NavigationMenuLink,fm as NavigationMenuList,bm as NavigationMenuTrigger,Nm as NavigationMenuViewport,Vv as NavigationProvider,yg as NumericPanel,ih as OnboardingDialog,Th as OnlineEditorDialog,om as P,Lx as PRIORITIES,lr as PROD_PROJECT_ID,Fx as PROGRESS_ALLOWED_STATUSES,_m as PageBreadcrumb,dc as PageMetadataProvider,km as Pagination,Sm as PaginationContent,Im as PaginationEllipsis,Am as PaginationItem,Em as PaginationLink,Pm as PaginationNext,Dm as PaginationPrevious,Gf as PaletteType,fg as PanelError,hg as PanelHeader,Df as PanelItemsPerPanel,gg as PanelLoader,vg as PanelNoData,If as PanelSortType,Rf as PanelState,bg as PanelUnavailable,Dg as ParetoPanel,Ig as PerformancePanel,Eg as PiePanel,bb as PlaceCard,xb as PlacesList,Ff as PlanType,bs as Popover,ys as PopoverContent,xs as PopoverTrigger,Tm as Progress,Xd as ProtectedRoute,Nr as QUALIEX_CONFIG,yr as QUERY_KEYS,hl as QualiexEnrichmentService,sl as QualiexErrorInterceptor,zd as QualiexUserField,jf as QueriesContextType,Bf as QueriesShareType,Vf as QuickFilterDashboard,Rm as RadioGroup,Mm as RadioGroupItem,Ny as ReadOnlyTextField,Hh as ReportRequestList,Bh as ReportRequestStatus,Fm as ResizableHandle,zm as ResizablePanel,Lm as ResizablePanelGroup,ah as RichTextEditor,Wf as RiskCriticality,fr as SEARCH_CONFIG,Ax as STATUS_COLORS,Ix as STATUS_LABELS,Dx as STATUS_MAP,Ex as STATUS_TEXT_COLORS,ui as SUPPORTED_LOCALES,Dd as ScrollArea,Pd as ScrollBar,Mo as Select,Ky as SelectApproverDialog,Oo as SelectContent,Lo as SelectGroup,$o as SelectItem,Bo as SelectLabel,jo as SelectScrollDownButton,Uo as SelectScrollUpButton,Rs as SelectSearch,Vo as SelectSeparator,Fo as SelectTrigger,zo as SelectValue,Zi as Separator,Um as Sheet,Hm as SheetBody,Om as SheetClose,qm as SheetContent,Ym as SheetDescription,Gm as SheetFooter,Wm as SheetHeader,$m as SheetOverlay,Bm as SheetPortal,Km as SheetTitle,jm as SheetTrigger,ep as Sidebar,Xv as SidebarActionTrigger,lp as SidebarContent,op as SidebarFooter,dp as SidebarGroup,up as SidebarGroupAction,mp as SidebarGroupContent,cp as SidebarGroupLabel,sb as SidebarHeader,np as SidebarInput,rp as SidebarInset,Kv as SidebarLogo,pp as SidebarMenu,vp as SidebarMenuAction,bp as SidebarMenuBadge,gp as SidebarMenuButton,hp as SidebarMenuItem,xp as SidebarMenuSkeleton,yp as SidebarMenuSub,wp as SidebarMenuSubButton,Np as SidebarMenuSubItem,Zm as SidebarProvider,tp as SidebarRail,sp as SidebarSeparator,$l as SidebarSkeleton,ap as SidebarTrigger,gx as SignConfigForm,px as SignWidget,dy as SingleFileUpload,Ps as Skeleton,_p as Slider,dm as Small,Xo as SonnerToaster,Yo as Spinner,oh as SplitButton,Vd as Stack,Yh as StatusBadge,hh as StepSelector,hh as Stepper,Gh as StimulsoftViewer,Md as Switch,pi as TIMEZONES,Sp as TabPageContent,kp as TabPageHeader,Cp as TabPageLayout,Pl as Table,Tl as TableBody,Fl as TableCaption,zl as TableCell,Rl as TableFooter,Ll as TableHead,Il as TableHeader,Hl as TableResizeHandle,Ml as TableRow,dd as TableRowActions,Ul as TableSkeleton,Pc as Tabs,Rc as TabsContent,Ic as TabsList,Tc as TabsTrigger,rN as TeamSelector,Mh as TermsOfUseDialog,Lh as TermsOfUseViewer,Ng as TextPanel,Wo as Textarea,mh as Timepicker,Xo as Toaster,hd as Toggle,gd as ToggleGroup,vd as ToggleGroupItem,Ys as TokenManager,Os as TokenService,hs as Tooltip,gs as TooltipContent,ps as TooltipProvider,fs as TooltipTrigger,js as TreeSelect,Lv as TreeTable,Wl as TruncatedCell,xh as UpdatesNotification,Fh as UsersGroupsSelector,Qb as VideoEditor,Xb as VideoRenderer,Ph as ViewerDialog,Lf as VisualizationType,vc as addAppTranslations,nv as addChild,iv as addSibling,Sr as assets,Ho as badgeVariants,Fy as buildDetailRows,wb as buildHierarchy,zi as buildModuleUrl,cg as buildPlacesTree,Dh as buildWopiUrl,Eu as buttonGroupVariants,Bi as buttonVariants,ex as calculateAspectRatio,$y as camelToDash,Fi as cn,Hd as createCrudPage,Fv as createCrudRoutingConfig,Zg as createMindMapNode,zv as createRoutingHandlers,vl as createService,Gd as createSimpleSaveHandler,Al as createSimpleService,Qh as createStatusConfig,Cr as createTranslatedMessages,dg as currencyFormatter,ji as debounce,cl as deriveEmailField,dl as deriveNameField,ul as deriveUsernameField,_i as detectBrowserLocale,Si as detectBrowserPreferences,Ci as detectBrowserTimezone,Kb as detectVideoProvider,gb as emailService,Qs as errorService,_v as exportMindMap,rx as extractImageFileName,lg as extractNumberFromCurrency,Wb as extractVimeoId,Vb as extractYouTubeId,Nb as filterAndPromoteOrphans,bi as findDatetimeFormat,vi as findLocale,ev as findNode,xi as findTimezone,_b as flattenTree,sy as formatBytes,Pi as formatCurrency,Di as formatDate,Ei as formatDatetime,nx as formatFileSize,Wx as formatTime,qx as formatTimeProgress,Kd as generateCrudConfig,Jg as generateNodeId,Ti as generatePastelBg,Tx as getActionTypes,Mi as getContrastRatio,Mg as getDefaultPanelSize,ur as getEnvironmentConfig,gy as getFieldValue,ly as getFileExtension,by as getFormFieldValues,rg as getLinkFromRow,Ri as getLuminance,Lg as getMinPanelSize,Sh as getOnlineViewerType,Mx as getPriorities,Hx as getProgressColor,xr as getQualiexApiUrl,Px as getStatusLabels,rl as getSupabaseClient,kh as getViewerType,Eh as getWopiViewer,Li as handleExternalLink,kv as importMindMap,ki as inferDatetimeFormat,Qu as inputGroupAddonVariants,Ju as inputGroupButtonVariants,sg as isCurrency,br as isDevEnvironment,mr as isDevSupabaseProject,tx as isImageUrl,gr as isLovablePreview,ag as isNullOrEmptyField,Ni as isValidDatetimeFormat,yi as isValidLocale,wi as isValidTimezone,ux as loadClicksignScript,du as loadForlogicFonts,Ar as logoSrc,pb as mergeTranslationFiles,sv as moveNode,vm as navigationMenuTriggerStyle,Yb as normalizeVideoUrl,Hb as normalizeVimeoUrl,qb as normalizeYouTubeUrl,Gb as parseIframeSrc,yb as placeService,My as processTrails,tg as processUrl,ll as qualiexApi,ov as removeNode,ax as resizeKeepingAspect,ml as resolveFieldMappings,Hv as resolvePageTitle,dv as setCollapsedAll,xy as setFormFieldValues,mc as setupQualiexCore,vy as shouldShowField,vr as shouldUseDevTokens,dx as signService,Oi as slugify,Er as smallLogoSrc,Zf as sortByMonthYear,ng as toQueryString,lv as toggleCollapsed,pd as toggleVariants,Hc as trackFooterClick,Wc as trackInterestClick,qc as trackModuleClick,Ui as trimTextFields,Ux as useActionPlan,Vx as useActionPlanProgress,cb as useActiveModules,Jd as useAliasFromUrl,kl as useAuth,Sd as useBaseForm,cu as useClarity,Nd as useColumnManager,md as useColumnResize,Ab as useCreateMultipleLeadersMutation,Sb as useCreateSingleLeaderMutation,Sl as useCrud,Gv as useDebounce,tu as useDerivedContractedModules,Ao as useFormField,nb as useHasOpenModal,hb as useI18nFormatters,Dl as useIsMobile,Cb as useLeadershipApi,wc as useLocale,El as useMediaQuery,$b as useMediaUpload,rb as useModalState,au as useModuleAccess,kc as useModuleConfig,qv as useNavigation,uc as usePageMetadata,cc as usePageMetadataContext,Wv as usePageTitle,Qv as usePermissionQuery,Ld as useQualiexUsers,Db as useRemoveLeaderMutation,Cm as useRouteBreadcrumbs,ub as useRowResize,Jm as useSidebar,eb as useSidebarResize,ix as useSignConfig,Pb as useSyncSubordinatesMutation,Eb as useUpdateLeaderMutation,bh as useUpdatesNotification,mb as useWizard,yy as validateFields};
|
|
1
|
+
import e from"i18next";export{default as i18n}from"i18next";import{jsx as a,jsxs as t,Fragment as r}from"react/jsx-runtime";import*as n from"react";import i,{useState as o,useMemo as s,useCallback as l,createContext as d,useContext as c,useRef as u,useEffect as m,memo as p,Component as h,forwardRef as f}from"react";import{Slot as g}from"@radix-ui/react-slot";import{cva as v}from"class-variance-authority";import{clsx as b}from"clsx";import{twMerge as x}from"tailwind-merge";import{getDefaultOptions as y,parseISO as N,isValid as w,format as _}from"date-fns";import{toast as C,Toaster as k}from"sonner";export{toast as sonnerToast,toast}from"sonner";import*as S from"lucide-react";import{EllipsisVertical as A,X as E,ChevronDown as D,ChevronUp as P,Check as I,Loader2 as T,Loader2Icon as R,OctagonXIcon as M,TriangleAlertIcon as L,InfoIcon as z,CircleCheckIcon as F,ChevronRight as U,Circle as j,AlertCircle as O,Search as B,FileX as $,Edit as V,PowerOff as q,Power as W,Trash2 as H,Pencil as G,ToggleRight as K,ToggleLeft as Y,Plus as Q,LayoutGrid as X,List as J,Table2 as Z,Columns3 as ee,GripVertical as ae,Group as te,ArrowUp as re,ArrowDown as ne,ChevronsLeft as ie,ChevronLeft as oe,ChevronsRight as se,CheckCircle as le,AlertTriangle as de,Info as ce,RefreshCw as ue,Copy as me,ExternalLink as pe,NotebookText as he,Building2 as fe,User as ge,LogOut as ve,Sparkles as be,MoreHorizontal as xe,Calendar as ye,PanelLeft as Ne,Edit3 as we,Code as _e,Eye as Ce,Heading1 as ke,Heading2 as Se,Heading3 as Ae,Bold as Ee,Italic as De,Underline as Pe,Strikethrough as Ie,ListOrdered as Te,Highlighter as Re,Link as Me,RemoveFormatting as Le,Undo as ze,Redo as Fe,ImageIcon as Ue,ArrowLeft as je,ArrowRight as Oe,FileText as Be,FileSpreadsheet as $e,Image as Ve,FileImage as qe,Clock as We,Lock as He,ShieldCheck as Ge,Mail as Ke,Coffee as Ye,CheckCheck as Qe,Star as Xe,Download as Je,Users as Ze,TriangleAlert as ea,CheckCircle2 as aa,Hourglass as ta,MoreVertical as ra,Minus as na,CornerDownRight as ia,ChevronsUpDown as oa,ChevronsDownUp as sa,ZoomOut as la,ZoomIn as da,Maximize2 as ca,Undo2 as ua,Redo2 as ma,ArrowUpToLine as pa,Camera as ha,UserPen as fa,Menu as ga,Crown as va,UserPlus as ba,Settings as xa,Upload as ya,Pause as Na,Play as wa,MessageSquare as _a,Smartphone as Ca,Paperclip as ka,CloudUpload as Sa,RotateCcw as Aa,Filter as Ea,Layers as Da,MapPin as Pa,XCircle as Ia,Shield as Ta}from"lucide-react";import*as Ra from"@radix-ui/react-label";import*as Ma from"@radix-ui/react-dialog";import*as La from"@radix-ui/react-separator";import*as za from"@radix-ui/react-alert-dialog";import{useFormContext as Fa,FormProvider as Ua,Controller as ja,appendErrors as Oa,useForm as Ba}from"react-hook-form";import*as $a from"@radix-ui/react-select";import*as Va from"@radix-ui/react-checkbox";import*as qa from"@radix-ui/react-dropdown-menu";import*as Wa from"@radix-ui/react-tooltip";import*as Ha from"@radix-ui/react-popover";import{useTranslation as Ga,initReactI18next as Ka,I18nextProvider as Ya}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import{createClient as Qa}from"@supabase/supabase-js";import{useQueryClient as Xa,useQuery as Ja,useMutation as Za,QueryClient as et,QueryClientProvider as at}from"@tanstack/react-query";import{useSearchParams as tt,useParams as rt,useNavigate as nt,useLocation as it,Navigate as ot,Link as st}from"react-router-dom";import*as lt from"@radix-ui/react-context-menu";import*as dt from"@radix-ui/react-toggle-group";import*as ct from"@radix-ui/react-toggle";import*as ut from"@radix-ui/react-scroll-area";import*as mt from"@radix-ui/react-switch";import*as pt from"@radix-ui/react-collapsible";import*as ht from"@radix-ui/react-tabs";import*as ft from"@radix-ui/react-accordion";import*as gt from"@radix-ui/react-avatar";import{DayPicker as vt}from"react-day-picker";import{Drawer as bt}from"vaul";import*as xt from"@radix-ui/react-hover-card";import*as yt from"@radix-ui/react-navigation-menu";import*as Nt from"@radix-ui/react-progress";import*as wt from"@radix-ui/react-radio-group";import*as _t from"react-resizable-panels";import*as Ct from"@radix-ui/react-slider";import*as kt from"@radix-ui/react-menubar";import*as St from"recharts";import{ResponsiveContainer as At,XAxis as Et,YAxis as Dt,CartesianGrid as Pt,Tooltip as It,Legend as Tt,BarChart as Rt,Bar as Mt,AreaChart as Lt,Area as zt,LineChart as Ft,Line as Ut,PieChart as jt,Pie as Ot,Cell as Bt,ComposedChart as $t}from"recharts";import{useEditor as Vt,EditorContent as qt}from"@tiptap/react";import Wt from"@tiptap/starter-kit";import Ht from"@tiptap/extension-underline";import Gt from"@tiptap/extension-link";import{TextStyle as Kt}from"@tiptap/extension-text-style";import{Color as Yt}from"@tiptap/extension-color";import Qt from"@tiptap/extension-highlight";import{useSensors as Xt,useSensor as Jt,PointerSensor as Zt,DndContext as er,closestCenter as ar}from"@dnd-kit/core";import{SortableContext as tr,rectSortingStrategy as rr,useSortable as nr}from"@dnd-kit/sortable";import{z as ir}from"zod";import{validateFieldsNatively as or,toNestErrors as sr}from"@hookform/resolvers";const lr="ccjfvpnndclajkleyqkc",dr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},cr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login-dev.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api-dev.qualiex.com"};function ur(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e===lr?dr:cr}function mr(){let e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)try{const a=import.meta.env.VITE_SUPABASE_URL;a&&(e=new URL(a).hostname.split(".")[0])}catch{}return e!==lr}const pr={get oauth(){const e=ur();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},hr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},fr={debounceDelay:500},gr=()=>{const e=window.location.origin,a=(()=>{try{return window.self!==window.top}catch{return!0}})();return e.includes("localhost")||e.includes("127.0.0.1")||e.includes("lovable.dev")||e.includes("lovable.app")&&a||import.meta.env.DEV},vr=()=>gr(),br=gr,xr=()=>ur().qualiexApiUrl,yr={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Nr={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},wr={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},_r={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}`}},Cr=a=>({success:{created:a=>e.t("msg_created_success",`${a} criado com sucesso`).replace("{{entity}}",a),updated:a=>e.t("msg_updated_success",`${a} atualizado com sucesso`).replace("{{entity}}",a),deleted:a=>e.t("msg_deleted_success",`${a} removido com sucesso`).replace("{{entity}}",a)},error:{create:a=>e.t("msg_create_error",`Erro ao criar ${a}`).replace("{{entity}}",a),update:a=>e.t("msg_update_error",`Erro ao atualizar ${a}`).replace("{{entity}}",a),delete:a=>e.t("msg_delete_error",`Erro ao remover ${a}`).replace("{{entity}}",a),load:a=>e.t("msg_load_error",`Erro ao carregar ${a}`).replace("{{entity}}",a)}}),kr=`https://${ur().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,Sr={logo:wr.isQualiex?`${kr}/logo-qualiex-white.svg`:`${kr}/saber-gestao-white.png`,smallLogo:wr.isQualiex?`${kr}/logo-forlogic-white.svg`:`${kr}/small.svg`,favicon:`${kr}/favicon.png`},Ar=Sr.logo,Er=Sr.smallLogo;if("undefined"!=typeof document){document.querySelectorAll("link[rel='icon'], link[rel='shortcut icon']").forEach(e=>e.remove());const e=document.createElement("link");e.rel="icon",e.type="image/png",e.href=Sr.favicon,document.head.appendChild(e)}const Dr={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}};function Pr(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const Ir={date:Pr({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Pr({formats:{full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},defaultWidth:"full"}),dateTime:Pr({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Tr={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Rr(e){return(a,t)=>{let r;if("formatting"===(t?.context?String(t.context):"standalone")&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,n=t?.width?String(t.width):a;r=e.formattingValues[n]||e.formattingValues[a]}else{const a=e.defaultWidth,n=t?.width?String(t.width):e.defaultWidth;r=e.values[n]||e.values[a]}return r[e.argumentCallback?e.argumentCallback(a):a]}}function Mr(e){return(a,t={})=>{const r=t.width,n=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],i=a.match(n);if(!i)return null;const o=i[0],s=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(s,e=>e.test(o)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(s,e=>e.test(o));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(o.length)}}}function Lr(e){return(a,t={})=>{const r=a.match(e.matchPattern);if(!r)return null;const n=r[0],i=a.match(e.parsePattern);if(!i)return null;let o=e.valueCallback?e.valueCallback(i[0]):i[0];o=t.valueCallback?t.valueCallback(o):o;return{value:o,rest:a.slice(n.length)}}}const zr={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=Dr[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r},formatLong:Ir,formatRelative:(e,a,t,r)=>Tr[e],localize:{ordinalNumber:(e,a)=>{const t=Number(e),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},era:Rr({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Rr({values:{narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},defaultWidth:"wide",argumentCallback:e=>e-1}),month:Rr({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},defaultWidth:"wide"}),day:Rr({values:{narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},defaultWidth:"wide"}),dayPeriod:Rr({values:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},defaultFormattingWidth:"wide"})},match:{ordinalNumber:Lr({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mr({matchPatterns:{narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^b/i,/^(a|c)/i]},defaultParseWidth:"any"}),quarter:Mr({matchPatterns:{narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:e=>e+1}),month:Mr({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:Mr({matchPatterns:{narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Mr({matchPatterns:{narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},defaultParseWidth:"any"})},options:{weekStartsOn:0,firstWeekContainsDate:1}};let Fr={};function Ur(){return Fr}const jr=6048e5;function Or(e){const a=Object.prototype.toString.call(e);return e instanceof Date||"object"==typeof e&&"[object Date]"===a?new e.constructor(+e):"number"==typeof e||"[object Number]"===a||"string"==typeof e||"[object String]"===a?new Date(e):new Date(NaN)}function Br(e){const a=Or(e);return a.setHours(0,0,0,0),a}function $r(e){const a=Or(e),t=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds(),a.getMilliseconds()));return t.setUTCFullYear(a.getFullYear()),+e-+t}function Vr(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function qr(e){const a=Or(e),t=function(e,a){const t=Br(e),r=Br(a),n=+t-$r(t),i=+r-$r(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Or(e),t=Vr(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Wr(e,a){const t=Ur(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Or(e),i=n.getDay(),o=(i<r?7:0)+i-r;return n.setDate(n.getDate()-o),n.setHours(0,0,0,0),n}function Hr(e){return Wr(e,{weekStartsOn:1})}function Gr(e){const a=Or(e),t=a.getFullYear(),r=Vr(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Hr(r),i=Vr(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const o=Hr(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=o.getTime()?t:t-1}function Kr(e){const a=Or(e),t=+Hr(a)-+function(e){const a=Gr(e),t=Vr(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Hr(t)}(a);return Math.round(t/jr)+1}function Yr(e,a){const t=Or(e),r=t.getFullYear(),n=Ur(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,o=Vr(e,0);o.setFullYear(r+1,0,i),o.setHours(0,0,0,0);const s=Wr(o,a),l=Vr(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const d=Wr(l,a);return t.getTime()>=s.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function Qr(e,a){const t=Or(e),r=+Wr(t,a)-+function(e,a){const t=Ur(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=Yr(e,a),i=Vr(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),Wr(i,a)}(t,a);return Math.round(r/jr)+1}function Xr(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Jr={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return Xr("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):Xr(t+1,2)},d:(e,a)=>Xr(e.getDate(),a.length),a(e,a){const t=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return"am"===t?"a.m.":"p.m."}},h:(e,a)=>Xr(e.getHours()%12||12,a.length),H:(e,a)=>Xr(e.getHours(),a.length),m:(e,a)=>Xr(e.getMinutes(),a.length),s:(e,a)=>Xr(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return Xr(Math.trunc(r*Math.pow(10,t-3)),a.length)}},Zr="midnight",en="noon",an="morning",tn="afternoon",rn="evening",nn="night",on={G:function(e,a,t){const r=e.getFullYear()>0?1:0;switch(a){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});default:return t.era(r,{width:"wide"})}},y:function(e,a,t){if("yo"===a){const a=e.getFullYear(),r=a>0?a:1-a;return t.ordinalNumber(r,{unit:"year"})}return Jr.y(e,a)},Y:function(e,a,t,r){const n=Yr(e,r),i=n>0?n:1-n;if("YY"===a){return Xr(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):Xr(i,a.length)},R:function(e,a){return Xr(Gr(e),a.length)},u:function(e,a){return Xr(e.getFullYear(),a.length)},Q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"Q":return String(r);case"QQ":return Xr(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,a,t){const r=Math.ceil((e.getMonth()+1)/3);switch(a){case"q":return String(r);case"qq":return Xr(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,a,t){const r=e.getMonth();switch(a){case"M":case"MM":return Jr.M(e,a);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(e,a,t){const r=e.getMonth();switch(a){case"L":return String(r+1);case"LL":return Xr(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(e,a,t,r){const n=Qr(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):Xr(n,a.length)},I:function(e,a,t){const r=Kr(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):Xr(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Jr.d(e,a)},D:function(e,a,t){const r=qr(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):Xr(r,a.length)},E:function(e,a,t){const r=e.getDay();switch(a){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"e":return String(i);case"ee":return Xr(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(n,{width:"short",context:"formatting"});default:return t.day(n,{width:"wide",context:"formatting"})}},c:function(e,a,t,r){const n=e.getDay(),i=(n-r.weekStartsOn+8)%7||7;switch(a){case"c":return String(i);case"cc":return Xr(i,a.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(n,{width:"narrow",context:"standalone"});case"cccccc":return t.day(n,{width:"short",context:"standalone"});default:return t.day(n,{width:"wide",context:"standalone"})}},i:function(e,a,t){const r=e.getDay(),n=0===r?7:r;switch(a){case"i":return String(n);case"ii":return Xr(n,a.length);case"io":return t.ordinalNumber(n,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(e,a,t){const r=e.getHours()/12>=1?"pm":"am";switch(a){case"a":case"aa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(r,{width:"narrow",context:"formatting"});default:return t.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,a,t){const r=e.getHours();let n;switch(n=12===r?en:0===r?Zr:r/12>=1?"pm":"am",a){case"b":case"bb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(e,a,t){const r=e.getHours();let n;switch(n=r>=17?rn:r>=12?tn:r>=4?an:nn,a){case"B":case"BB":case"BBB":return t.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(n,{width:"narrow",context:"formatting"});default:return t.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(e,a,t){if("ho"===a){let a=e.getHours()%12;return 0===a&&(a=12),t.ordinalNumber(a,{unit:"hour"})}return Jr.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Jr.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):Xr(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):Xr(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Jr.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Jr.s(e,a)},S:function(e,a){return Jr.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return ln(r);case"XXXX":case"XX":return dn(r);default:return dn(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return ln(r);case"xxxx":case"xx":return dn(r);default:return dn(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+sn(r,":");default:return"GMT"+dn(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+sn(r,":");default:return"GMT"+dn(r,":")}},t:function(e,a,t){return Xr(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return Xr(e.getTime(),a.length)}};function sn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.trunc(r/60),i=r%60;return 0===i?t+String(n):t+String(n)+a+Xr(i,2)}function ln(e,a){if(e%60==0){return(e>0?"-":"+")+Xr(Math.abs(e)/60,2)}return dn(e,a)}function dn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Xr(Math.trunc(r/60),2)+a+Xr(r%60,2)}const cn=(e,a)=>{switch(e){case"P":return a.date({width:"short"});case"PP":return a.date({width:"medium"});case"PPP":return a.date({width:"long"});default:return a.date({width:"full"})}},un=(e,a)=>{switch(e){case"p":return a.time({width:"short"});case"pp":return a.time({width:"medium"});case"ppp":return a.time({width:"long"});default:return a.time({width:"full"})}},mn={p:un,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return cn(e,a);let i;switch(r){case"P":i=a.dateTime({width:"short"});break;case"PP":i=a.dateTime({width:"medium"});break;case"PPP":i=a.dateTime({width:"long"});break;default:i=a.dateTime({width:"full"})}return i.replace("{{date}}",cn(r,a)).replace("{{time}}",un(n,a))}},pn=/^D+$/,hn=/^Y+$/,fn=["D","DD","YY","YYYY"];function gn(e){if(!(a=e,a instanceof Date||"object"==typeof a&&"[object Date]"===Object.prototype.toString.call(a)||"number"==typeof e))return!1;var a;const t=Or(e);return!isNaN(Number(t))}const vn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,bn=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,xn=/^'([^]*?)'?$/,yn=/''/g,Nn=/[a-zA-Z]/;function wn(e,a,t){const r=Ur(),n=t?.locale??r.locale??zr,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,s=Or(e);if(!gn(s))throw new RangeError("Invalid time value");let l=a.match(bn).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,mn[a])(e,n.formatLong)}return e}).join("").match(vn).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:_n(e)};if(on[a])return{isToken:!0,value:e};if(a.match(Nn))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(s,l));const d={firstWeekContainsDate:i,weekStartsOn:o,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return hn.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return pn.test(e)}(i))&&function(e,a,t){const r=function(e,a,t){const r="Y"===e[0]?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${a}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}(e,a,t);if(fn.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,on[i[0]])(s,i,n.localize,d)}).join("")}function _n(e){const a=e.match(xn);return a?a[1].replace(yn,"'"):e}function Cn(e,a,t){const r=y(),n=function(e,a,t){return new Intl.DateTimeFormat(t?[t.code,"en-US"]:void 0,{timeZone:a,timeZoneName:e})}(e,t.timeZone,t.locale??r.locale);return"formatToParts"in n?function(e,a){const t=e.formatToParts(a);for(let r=t.length-1;r>=0;--r)if("timeZoneName"===t[r].type)return t[r].value;return}(n,a):function(e,a){const t=e.format(a).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(t);return r?r[0].substr(1):""}(n,a)}function kn(e,a){const t=function(e){An[e]||(An[e]=Dn?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:e,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}));return An[e]}(a);return"formatToParts"in t?function(e,a){try{const t=e.formatToParts(a),r=[];for(let e=0;e<t.length;e++){const a=Sn[t[e].type];void 0!==a&&(r[a]=parseInt(t[e].value,10))}return r}catch(t){if(t instanceof RangeError)return[NaN];throw t}}(t,e):function(e,a){const t=e.format(a),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(t);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}(t,e)}const Sn={year:0,month:1,day:2,hour:3,minute:4,second:5};const An={},En=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),Dn="06/25/2014, 00:00:00"===En||"06/25/2014 00:00:00"===En;function Pn(e,a,t,r,n,i,o){const s=new Date(0);return s.setUTCFullYear(e,a,t),s.setUTCHours(r,n,i,o),s}const In=36e5,Tn={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Rn(e,a,t){if(!e)return 0;let r,n,i=Tn.timezoneZ.exec(e);if(i)return 0;if(i=Tn.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Ln(r)?-r*In:NaN;if(i=Tn.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Ln(r,e)?(n=Math.abs(r)*In+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(zn[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),zn[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Pn(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Mn(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Mn(new Date(n),t);if(a===i)return a;n-=i-a;const o=Mn(new Date(n),t);if(i===o)return i;return Math.max(i,o)}(a,n,e);return-i}return NaN}function Mn(e,a){const t=kn(e,a),r=Pn(t[0],t[1]-1,t[2],t[3]%24,t[4],t[5],0).getTime();let n=e.getTime();const i=n%1e3;return n-=i>=0?i:1e3+i,r-n}function Ln(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const zn={};const Fn={X:function(e,a,t){const r=Un(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Bn(r);case"XXXX":case"XX":return On(r);default:return On(r,":")}},x:function(e,a,t){const r=Un(t.timeZone,e);switch(a){case"x":return Bn(r);case"xxxx":case"xx":return On(r);default:return On(r,":")}},O:function(e,a,t){const r=Un(t.timeZone,e);switch(a){case"O":case"OO":case"OOO":return"GMT"+function(e,a=""){const t=e>0?"-":"+",r=Math.abs(e),n=Math.floor(r/60),i=r%60;if(0===i)return t+String(n);return t+String(n)+a+jn(i,2)}(r,":");default:return"GMT"+On(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Cn("short",e,t);default:return Cn("long",e,t)}}};function Un(e,a){const t=e?Rn(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function jn(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function On(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+jn(Math.floor(r/60),2)+a+jn(Math.floor(r%60),2)}function Bn(e,a){if(e%60==0){return(e>0?"-":"+")+jn(Math.abs(e)/60,2)}return On(e,a)}function $n(e){const a=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return a.setUTCFullYear(e.getFullYear()),+e-+a}const Vn=36e5,qn=6e4,Wn={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/};function Hn(e,a={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(null===e)return new Date(NaN);const t=null==a.additionalDigits?2:Number(a.additionalDigits);if(2!==t&&1!==t&&0!==t)throw new RangeError("additionalDigits must be 0, 1 or 2");if(e instanceof Date||"object"==typeof e&&"[object Date]"===Object.prototype.toString.call(e))return new Date(e.getTime());if("number"==typeof e||"[object Number]"===Object.prototype.toString.call(e))return new Date(e);if("[object String]"!==Object.prototype.toString.call(e))return new Date(NaN);const r=function(e){const a={};let t,r=Wn.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Wn.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Wn.timeZone.exec(t);e?(a.time=t.replace(e[1],""),a.timeZone=e[1].trim()):a.time=t}return a}(e),{year:n,restDateString:i}=function(e,a){if(e){const t=Wn.YYY[a],r=Wn.YYYYY[a];let n=Wn.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Wn.YY.exec(e)||t.exec(e),n){const a=n[1];return{year:100*parseInt(a,10),restDateString:e.slice(a.length)}}}return{year:null}}(r.date,t),o=function(e,a){if(null===a)return null;let t,r,n;if(!e||!e.length)return t=new Date(0),t.setUTCFullYear(a),t;let i=Wn.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,Xn(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=Wn.DDD.exec(e),i){t=new Date(0);const e=parseInt(i[1],10);return function(e,a){if(a<1)return!1;const t=Qn(e);if(t&&a>366)return!1;if(!t&&a>365)return!1;return!0}(a,e)?(t.setUTCFullYear(a,0,e),t):new Date(NaN)}if(i=Wn.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return Xn(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=Wn.Www.exec(e),i)return n=parseInt(i[1],10)-1,Jn(n)?Gn(a,n):new Date(NaN);if(i=Wn.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return Jn(n,e)?Gn(a,n,e):new Date(NaN)}return null}(i,n);if(null===o||isNaN(o.getTime()))return new Date(NaN);if(o){const e=o.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Wn.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),Zn(a)?a%24*Vn:NaN;if(r=Wn.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),Zn(a,t)?a%24*Vn+t*qn:NaN;if(r=Wn.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return Zn(a,t,e)?a%24*Vn+t*qn+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Rn(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=$n(new Date(e+n)),t=$n(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Gn(e,a,t){a=a||0,t=t||0;const r=new Date(0);r.setUTCFullYear(e,0,4);const n=7*a+t+1-(r.getUTCDay()||7);return r.setUTCDate(r.getUTCDate()+n),r}const Kn=[31,28,31,30,31,30,31,31,30,31,30,31],Yn=[31,29,31,30,31,30,31,31,30,31,30,31];function Qn(e){return e%400==0||e%4==0&&e%100!=0}function Xn(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=Qn(e);if(r&&t>Yn[a])return!1;if(!r&&t>Kn[a])return!1}return!0}function Jn(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Zn(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const ei=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function ai(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(ei);if(r){const n=Hn(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],o=e.replace(a,"'"+Fn[a[0]](n,a,t)+"'");return i?o.substring(0,r-1)+o.substring(r+1):o},a)}return wn(e,a,t)}(function(e,a,t){const r=Rn(a,e=Hn(e,t),!0),n=new Date(e.getTime()-r),i=new Date(0);return i.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),i.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}(e,a,{timeZone:(r={...r,timeZone:a,originalDate:e}).timeZone}),t,r)}const ti={lessThanXSeconds:{one:"menos de un segundo",other:"menos de {{count}} segundos"},xSeconds:{one:"1 segundo",other:"{{count}} segundos"},halfAMinute:"medio minuto",lessThanXMinutes:{one:"menos de un minuto",other:"menos de {{count}} minutos"},xMinutes:{one:"1 minuto",other:"{{count}} minutos"},aboutXHours:{one:"alrededor de 1 hora",other:"alrededor de {{count}} horas"},xHours:{one:"1 hora",other:"{{count}} horas"},xDays:{one:"1 día",other:"{{count}} días"},aboutXWeeks:{one:"alrededor de 1 semana",other:"alrededor de {{count}} semanas"},xWeeks:{one:"1 semana",other:"{{count}} semanas"},aboutXMonths:{one:"alrededor de 1 mes",other:"alrededor de {{count}} meses"},xMonths:{one:"1 mes",other:"{{count}} meses"},aboutXYears:{one:"alrededor de 1 año",other:"alrededor de {{count}} años"},xYears:{one:"1 año",other:"{{count}} años"},overXYears:{one:"más de 1 año",other:"más de {{count}} años"},almostXYears:{one:"casi 1 año",other:"casi {{count}} años"}},ri={date:Pr({formats:{full:"EEEE, d 'de' MMMM 'de' y",long:"d 'de' MMMM 'de' y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:Pr({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Pr({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},ni={lastWeek:"'el' eeee 'pasado a la' p",yesterday:"'ayer a la' p",today:"'hoy a la' p",tomorrow:"'mañana a la' p",nextWeek:"eeee 'a la' p",other:"P"},ii={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},oi={code:"es",formatDistance:(e,a,t)=>{let r;const n=ti[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",a.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"en "+r:"hace "+r:r},formatLong:ri,formatRelative:(e,a,t,r)=>1!==a.getHours()?ii[e]:ni[e],localize:{ordinalNumber:(e,a)=>Number(e)+"º",era:Rr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Rr({values:{narrow:["1","2","3","4"],abbreviated:["T1","T2","T3","T4"],wide:["1º trimestre","2º trimestre","3º trimestre","4º trimestre"]},defaultWidth:"wide",argumentCallback:e=>Number(e)-1}),month:Rr({values:{narrow:["e","f","m","a","m","j","j","a","s","o","n","d"],abbreviated:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],wide:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]},defaultWidth:"wide"}),day:Rr({values:{narrow:["d","l","m","m","j","v","s"],short:["do","lu","ma","mi","ju","vi","sá"],abbreviated:["dom","lun","mar","mié","jue","vie","sáb"],wide:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"]},defaultWidth:"wide"}),dayPeriod:Rr({values:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"mañana",afternoon:"tarde",evening:"tarde",night:"noche"}},defaultWidth:"wide",formattingValues:{narrow:{am:"a",pm:"p",midnight:"mn",noon:"md",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},abbreviated:{am:"AM",pm:"PM",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"},wide:{am:"a.m.",pm:"p.m.",midnight:"medianoche",noon:"mediodia",morning:"de la mañana",afternoon:"de la tarde",evening:"de la tarde",night:"de la noche"}},defaultFormattingWidth:"wide"})},match:{ordinalNumber:Lr({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Mr({matchPatterns:{narrow:/^(ac|dc|a|d)/i,abbreviated:/^(a\.?\s?c\.?|a\.?\s?e\.?\s?c\.?|d\.?\s?c\.?|e\.?\s?c\.?)/i,wide:/^(antes de cristo|antes de la era com[uú]n|despu[eé]s de cristo|era com[uú]n)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^ac/i,/^dc/i],wide:[/^(antes de cristo|antes de la era com[uú]n)/i,/^(despu[eé]s de cristo|era com[uú]n)/i]},defaultParseWidth:"any"}),quarter:Mr({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:Mr({matchPatterns:{narrow:/^[efmajsond]/i,abbreviated:/^(ene|feb|mar|abr|may|jun|jul|ago|sep|oct|nov|dic)/i,wide:/^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^e/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^en/i,/^feb/i,/^mar/i,/^abr/i,/^may/i,/^jun/i,/^jul/i,/^ago/i,/^sep/i,/^oct/i,/^nov/i,/^dic/i]},defaultParseWidth:"any"}),day:Mr({matchPatterns:{narrow:/^[dlmjvs]/i,short:/^(do|lu|ma|mi|ju|vi|s[áa])/i,abbreviated:/^(dom|lun|mar|mi[ée]|jue|vie|s[áa]b)/i,wide:/^(domingo|lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^do/i,/^lu/i,/^ma/i,/^mi/i,/^ju/i,/^vi/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:Mr({matchPatterns:{narrow:/^(a|p|mn|md|(de la|a las) (mañana|tarde|noche))/i,any:/^([ap]\.?\s?m\.?|medianoche|mediodia|(de la|a las) (mañana|tarde|noche))/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^mn/i,noon:/^md/i,morning:/mañana/i,afternoon:/tarde/i,evening:/tarde/i,night:/noche/i}},defaultParseWidth:"any"})},options:{weekStartsOn:1,firstWeekContainsDate:1}},si={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"}},li={date:Pr({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:Pr({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Pr({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},di={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"},ci={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=si[e];return r="string"==typeof n?n:1===a?n.one:n.other.replace("{{count}}",String(a)),t?.addSuffix?t.comparison&&t.comparison>0?"em "+r:"há "+r:r},formatLong:li,formatRelative:(e,a,t,r)=>{const n=di[e];return"function"==typeof n?n(a):n},localize:{ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Rr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Rr({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:Rr({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:Rr({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:Rr({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"})},match:{ordinalNumber:Lr({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Mr({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:Mr({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:Mr({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:Mr({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:Mr({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"})},options:{weekStartsOn:0,firstWeekContainsDate:1}},ui=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],mi=[{value:"dd/MM/yyyy HH:mm",label:"dd/MM/yyyy HH:mm",example:"28/11/2024 14:30",description:"Padrão Brasileiro"},{value:"MM/dd/yyyy hh:mm a",label:"MM/dd/yyyy hh:mm a",example:"11/28/2024 02:30 PM",description:"Padrão Americano (12h)"},{value:"MM/dd/yyyy HH:mm",label:"MM/dd/yyyy HH:mm",example:"11/28/2024 14:30",description:"Padrão Americano (24h)"},{value:"yyyy-MM-dd HH:mm",label:"yyyy-MM-dd HH:mm",example:"2024-11-28 14:30",description:"ISO 8601"},{value:"dd.MM.yyyy HH:mm",label:"dd.MM.yyyy HH:mm",example:"28.11.2024 14:30",description:"Padrão Europeu"},{value:"d MMM yyyy, HH:mm",label:"d MMM yyyy, HH:mm",example:"28 Nov 2024, 14:30",description:"Formato Longo"}],pi=[{value:"America/Sao_Paulo",label:"Brasília (UTC-3)",offset:"-03:00"},{value:"America/Noronha",label:"Fernando de Noronha (UTC-2)",offset:"-02:00"},{value:"America/Manaus",label:"Manaus (UTC-4)",offset:"-04:00"},{value:"America/Rio_Branco",label:"Rio Branco (UTC-5)",offset:"-05:00"},{value:"America/Buenos_Aires",label:"Buenos Aires (UTC-3)",offset:"-03:00"},{value:"America/Santiago",label:"Santiago (UTC-4)",offset:"-04:00"},{value:"America/Bogota",label:"Bogotá (UTC-5)",offset:"-05:00"},{value:"America/Mexico_City",label:"Cidade do México (UTC-6)",offset:"-06:00"},{value:"America/New_York",label:"New York (UTC-5)",offset:"-05:00"},{value:"America/Chicago",label:"Chicago (UTC-6)",offset:"-06:00"},{value:"America/Denver",label:"Denver (UTC-7)",offset:"-07:00"},{value:"America/Los_Angeles",label:"Los Angeles (UTC-8)",offset:"-08:00"},{value:"America/Toronto",label:"Toronto (UTC-5)",offset:"-05:00"},{value:"America/Vancouver",label:"Vancouver (UTC-8)",offset:"-08:00"},{value:"Europe/London",label:"Londres (UTC+0)",offset:"+00:00"},{value:"Europe/Lisbon",label:"Lisboa (UTC+0)",offset:"+00:00"},{value:"Europe/Paris",label:"Paris (UTC+1)",offset:"+01:00"},{value:"Europe/Berlin",label:"Berlim (UTC+1)",offset:"+01:00"},{value:"Europe/Madrid",label:"Madrid (UTC+1)",offset:"+01:00"},{value:"Europe/Rome",label:"Roma (UTC+1)",offset:"+01:00"},{value:"Europe/Amsterdam",label:"Amsterdã (UTC+1)",offset:"+01:00"},{value:"Europe/Moscow",label:"Moscou (UTC+3)",offset:"+03:00"},{value:"Asia/Dubai",label:"Dubai (UTC+4)",offset:"+04:00"},{value:"Asia/Kolkata",label:"Mumbai (UTC+5:30)",offset:"+05:30"},{value:"Asia/Singapore",label:"Singapura (UTC+8)",offset:"+08:00"},{value:"Asia/Hong_Kong",label:"Hong Kong (UTC+8)",offset:"+08:00"},{value:"Asia/Shanghai",label:"Xangai (UTC+8)",offset:"+08:00"},{value:"Asia/Tokyo",label:"Tóquio (UTC+9)",offset:"+09:00"},{value:"Asia/Seoul",label:"Seul (UTC+9)",offset:"+09:00"},{value:"Australia/Perth",label:"Perth (UTC+8)",offset:"+08:00"},{value:"Australia/Sydney",label:"Sydney (UTC+10)",offset:"+10:00"},{value:"Pacific/Auckland",label:"Auckland (UTC+12)",offset:"+12:00"},{value:"UTC",label:"UTC (UTC+0)",offset:"+00:00"}],hi="pt-BR",fi="dd/MM/yyyy HH:mm",gi="America/Sao_Paulo",vi=e=>ui.find(a=>a.value===e),bi=e=>mi.find(a=>a.value===e),xi=e=>pi.find(a=>a.value===e),yi=e=>ui.some(a=>a.value===e),Ni=e=>mi.some(a=>a.value===e),wi=e=>pi.some(a=>a.value===e),_i=()=>{if("undefined"==typeof navigator)return hi;const e=navigator.language;if(yi(e))return e;const a=e.split("-")[0],t=ui.find(e=>e.value.startsWith(a));return t?.value||hi},Ci=()=>{if("undefined"==typeof Intl)return gi;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return wi(e)?e:gi}catch{return gi}},ki=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||fi),Si=()=>{const e=_i();return{locale:e,timezone:Ci(),datetimeFormat:ki(e)}},Ai={"pt-BR":ci,"en-US":zr,"es-ES":oi},Ei=(e,a=fi,t=gi,r=hi)=>{if(!e)return"";const n=N(e);if(!w(n))return"Data inválida";const i=Ai[r]||ci;try{return ai(n,t,a,{locale:i})}catch(o){return ai(n,gi,a,{locale:i})}},Di=(e,a=hi,t=gi)=>{if(!e)return"";const r=N(e);if(!w(r))return"Data inválida";const n=Ai[a]||ci;try{return ai(r,t,"PP",{locale:n})}catch(i){return ai(r,gi,"PP",{locale:n})}},Pi=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function Ii(e){const a=e.replace("#",""),t=3===a.length?a.split("").map(e=>e+e).join(""):a;return{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function Ti(e,a=.1){const{r:t,g:r,b:n}=Ii(e);return`rgba(${t}, ${r}, ${n}, ${a})`}function Ri(e){const{r:a,g:t,b:r}=Ii(e),[n,i,o]=[a,t,r].map(e=>{const a=e/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)});return.2126*n+.7152*i+.0722*o}function Mi(e,a){const t=Ri(e),r=Ri(a);return(Math.max(t,r)+.05)/(Math.min(t,r)+.05)}function Li(e,a){a?.stopPropagation();window.open(e,"_blank","noopener,noreferrer")||navigator.clipboard.writeText(e).then(()=>{C.info("Link copiado para a área de transferência")})}function zi(e,a){return a?e.replace(/\{alias\}/g,a):e}function Fi(...e){return x(b(e))}const Ui=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Ui);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Ui(r);return a}return e},ji=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Oi=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Bi=v("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm hover:shadow-md active:scale-[0.98]",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary-hover border border-input shadow-sm",tertiary:"bg-background text-foreground hover:bg-accent hover:text-accent-foreground border border-border",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",ghost:"hover:bg-accent hover:text-accent-foreground",subtle:"text-muted-foreground hover:text-foreground hover:bg-accent/50",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",danger:"bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-sm hover:shadow-md",link:"text-primary underline-offset-4 hover:underline",icon:"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2",loading:"bg-primary/50 text-primary-foreground cursor-wait",default:"bg-primary text-primary-foreground hover:bg-primary/90",action:"bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30","icon-only":"bg-transparent border border-input hover:bg-accent hover:text-accent-foreground p-2","external-link":"bg-transparent text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors","action-primary":"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm","action-secondary":"bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input"},size:{sm:"h-8 px-3 text-xs rounded-lg",md:"h-10 px-4 py-2 text-sm rounded-md",lg:"h-12 px-8 text-base rounded-lg",xl:"h-14 px-10 text-lg rounded-lg",icon:"h-10 w-10","icon-sm":"h-8 w-8","icon-xs":"h-6 w-6",default:"h-10 px-4 py-2"}},defaultVariants:{variant:"primary",size:"md"}}),$i=n.forwardRef(({className:e,variant:t,size:r,asChild:n=!1,...i},o)=>a(n?g:"button",{className:Fi(Bi({variant:t,size:r,className:e})),ref:o,...i}));$i.displayName="Button";const Vi=i.forwardRef(({className:e,children:t,variant:r="action",...n},i)=>a($i,{ref:i,variant:r,size:"icon",className:Fi("h-8 w-8",e),...n,children:t||a(A,{size:16})}));Vi.displayName="ActionButton";const qi=n.forwardRef(({className:e,type:r,showCharCount:i,maxLength:o,onChange:s,...l},d)=>{const[c,u]=n.useState(0);n.useEffect(()=>{"string"==typeof l.value?u(l.value.length):"string"==typeof l.defaultValue&&u(l.defaultValue.length)},[l.value,l.defaultValue]);return t("div",{className:"w-full",children:[a("input",{type:r,className:Fi("flex h-10 w-full rounded-lg 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 hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors md:text-sm",e),ref:d,maxLength:o,onChange:e=>{u(e.target.value.length),s?.(e)},...l}),i&&o&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[c," / ",o]})]})});qi.displayName="Input";const Wi=v("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Hi=n.forwardRef(({className:e,...t},r)=>a(Ra.Root,{ref:r,className:Fi(Wi(),e),...t}));Hi.displayName=Ra.Root.displayName;const Gi=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Gi.displayName="Card";const Ki=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("flex flex-col space-y-1.5 p-6",e),...t}));Ki.displayName="CardHeader";const Yi=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Fi("text-2xl font-semibold leading-none tracking-tight",e),...t}));Yi.displayName="CardTitle";const Qi=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));Qi.displayName="CardDescription";const Xi=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("p-6 pt-0",e),...t}));Xi.displayName="CardContent";const Ji=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("flex items-center p-6 pt-0",e),...t}));Ji.displayName="CardFooter";const Zi=n.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...n},i)=>a(La.Root,{ref:i,decorative:r,orientation:t,className:Fi("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...n}));Zi.displayName=La.Root.displayName;const eo=za.Root,ao=za.Trigger,to=za.Portal,ro=n.forwardRef(({className:e,...t},r)=>a(za.Overlay,{className:Fi("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:r}));ro.displayName=za.Overlay.displayName;const no=n.forwardRef(({className:e,...r},n)=>t(to,{children:[a(ro,{}),a(za.Content,{ref:n,className:Fi("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),...r})]}));no.displayName=za.Content.displayName;const io=({className:e,...t})=>a("div",{className:Fi("flex flex-col space-y-2 text-center sm:text-left",e),...t});io.displayName="AlertDialogHeader";const oo=({className:e,...t})=>a("div",{className:Fi("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});oo.displayName="AlertDialogFooter";const so=n.forwardRef(({className:e,...t},r)=>a(za.Title,{ref:r,className:Fi("text-lg font-semibold",e),...t}));so.displayName=za.Title.displayName;const lo=n.forwardRef(({className:e,...t},r)=>a(za.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));lo.displayName=za.Description.displayName;const co=n.forwardRef(({className:e,...t},r)=>a(za.Action,{ref:r,className:Fi(Bi(),e),...t}));co.displayName=za.Action.displayName;const uo=n.forwardRef(({className:e,...t},r)=>a(za.Cancel,{ref:r,className:Fi(Bi({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));uo.displayName=za.Cancel.displayName;const mo=Ma.Root,po=Ma.Trigger,ho=Ma.Portal,fo=Ma.Close,go=n.forwardRef(({className:e,...t},r)=>a(Ma.Overlay,{ref:r,className:Fi("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}));go.displayName=Ma.Overlay.displayName;const vo={sm:{width:"30vw",minWidth:"320px",maxWidth:"480px",maxHeight:"320px"},md:{width:"50vw",minWidth:"480px",maxWidth:"720px",maxHeight:"70vh"},lg:{width:"85vw",height:"85vh",maxWidth:"1440px",minHeight:"480px",maxHeight:"900px"}},bo=n.forwardRef(({className:r,children:i,size:o,variant:s="informative",isDirty:l,customWidth:d,customMinWidth:c,customMaxWidth:u,customHeight:m,customMinHeight:p,customMaxHeight:h,unsavedChangesTitle:f=e.t("unsaved_changes"),unsavedChangesDescription:g=e.t("unsaved_changes_description"),cancelText:v=e.t("cancel"),leaveWithoutSavingText:b=e.t("leave_without_saving"),style:x,onInteractOutside:y,onEscapeKeyDown:N,...w},_)=>{const[C,k]=n.useState(!1),S=n.useRef(null),A=n.useRef(!1),D=o??(d||c||u||m||p||h?void 0:"md"),P=D?vo[D]:{},I={...d??P.width?{width:d??P.width}:{},...c??P.minWidth?{minWidth:c??P.minWidth}:{},...u??P.maxWidth?{maxWidth:u??P.maxWidth}:{},...m??P.height?{height:m??P.height}:{},...p??P.minHeight?{minHeight:p??P.minHeight}:{},...h??P.maxHeight?{maxHeight:h??P.maxHeight}:{},...x},T=n.useCallback(e=>{"form"===s&&l?(S.current=e,k(!0)):e()},[s,l]),R=n.useRef(null),M="destructive"!==s;if("development"===process.env.NODE_ENV&&i){const e=n.Children.toArray(i);e.some(e=>n.isValidElement(e)&&"DialogFooter"===e.type?.displayName),e.some(e=>n.isValidElement(e)&&"DialogBody"===e.type?.displayName)}return t(ho,{children:[a(go,{}),t(Ma.Content,{ref:_,className:Fi("fixed left-[50%] top-[50%] z-50 flex flex-col translate-x-[-50%] translate-y-[-50%] border-0 border-l-[10px] border-l-primary 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%] rounded-lg max-sm:!w-[calc(100vw-2rem)] max-sm:!h-[calc(100dvh-2rem)] max-sm:!min-w-0 max-sm:!min-h-0 max-sm:!max-w-none max-sm:!max-h-none max-sm:p-4",r),style:I,onInteractOutside:e=>{"form"!==s&&"destructive"!==s?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==s)return"form"===s&&l?(e.preventDefault(),void T(()=>{A.current=!0,R.current?.click()})):void N?.(e);e.preventDefault()},...w,children:[i,M&&t(Ma.Close,{ref:R,onClick:e=>{A.current?A.current=!1:"form"===s&&l&&(e.preventDefault(),T(()=>{A.current=!0,R.current?.click()}))},className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[a(E,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]}),a(eo,{open:C,onOpenChange:k,children:t(no,{children:[t(io,{children:[a(so,{children:f}),a(lo,{children:g})]}),t(oo,{children:[a(uo,{onClick:()=>{k(!1),S.current=null},children:v}),a(co,{onClick:()=>{k(!1),S.current?.(),S.current=null},children:b})]})]})})]})});bo.displayName=Ma.Content.displayName;const xo=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Fi("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(Zi,{className:"mt-2"})]});xo.displayName="DialogHeader";const yo=({className:e,...t})=>a("div",{className:Fi("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",e),...t});yo.displayName="DialogBody";const No=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(Zi,{className:"mb-4"}),a("div",{className:Fi("flex flex-row justify-end gap-2",e),...n,children:r})]});No.displayName="DialogFooter";const wo=n.forwardRef(({className:e,...t},r)=>a(Ma.Title,{ref:r,className:Fi("text-xl font-semibold leading-none tracking-tight",e),...t}));wo.displayName=Ma.Title.displayName;const _o=n.forwardRef(({className:e,...t},r)=>a(Ma.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));_o.displayName=Ma.Description.displayName;const Co=Ua,ko=n.createContext({}),So=({...e})=>a(ko.Provider,{value:{name:e.name},children:a(ja,{...e})}),Ao=()=>{const e=n.useContext(ko),a=n.useContext(Eo),{getFieldState:t,formState:r}=Fa(),i=t(e.name,r);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:o}=a;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...i}},Eo=n.createContext({}),Do=n.forwardRef(({className:e,...t},r)=>{const i=n.useId();return a(Eo.Provider,{value:{id:i},children:a("div",{ref:r,className:Fi("space-y-1.5",e),...t})})});Do.displayName="FormItem";const Po=n.forwardRef(({className:e,...t},r)=>{const{error:n,formItemId:i}=Ao();return a(Hi,{ref:r,className:Fi(n&&"text-destructive",e),htmlFor:i,...t})});Po.displayName="FormLabel";const Io=n.forwardRef(({...e},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=Ao();return a(g,{ref:t,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...e})});Io.displayName="FormControl";const To=n.forwardRef(({className:e,...t},r)=>{const{formDescriptionId:n}=Ao();return a("p",{ref:r,id:n,className:Fi("text-sm text-muted-foreground",e),...t})});To.displayName="FormDescription";const Ro=n.forwardRef(({className:e,children:t,...r},n)=>{const{error:i,formMessageId:o}=Ao(),s=i?String(i?.message):t;return s?a("p",{ref:n,id:o,className:Fi("text-sm font-medium text-destructive",e),...r,children:s}):null});Ro.displayName="FormMessage";const Mo=$a.Root,Lo=$a.Group,zo=$a.Value,Fo=n.forwardRef(({className:e,children:r,...n},i)=>t($a.Trigger,{ref:i,className:Fi("flex h-10 w-full items-center justify-between rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors [&>span]:line-clamp-1",e),...n,children:[r,a($a.Icon,{asChild:!0,children:a(D,{className:"h-4 w-4 opacity-50"})})]}));Fo.displayName=$a.Trigger.displayName;const Uo=n.forwardRef(({className:e,...t},r)=>a($a.ScrollUpButton,{ref:r,className:Fi("flex cursor-default items-center justify-center py-1",e),...t,children:a(P,{className:"h-4 w-4"})}));Uo.displayName=$a.ScrollUpButton.displayName;const jo=n.forwardRef(({className:e,...t},r)=>a($a.ScrollDownButton,{ref:r,className:Fi("flex cursor-default items-center justify-center py-1",e),...t,children:a(D,{className:"h-4 w-4"})}));jo.displayName=$a.ScrollDownButton.displayName;const Oo=n.forwardRef(({className:e,children:r,position:n="popper",container:i,collisionBoundary:o,...s},l)=>a($a.Portal,{container:i,children:t($a.Content,{ref:l,className:Fi("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:o,...s,children:[a(Uo,{}),a($a.Viewport,{className:Fi("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),a(jo,{})]})}));Oo.displayName=$a.Content.displayName;const Bo=n.forwardRef(({className:e,...t},r)=>a($a.Label,{ref:r,className:Fi("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Bo.displayName=$a.Label.displayName;const $o=n.forwardRef(({className:e,children:r,...n},i)=>t($a.Item,{ref:i,className:Fi("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:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a($a.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),a($a.ItemText,{children:r})]}));$o.displayName=$a.Item.displayName;const Vo=n.forwardRef(({className:e,...t},r)=>a($a.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-muted",e),...t}));Vo.displayName=$a.Separator.displayName;const qo=n.forwardRef(({className:e,...t},r)=>a(Va.Root,{ref:r,className:Fi("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:a(Va.Indicator,{className:Fi("flex items-center justify-center text-current"),children:a(I,{className:"h-4 w-4"})})}));qo.displayName=Va.Root.displayName;const Wo=n.forwardRef(({className:e,showCharCount:r,maxLength:i,onChange:o,...s},l)=>{const[d,c]=n.useState(0);n.useEffect(()=>{"string"==typeof s.value?c(s.value.length):"string"==typeof s.defaultValue&&c(s.defaultValue.length)},[s.value,s.defaultValue]);return t("div",{className:"w-full",children:[a("textarea",{className:Fi("flex min-h-[80px] w-full rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:border-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-colors",e),ref:l,maxLength:i,onChange:e=>{c(e.target.value.length),o?.(e)},...s}),r&&i&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",i]})]})});Wo.displayName="Textarea";const Ho=v("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",danger:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-success text-success-foreground hover:bg-success/90",warning:"border-transparent bg-warning text-warning-foreground hover:bg-warning/90",info:"border-transparent bg-primary/10 text-primary hover:bg-primary/20",sharp:"border-transparent bg-[hsl(78,70%,46%)] text-foreground hover:bg-[hsl(78,70%,40%)]"}},defaultVariants:{variant:"default"}}),Go=n.forwardRef(({className:e,variant:t,...r},n)=>a("div",{ref:n,className:Fi(Ho({variant:t}),e),...r}));Go.displayName="Badge";const Ko={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Yo({size:e="md",className:t}){return a(T,{className:Fi("animate-spin text-muted-foreground",Ko[e],t)})}function Qo({isLoading:e,children:n,className:i,type:o="spinner",size:s="md"}){return e?"overlay"===o?t("div",{className:Fi("relative",i),children:[n,a("div",{className:"absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10",children:a(Yo,{size:s})})]}):a("div","skeleton"===o?{className:Fi("animate-pulse",i),children:a("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Fi("flex items-center justify-center py-8",i),children:a(Yo,{size:s})}):a(r,{children:n})}const Xo=({...e})=>a(k,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:a(F,{className:"h-4 w-4"}),info:a(z,{className:"h-4 w-4"}),warning:a(L,{className:"h-4 w-4"}),error:a(M,{className:"h-4 w-4"}),loading:a(R,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive-light !border-destructive-light",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...e}),Jo=qa.Root,Zo=qa.Trigger,es=qa.Group,as=qa.Portal,ts=qa.Sub,rs=qa.RadioGroup,ns=n.forwardRef(({className:e,inset:r,children:n,...i},o)=>t(qa.SubTrigger,{ref:o,className:Fi("flex cursor-default select-none items-center px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",r&&"pl-8",e),...i,children:[n,a(U,{className:"ml-auto h-4 w-4"})]}));ns.displayName=qa.SubTrigger.displayName;const is=n.forwardRef(({className:e,...t},r)=>a(qa.SubContent,{ref:r,className:Fi("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}));is.displayName=qa.SubContent.displayName;const os=n.forwardRef(({className:e,sideOffset:t=4,...r},n)=>a(qa.Portal,{children:a(qa.Content,{ref:n,sideOffset:t,className:Fi("z-[100] min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground p-1 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));os.displayName=qa.Content.displayName;const ss=n.forwardRef(({className:e,inset:t,...r},n)=>a(qa.Item,{ref:n,className:Fi("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),...r}));ss.displayName=qa.Item.displayName;const ls=n.forwardRef(({className:e,children:r,checked:n,...i},o)=>t(qa.CheckboxItem,{ref:o,className:Fi("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,...i,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(qa.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),r]}));ls.displayName=qa.CheckboxItem.displayName;const ds=n.forwardRef(({className:e,children:r,...n},i)=>t(qa.RadioItem,{ref:i,className:Fi("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:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(qa.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));ds.displayName=qa.RadioItem.displayName;const cs=n.forwardRef(({className:e,inset:t,...r},n)=>a(qa.Label,{ref:n,className:Fi("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));cs.displayName=qa.Label.displayName;const us=n.forwardRef(({className:e,...t},r)=>a(qa.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-muted",e),...t}));us.displayName=qa.Separator.displayName;const ms=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest opacity-60",e),...t});ms.displayName="DropdownMenuShortcut";const ps=({delayDuration:e=300,...t})=>a(Wa.Provider,{delayDuration:e,...t}),hs=Wa.Root,fs=Wa.Trigger,gs=n.forwardRef(({className:e,sideOffset:t=4,container:r,...n},i)=>a(Wa.Portal,{container:r,children:a(Wa.Content,{ref:i,sideOffset:t,className:Fi("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})}));gs.displayName=Wa.Content.displayName;const vs=n.forwardRef(({children:e,disabledReason:r,className:n},i)=>{const o=a(ss,{ref:i,className:Fi("opacity-50 cursor-not-allowed pointer-events-auto",n),onSelect:e=>{e.preventDefault(),e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation()},children:e});return r?a(ps,{delayDuration:100,children:t(hs,{children:[a(fs,{asChild:!0,children:a("div",{className:"w-full",children:o})}),a(gs,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):o});vs.displayName="DisabledMenuItem";const bs=Ha.Root,xs=Ha.Trigger,ys=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,container:n,...i},o)=>a(Ha.Portal,{container:n,children:a(Ha.Content,{ref:o,align:t,sideOffset:r,className:Fi("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),...i})}));ys.displayName=Ha.Content.displayName;const Ns=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));Ns.displayName="Command";const ws=({children:e,...t})=>a("div",{...t,children:a(Ns,{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})}),_s=n.forwardRef(({className:e,...t},r)=>a("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:a("input",{ref:r,className:Fi("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})}));_s.displayName="CommandInput";const Cs=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));Cs.displayName="CommandList";const ks=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("py-6 text-center text-sm text-muted-foreground",e),...t}));ks.displayName="CommandEmpty";const Ss=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("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}));Ss.displayName="CommandGroup";const As=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("-mx-1 h-px bg-border",e),...t}));As.displayName="CommandSeparator";const Es=n.forwardRef(({className:e,disabled:t,onSelect:r,value:n,...i},o)=>a("div",{ref:o,className:Fi("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),"data-disabled":t,onClick:()=>!t&&r?.(n||""),...i}));Es.displayName="CommandItem";const Ds=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});function Ps({className:e,...t}){return a("div",{className:Fi("animate-pulse rounded-md bg-muted",e),...t})}Ds.displayName="CommandShortcut";const Is=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ts({multiple:r,options:n,value:i,onChange:l,getOptionValue:d,getOptionLabel:c,placeholder:u,label:m,icon:p,emptyMessage:h,searchPlaceholder:f,disabled:g,required:v,className:b,sortOptions:x,maxDisplayedBadges:y,popoverContainer:N,onOpen:w,onClose:_,clearable:C}){const[k,S]=o(!1),[A,P]=o(""),T=s(()=>i?Array.isArray(i)?i:[i]:[],[i]),R=s(()=>{if(!N)return;let e=N,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[N]),M=s(()=>{const e=n.map(e=>({original:e,value:d(e),label:c(e)}));return x?e.sort((e,a)=>e.label.localeCompare(a.label,"pt-BR",{sensitivity:"base"})):e},[n,d,c,x]),L=s(()=>{if(!A)return M;const e=Is(A);return M.filter(a=>Is(a.label).includes(e))},[M,A]),z=s(()=>M.filter(e=>T.includes(e.value)),[M,T]),F=e=>{S(e),e?w?.():(P(""),_?.())},U=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(r?T.filter(a=>a!==e):"")},j=y?z.slice(0,y):z,O=y&&z.length>y?z.length-y:0;return t("div",{className:Fi("space-y-2",b),children:[m&&t(Hi,{children:[m,v&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(bs,{open:k,onOpenChange:F,modal:!1,children:[r?a(xs,{asChild:!0,children:t("div",{role:"combobox","aria-expanded":k,"aria-disabled":g,tabIndex:g?-1:0,onKeyDown:e=>{g||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),F(!k))},className:Fi("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",g&&"pointer-events-none opacity-50 cursor-not-allowed",0===z.length&&"text-muted-foreground"),children:[0===z.length?t("span",{className:"flex items-center gap-2",children:[p&&a(p,{className:"h-4 w-4"}),u]}):t("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[j.map(e=>t(Go,{variant:"secondary",className:"gap-1 pr-1",children:[e.label,a("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:a=>{"Enter"===a.key&&U(e.value,a)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:a=>U(e.value,a),children:a(E,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),O>0&&t(Go,{variant:"outline",className:"gap-1",children:["+",O]})]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]})}):t("div",{className:"flex items-center gap-1",children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",role:"combobox","aria-expanded":k,disabled:g,className:Fi("flex-1 justify-between min-h-10 h-auto",0===z.length&&"text-muted-foreground"),children:[0===z.length?t("span",{className:"flex items-center gap-2",children:[p&&a(p,{className:"h-4 w-4"}),u]}):t("span",{className:"flex items-center gap-2",children:[p&&a(p,{className:"h-4 w-4"}),z[0]?.label]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),C&&z.length>0&&a($i,{type:"button",variant:"ghost",size:"icon",disabled:g,className:"h-9 w-9 shrink-0 text-muted-foreground hover:text-foreground",onClick:e=>U("",e),title:"Limpar seleção",children:a(E,{className:"h-4 w-4"})})]}),a(ys,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:R,collisionBoundary:R,children:t(Ns,{children:[t("div",{className:"relative",children:[a(_s,{placeholder:f,value:A,onChange:e=>P(e.target.value)}),A&&a("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:a(E,{className:"h-3.5 w-3.5"})})]}),a(Cs,{children:0===n.length?a(ks,{children:h}):0===L.length?a(ks,{children:e.t("no_results")}):a(Ss,{children:L.map(e=>t(Es,{value:e.value,onSelect:()=>(e=>{if(l)if(r){const a=T.includes(e)?T.filter(a=>a!==e):[...T,e];l(a)}else l(e),S(!1)})(e.value),className:"cursor-pointer",children:[a(I,{className:Fi("mr-2 h-4 w-4",T.includes(e.value)?"opacity-100":"opacity-0")}),e.label]},e.value))})})]})})]})]})}function Rs({multiple:e=!1,options:r,items:n,value:i,onChange:o,onValueChange:s,getOptionValue:l=e=>e.value,getOptionLabel:d=e=>e.label,placeholder:c,label:u,icon:m,emptyMessage:p,searchPlaceholder:h,disabled:f=!1,required:g=!1,isLoading:v=!1,error:b,className:x,sortOptions:y=!0,maxDisplayedBadges:N,popoverContainer:w,onOpen:_,onClose:C,clearable:k=!0}){const{t:S}=Ga(),A=r||n||[],E=s||o,D=c||S("select_placeholder","Selecione..."),P=p||S("no_results",S("no_results")),I=h||S("search_placeholder","Pesquisar...");if(v)return t("div",{className:Fi("space-y-2",x),children:[u&&t(Hi,{children:[u,g&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ps,{className:"h-10 w-full"})]});const T="string"==typeof b?b:b instanceof Error?b.message:b?S("error_loading",S("error_loading")):void 0;return T?t("div",{className:Fi("space-y-2",x),children:[u&&t(Hi,{children:[u,g&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[a(O,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:T})]})]}):a(Ts,{multiple:e,options:A,value:i||(e?[]:""),onChange:E,getOptionValue:l,getOptionLabel:d,placeholder:D,label:u,icon:m,emptyMessage:P,searchPlaceholder:I,disabled:f,required:g,className:x,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:_,onClose:C,clearable:k})}const Ms=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Ls(e,a){if(!a)return null;const t=Ms(a),r=[];for(const n of e){const e=Ms(n.label).includes(t),i=n.children?Ls(n.children,a):null,o=i&&i.length>0;(e||o)&&r.push({...n,children:e?n.children:o?i:n.children})}return r}function zs(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=zs(t.children,a);if(e)return e}}}function Fs({node:e,level:r,expanded:n,onToggleExpand:i,selectedValues:o,onSelect:s}){const l=e.children&&e.children.length>0,d=o.includes(e.value);return t("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":d,className:Fi("flex items-center gap-1 rounded-sm px-2 py-1.5 text-sm cursor-pointer","hover:bg-accent hover:text-accent-foreground","outline-none"),style:{paddingLeft:8+20*r+"px"},children:[t("span",{className:"flex flex-1 items-center gap-2 truncate",onClick:a=>{a.stopPropagation(),s(e.value)},children:[a(I,{className:Fi("h-4 w-4 shrink-0",d?"opacity-100":"opacity-0")}),(()=>{const t=d?e.iconSelected??(n?e.iconOpen:null)??e.icon:n?e.iconOpen??e.icon:e.icon;return t?a(t,{className:Fi("h-4 w-4 shrink-0",e.iconClassName||"text-muted-foreground")}):null})(),a("span",{className:"truncate",children:e.label})]}),l&&a("button",{type:"button",className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm hover:bg-muted ml-auto",onClick:a=>{a.stopPropagation(),i(e.value)},tabIndex:-1,"aria-label":n?"Recolher":"Expandir",children:a(n?D:U,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Us({nodes:e,level:n,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:d}){return a(r,{children:e.map(e=>{const r=o.has(e.value);return t(i.Fragment,{children:[a(Fs,{node:e,level:n,expanded:r,onToggleExpand:s,selectedValues:l,onSelect:d}),r&&e.children&&e.children.length>0&&a(Us,{nodes:e.children,level:n+1,expandedIds:o,onToggleExpand:s,selectedValues:l,onSelect:d})]},e.value)})})}function js({multiple:e=!1,options:r,value:n,onChange:i,placeholder:d,label:c,icon:u,emptyMessage:m,searchPlaceholder:p,disabled:h=!1,required:f=!1,isLoading:g=!1,error:v,className:b,maxDisplayedBadges:x,popoverContainer:y,onOpen:N,onClose:w,defaultExpanded:_=!0}){const{t:C}=Ga(),[k,S]=o(!1),[A,P]=o(""),[I,T]=o(()=>_?function(e){const a=new Set;return function e(t){for(const r of t)r.children&&r.children.length>0&&(a.add(r.value),e(r.children))}(e),a}(r):new Set),R=d||C("select_placeholder","Selecione..."),M=m||C("no_results",C("no_results")),L=p||C("search_placeholder","Pesquisar..."),z=s(()=>n?Array.isArray(n)?n:[n]:[],[n]),F=s(()=>{if(!y)return;let e=y,a=0;try{for(;e&&a<3;){const t=window.getComputedStyle(e),r=t.overflowY||t.overflow;if(!r||"visible"===r||"unset"===r)break;e=e.parentElement,a++}}catch{}return e??void 0},[y]),U=s(()=>Ls(r,A),[r,A])??r,j=s(()=>A?function(e,a){const t=new Set,r=Ms(a);function n(e){if(!e.children||0===e.children.length)return Ms(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||Ms(e.label).includes(r)}for(const i of e)n(i);return t}(r,A):new Set,[r,A]),$=A?j:I,V=l(e=>{A||T(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[A]),q=s(()=>z.map(e=>({value:e,label:zs(r,e)||e})),[z,r]),W=e=>{S(e),e?N?.():(P(""),w?.())},H=l(a=>{if(i)if(e){const e=z.includes(a)?z.filter(e=>e!==a):[...z,a];i(e)}else i(a),S(!1)},[i,e,z]),G=(a,t)=>{t.preventDefault(),t.stopPropagation(),i&&i(e?z.filter(e=>e!==a):"")},K=x?q.slice(0,x):q,Y=x&&q.length>x?q.length-x:0;if(g)return t("div",{className:Fi("space-y-2",b),children:[c&&t(Hi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ps,{className:"h-10 w-full"})]});const Q="string"==typeof v?v:v instanceof Error?v.message:v?C("error_loading",C("error_loading")):void 0;return t("div",Q?{className:Fi("space-y-2",b),children:[c&&t(Hi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t("div",{className:"flex items-center gap-2 p-3 border border-destructive rounded-md bg-destructive/10 text-destructive",children:[a(O,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:Q})]})]}:{className:Fi("space-y-2",b),children:[c&&t(Hi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(bs,{open:k,onOpenChange:W,modal:!1,children:[a(xs,{asChild:!0,children:e?t("div",{role:"combobox","aria-expanded":k,"aria-disabled":h,tabIndex:h?-1:0,onKeyDown:e=>{h||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),W(!k))},className:Fi("flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","min-h-10 h-auto cursor-pointer",h&&"pointer-events-none opacity-50 cursor-not-allowed",0===q.length&&"text-muted-foreground"),children:[0===q.length?t("span",{className:"flex items-center gap-2",children:[u&&a(u,{className:"h-4 w-4"}),R]}):t("div",{className:"flex flex-wrap gap-1.5 flex-1 mr-2",children:[K.map(e=>t(Go,{variant:"secondary",className:"gap-1 pr-1",children:[e.label,a("button",{type:"button",className:"rounded-full outline-none ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2",onKeyDown:a=>{"Enter"===a.key&&G(e.value,a)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:a=>G(e.value,a),children:a(E,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),Y>0&&t(Go,{variant:"outline",className:"gap-1",children:["+",Y]})]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]}):t($i,{variant:"outline",role:"combobox","aria-expanded":k,disabled:h,className:Fi("w-full justify-between min-h-10 h-auto font-normal",0===q.length&&"text-muted-foreground"),children:[0===q.length?t("span",{className:"flex items-center gap-2",children:[u&&a(u,{className:"h-4 w-4"}),R]}):t("span",{className:"flex items-center gap-2",children:[u&&a(u,{className:"h-4 w-4"}),q[0]?.label]}),a(D,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),t(ys,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:F,collisionBoundary:F,children:[t("div",{className:"flex items-center border-b px-3",children:[a(B,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a("input",{className:"flex h-10 w-full bg-transparent py-3 px-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",placeholder:L,value:A,onChange:e=>P(e.target.value)}),A&&a("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:a(E,{className:"h-3.5 w-3.5"})})]}),a("div",{className:"max-h-[300px] overflow-y-auto overflow-x-hidden",children:a("div",{role:"tree",className:"p-1",children:0===U.length?a("div",{className:"py-6 text-center text-sm text-muted-foreground",children:0===r.length?M:C("no_search_results",C("no_results"))}):a(Us,{nodes:U,level:0,expandedIds:$,onToggleExpand:V,selectedValues:z,onSelect:H})})})]})]})]})}class Os{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 n=e.split(".");if(3!==n.length)return null;const i=n[1];i.length,this.LARGE_PAYLOAD_THRESHOLD;try{const e=this.normalizeBase64Url(i),a=atob(e),t=new Uint8Array(a.length);for(let n=0;n<a.length;n++)t[n]=a.charCodeAt(n);const r=new TextDecoder("utf-8").decode(t);return JSON.parse(r)}catch(a){try{const e=this.normalizeBase64Url(i),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(i),a=atob(e);return JSON.parse(a)}catch(r){throw r}}}}catch(n){return null}}static validateTokens(e,a){const t=[],r=[];try{a.split(".")[1],e.split(".")[1];const n=this.parseJwtPayload(a),i=this.parseJwtPayload(e);if(!n){const e="ID token decode falhou - possível problema com base64url encoding";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}let o=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),o=!1}const s=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<s){const e="Access token expirado - pode precisar de refresh";t.push(e),o=!1}if(n.exp&&n.exp<s){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:o,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:o,warnings:t,errors:r}}catch(n){const e=`Erro na validação de tokens: ${n}`;return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:!1,warnings:t,errors:r}}}static isTokenExpired(e){const a=this.parseJwtPayload(e);return!a||!a.exp||1e3*a.exp<Date.now()}}Os.LARGE_PAYLOAD_THRESHOLD=1e3;const Bs="qualiex_access_token",$s="qualiex_id_token",Vs="supabase_token",qs="oauth_state",Ws="oauth_nonce",Hs="selected_alias",Gs="manual_logout",Ks="supabase_project_id",Ys={setAccessToken:e=>localStorage.setItem(Bs,e),getAccessToken:()=>localStorage.getItem(Bs),setIdToken:e=>localStorage.setItem($s,e),getIdToken:()=>localStorage.getItem($s),getSupabaseToken:()=>localStorage.getItem(Vs),setOAuthState:e=>sessionStorage.setItem(qs,e),getOAuthState:()=>sessionStorage.getItem(qs),clearOAuthState:()=>sessionStorage.removeItem(qs),setOAuthNonce:e=>sessionStorage.setItem(Ws,e),getOAuthNonce:()=>sessionStorage.getItem(Ws),clearOAuthNonce:()=>sessionStorage.removeItem(Ws),setSelectedAlias:e=>localStorage.setItem(Hs,e),getSelectedAlias:()=>localStorage.getItem(Hs),clearSelectedAlias:()=>localStorage.removeItem(Hs),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Ys.getAccessToken()||!Ys.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(Ks);return a&&a!==e?(Ys.clearAll(),localStorage.setItem(Ks,e),!0):(a||localStorage.setItem(Ks,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Vs,e),Ys._clearValidationCache()},areAllTokensValid:()=>{const e=Ys.getAccessToken(),a=Ys.getIdToken();if(!e||!a)return!1;try{const t=Os.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Ys.getAccessToken(),t=Ys.getIdToken(),r=Ys.getSupabaseToken();return a&&Ys.isTokenExpired(a)&&(localStorage.removeItem(Bs),e=!0),t&&Ys.isTokenExpired(t)&&(localStorage.removeItem($s),e=!0),r&&Ys.isTokenExpired(r)&&(localStorage.removeItem(Vs),e=!0),e},clearAll:()=>{localStorage.removeItem(Bs),localStorage.removeItem($s),localStorage.removeItem(Vs),localStorage.removeItem(Hs),localStorage.removeItem(Gs),sessionStorage.removeItem(qs),sessionStorage.removeItem(Ws),Ys._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Gs,"true"),isManualLogout:()=>"true"===localStorage.getItem(Gs),clearManualLogout:()=>localStorage.removeItem(Gs),isTokenExpired:e=>{try{return Os.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Ys._validationCache.isValid=!1,Ys._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Ys.getSupabaseToken();if(!e)return!1;if(Ys.isTokenExpired(e))return Ys._clearValidationCache(),Ys._handleExpiredToken(),!1;const a=Date.now();return a-Ys._validationCache.timestamp<Ys._validationCache.cacheValidityMs?Ys._validationCache.isValid:(Ys._validationCache.isValid=!0,Ys._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Ys.isSupabaseTokenValid()?Ys.getSupabaseToken():null,_handleExpiredToken:()=>{Ys.clearAll()},extractTokenData:()=>{if(!Ys.isSupabaseTokenValid())return null;const e=Ys.getSupabaseToken();if(!e)return null;try{const a=Os.parseJwtPayload(e);if(!a)return null;const t=a.alias||a.default||a.user_alias,r=a.place_id||null,n=a.place_name||null;let i=a.company_id;if(!i&&t)for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.split(";");if(e.length>7&&e[0]===t){i=e[7];break}}}return{alias:t,companyId:i,placeId:r,placeName:n,payload:a}}catch(a){return Ys._handleExpiredToken(),null}},getCompanyId:e=>{const a=Ys.getAccessToken();if(a)try{const t=Os.parseJwtPayload(a);if(t)for(const a in t)if(a.startsWith("co")&&/^co\d+$/.test(a)){const r=t[a];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}const t=Ys.extractTokenData();if(t?.companyId)return t.companyId;const r=Ys.getIdToken();if(r)try{const a=Os.parseJwtPayload(r);if(a)for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>7&&a[0]===e)return a[7];if(!e&&a.length>7)return a[7]}}}catch(n){}return null},getCompanyIdInt:e=>{const a=[Ys.getAccessToken(),Ys.getIdToken()];for(const t of a)if(t)try{const a=Os.parseJwtPayload(t);if(!a)continue;for(const t in a)if(t.startsWith("co")&&/^co\d+$/.test(t)){const r=a[t];if(r&&"string"==typeof r){const a=r.split(";");if(e&&a.length>1&&a[0]===e)return a[1];if(!e&&a.length>1)return a[1]}}}catch{}return null},getCurrentCompanyId:()=>{const e=Ys.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Ys.getIdToken();if(!e)return[];try{const a=Os.parseJwtPayload(e);if(!a)return[];const t=[];for(const e in a)if(e.startsWith("co")&&/^co\d+$/.test(e)){const r=a[e];if(r&&"string"==typeof r){const e=r.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[]}}};const Qs=new class{constructor(){this.errors=[],this.toastCount=0,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}),this.errors.length>50&&(this.errors=this.errors.slice(-50)),a&&this.shouldShowToast()){const e=this.getErrorTitle(t);C.error(e,{description:t})}}getErrorTitle(a){const t=a.toLowerCase();return t.includes("401")||t.includes("unauthorized")||t.includes("expirou")?e.t("error_session_expired"):t.includes("token")||t.includes("autenticação")?e.t("error_authentication"):t.includes("api")||t.includes("network")?e.t("error_connection"):"Erro"}success(e,a){C.success(e,{description:a})}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=[]}};["[forlogic-core] ⚠️ VITE_SUPABASE_PUBLISHABLE_KEY contém uma legacy anon key (JWT).","O Supabase desativou legacy API keys. Substitua pela nova publishable key (formato sb_publishable_*).","Todas as requests retornarão 401 Unauthorized.","Causa provável: a integração Supabase do Lovable sobrescreveu o .env com a anon key legada.","Solução: defina VITE_SUPABASE_PK_OVERRIDE no .env com a publishable key correta."].join(" ");function Xs(e){return!!e&&e.startsWith("eyJ")}function Js(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE;return e||(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY??"")}let Zs=!1;const el=import.meta.env.VITE_SUPABASE_URL,al=Js();class tl{constructor(){this.currentToken=null,function(){const e=import.meta.env.VITE_SUPABASE_PK_OVERRIDE,a=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;Zs?Xs(a):e&&Xs(a)?Zs=!0:Xs(a)?Zs=!0:Zs=!0}(),this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:al};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Qa(el,al,{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 tl.instance||(tl.instance=new tl),tl.instance}getClient(){const e=Ys.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Os.isTokenExpired(e)}catch(a){return Qs.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function rl(){return tl.getInstance().getClient()}class nl{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Ys.getSupabaseToken();if(e&&Ys.isSupabaseTokenValid())return e}const n=rl(),{data:i,error:o}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return o&&(o.message?.includes("401")||o.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(Ys.setSupabaseToken(i.access_token),i.access_token):null}catch(n){return n instanceof Error&&(n.message.includes("401")||n.message.includes("Unauthorized"))&&t?.(),null}}}class il{static setLogoutCallback(e){this.onLogoutCallback=e}static async attemptRegeneration(e=!1){if(this.regenerationPromise)return this.regenerationPromise;this.regenerationPromise=this._doRegenerate(e);try{return await this.regenerationPromise}finally{this.regenerationPromise=null}}static async _doRegenerate(e=!1){try{const a=Ys.getAccessToken(),t=Ys.getSelectedAlias();if(!a||!t)return null;const r=await nl.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}il.regenerationPromise=null,il.onLogoutCallback=null;class ol{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Ys.clearAll(),window.location.href="/login",!0)}static isAuthenticationError(e,a){if(401===e.status||401===e.statusCode)return!0;const t=a.toLowerCase();return["401","unauthorized","token expired","invalid token","session expired","jwt expired","authentication failed","not authenticated"].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.")}}}class sl{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 il.attemptRegeneration()?(this.isRetrying=!1,!0):(ol.handleError(e),this.isRetrying=!1,!1)}catch(r){return ol.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Ys.getAccessToken();return e?Ys.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."}}}sl.isRetrying=!1;const ll=new class{get baseUrl(){return xr()}async makeApiCall(e,a,t){const r=sl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Ys.getAccessToken();if(!n)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 i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status} ${o.statusText}`);throw e.status=o.status,e.statusCode=o.status,e}return await o.json()}mapToQualiexUser(e){let a;return a="boolean"==typeof e.isActive?e.isActive:"boolean"==typeof e.active?e.active:"string"!=typeof e.status||"active"===e.status.toLowerCase(),{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0,isActive:a}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return Qs.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(e=>this.mapToQualiexUser(e)):(Qs.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a,t="active"){const r={companyId:a,search:"",filterStatus:t};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",r,e);return this.parseUsersResponse(a)??[]}catch(n){if(await sl.handleApiError(n))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",r,e);return this.parseUsersResponse(a," após retry")??[]}catch(i){return Qs.handleError(i instanceof Error?i:"Erro ao buscar usuários após renovação de token",!0),[]}return Qs.handleError(n instanceof Error?n.message:"Erro ao buscar usuários da API Qualiex",!0),[]}}async fetchUserById(e,a,t){try{return(await this.fetchUsers(a,t)).find(a=>a.userId===e)||null}catch(r){return Qs.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a,"active"),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async fetchAllUsersMap(e,a){const t=await this.fetchUsers(e,a,"all"),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e,a="active"){const t=Ys.extractTokenData();return t&&t.companyId?this.fetchUsers(e,t.companyId,a):[]}async fetchSoftwares(e){try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):(Qs.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await sl.handleApiError(a))try{const a=await this.makeApiCall("/api/common/v1/softwares",{},e),t=a?.data||a;return Array.isArray(t)?t.map(e=>({id:e.id,alias:e.alias||"",color:e.color||"",colorLight:e.colorLight||"",namePtBr:e.namePtBr||"",nameUs:e.nameUs||"",nameEs:e.nameEs||""})):[]}catch(t){return Qs.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return Qs.handleError(a instanceof Error?a.message:"Erro ao buscar softwares da API Qualiex",!0),[]}}async fetchUserAssociations(e,a){try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):(Qs.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await sl.handleApiError(t))try{const t=await this.makeApiCall(`/api/common/v1/Users/${e}/associations`,{},a),r=t?.data||t;return Array.isArray(r)?r.map(e=>({associationId:e.associationId||"",userId:e.userId||"",userName:e.userName||"",companyId:e.companyId||"",companyName:e.companyName||"",companyAlias:e.companyAlias||"",companyPhotoDate:e.companyPhotoDate,language:e.language,roleId:e.roleId||"",roleName:e.roleName||"",placeId:e.placeId,placeName:e.placeName,softwares:Array.isArray(e.softwares)?e.softwares:[],functionalities:Array.isArray(e.functionalities)?e.functionalities:[],isQualitfy:e.isQualitfy??!1,isMetroex:e.isMetroex??!1})):[]}catch(r){return Qs.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return Qs.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function dl(e,a){const t=a||Nr.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function cl(e,a){const t=a||Nr.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function ul(e,a){const t=a||Nr.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function ml(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||dl(e.idField),emailField:e.emailField||cl(e.idField),usernameField:e.usernameField||ul(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:dl(e),emailField:cl(e),usernameField:ul(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const pl=new Map;class hl{static async fetchQualiexUsers(e,a){const t=`${a}_${e}_all`,r=pl.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await ll.fetchUsers(e,a,"all");return pl.set(t,{users:n,timestamp:Date.now()}),n}static extractUserIds(e,a){const t=new Set;for(const r of e)for(const e of a){const a=r[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 r={...e};for(const n of a){const a=e[n.idField];if(!a)continue;const i=t.get(a);if(i){if(n.nameField){r[n.nameField]||(r[n.nameField]=i.userName||null)}if(n.emailField){r[n.emailField]||(r[n.emailField]=i.userEmail||null)}if(n.usernameField){r[n.usernameField]||(r[n.usernameField]=i.userName||null)}}}return r}static async enrichWithUserData(e,a){if(!Array.isArray(e)||0===e.length)return e;try{if(!Ys.areAllTokensValid())return e;const t=Ys.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=ml(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const o=await this.fetchQualiexUsers(r,n),s=this.indexUsers(o);return e.map(e=>this.enrichEntity(e,i,s))}catch(t){return Qs.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const fl=["responsible_name"],gl=e=>fl.includes(e);function vl(e,a,t){const r="string"==typeof e?{tableName:e,searchFields:a||[],schemaName:t||"common"}:{searchFields:e.searchFields||[],schemaName:e.schemaName||"common",...e},{tableName:n,searchFields:i,selectFields:o,schemaName:s,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Ys.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return rl().schema(s).from(n)},u=(e,a,t,r)=>{let n=c().select(o||"*",{count:"exact"});n=n.eq("is_removed",!1),Object.entries(r).forEach(([e,a])=>{void 0!==a&&""!==a&&(Array.isArray(a)?n=n.in(e,a):"object"==typeof a&&a&&"operator"in a?"not_null"===a.operator?n=n.not(e,"is",null):"is_null"===a.operator&&(n=n.is(e,null)):null!==a&&(n=n.eq(e,a)))}),n=((e,a)=>{if(a&&i.length>0){const t=i.map(e=>`${e}.ilike.%${a}%`).join(",");return e.or(t)}return e})(n,e);const s=a.includes(".");return s||gl(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:s}},m=async(e,a,t,n,i)=>{const o=ml(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),s=a.includes(".");if(gl(a)||s||o){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},o=await p.getAll(e);if(!o?.data?.length)return o;const d=await hl.enrichWithUserData(o.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=s?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",o=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?o:-o}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",o=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?o:-o}))(d,a,t);const u=((e,a=1,t=25)=>{const r=(a-1)*t,n=r+t;return{data:e.slice(r,n),pagination:{currentPage:a,totalPages:Math.ceil(e.length/t),totalItems:e.length,itemsPerPage:t,hasNextPage:n<e.length,hasPreviousPage:a>1}}})(c,n,i);return{data:u.data,currentPage:u.pagination.currentPage,totalPages:u.pagination.totalPages,totalItems:u.pagination.totalItems,itemsPerPage:u.pagination.itemsPerPage,hasNextPage:u.pagination.hasNextPage,hasPreviousPage:u.pagination.hasPreviousPage}}return await hl.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},p={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:o,limit:s,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...o}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:o}})(e),{query:p}=u(a,t,i,c),h=((e,a,t)=>{const r=(a-1)*t,n=r+t-1;return e.range(r,n)})(p,o,s),{data:f,error:g,count:v}=await h;if(g)throw new Error(`Error fetching ${n}: ${g.message}`);let b=((e,a,t,r)=>{const n=Math.ceil((a||0)/r);return{data:e,currentPage:t,totalPages:n,totalItems:a||0,itemsPerPage:r,hasNextPage:t<n,hasPreviousPage:t>1}})(f||[],v,o,s);if((e=>{if(!d||!l||0===e.length)return!1;const a=ml(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,o,s);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await c().select(o||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Ui(e),t=Object.entries(a).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),{data:r,error:i}=await c().insert(t).select().single();if(i)throw new Error(`Error creating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from create ${n} operation`);return r},async update(e,a){const t={...Ui(a),updated_at:(new Date).toISOString()},{data:r,error:i}=await c().update(t).eq("id",e).select().single();if(i)throw new Error(`Error updating ${n}: ${i.message}`);if(!r)throw new Error(`No data returned from update ${n} operation`);return r},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 ${n}: ${t.message}`)}};return p}var bl;const xl={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class yl{static async initialize(){try{if(Ys.checkProjectMismatch())return{...xl};if(!Ys.hasAllTokens()||!Ys.areAllTokensValid())return Ys.clearExpiredTokens(),{...xl};const e=Ys.getAccessToken(),a=Ys.getIdToken();Ys.clearManualLogout();const t=this.extractUserFromIdToken(a,e),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=Ys.extractTokenData(),o=i?.alias;let s=null;if(o&&r.some(e=>e.alias===o))s=o;else{const e=Ys.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);s=a?e:n||r[0]?.alias||null}if(!Ys.isSupabaseTokenValid()&&s&&await il.attemptRegeneration(),!Ys.isSupabaseTokenValid())return{...xl};let l=null;if(s){const e=Ys.getCompanyId(s),a=r.find(e=>e.alias===s);a&&(l={id:e||a.id,name:a.name,alias:a.alias})}const d=i?.placeId??null,c=i?.placeName??null;return{isAuthenticated:!0,isLoading:!1,user:t,alias:s,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{...xl}}}static async loginDev(){try{const e=rl(),{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 r=new URL("/callback",window.location.origin);return r.hash=`access_token=${a.access_token}&id_token=${a.id_token}&token_type=bearer`,window.location.href=r.toString(),!0}catch(e){return!1}}static loginProd(){const e="Lw==";Ys.setOAuthState(e);const a=Ys.generateOAuthNonce();Ys.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(pr.oauth.authUrl);r.searchParams.set("client_id",pr.oauth.clientId),r.searchParams.set("response_type",pr.oauth.responseType),r.searchParams.set("scope",pr.oauth.scope),r.searchParams.set("redirect_uri",t),r.searchParams.set("state",e),r.searchParams.set("nonce",a),r.searchParams.set("response_mode","fragment"),window.location.href=r.toString()}static async processCallback(){try{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),r=t("access_token"),n=t("id_token"),i=t("error");if(i)throw new Error(`Erro OAuth: ${i}`);if(r&&n){const e=Ys.getAccessToken();e!==r&&Ys.clearAll()}if(Ys.hasAllTokens()){return Ys.getValidSupabaseToken()||await il.attemptRegeneration(!0),!0}const o=r,s=n;if(!o||!s)throw new Error("Tokens não encontrados na URL de callback");Ys.setAccessToken(o),Ys.setIdToken(s),Ys.clearManualLogout();const l=this.extractAliasFromAccessToken(o);if(l)Ys.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(s);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Ys.setSelectedAlias(e[0].alias)}if(!await il.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return Ys.clearOAuthState(),Ys.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){Ys.setManualLogout(),Ys.clearAll(),localStorage.removeItem("auth_return_url"),sessionStorage.clear();try{if("caches"in window){const e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}}catch{}window.location.href="/login"}static decodeToken(e){return Os.parseJwtPayload(e)}static extractUserFromIdToken(e,a){const t=this.decodeToken(e);if(!t)return null;const r=a?this.decodeToken(a):null;return{id:t.subNewId,email:t.email,name:t.name,identifier:t.identifier,isSysAdmin:"1"===r?.admin}}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 r=a[e].split(";");if(r.length>=4)t.push({id:r.length>7?r[7].trim():"",alias:r[0].trim(),name:r[3].trim()});else{const[r,n]=a[e].split("|");r&&n&&t.push({id:"",alias:r.trim(),name:n.trim()})}}}),t}static extractAliasFromAccessToken(e){const a=this.decodeToken(e);return a?.default||null}}bl=yl,il.setLogoutCallback(()=>{bl.logout()});const Nl=e=>e?.placeId||null,wl=e=>e?.placeName||null,_l=d(void 0),Cl=({children:e})=>{const[t,r]=o({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=Xa()}catch{}const[i,d]=o(!1),c=u(0),p=l(e=>{r(a=>({...a,...e}))},[]),h=l(e=>{r(a=>({...a,isLoading:e}))},[]),f=l(()=>{r({user:null,companies:[],alias:null,isAuthenticated:!1,isLoading:!0,selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null})},[]),g=l(async e=>{if(e.alias===t.alias)return;const a=++c.current;try{const i=Ys.getAccessToken();if(!i)return;const o=await nl.generateToken(i,e.alias,void 0,!0);if(c.current!==a)return;if(!o)return;Ys.setSupabaseToken(o),Ys.setSelectedAlias(e.alias);const s=Ys.extractTokenData(),l=s?.alias||e.alias,d=s?.companyId||Ys.getCompanyId(e.alias),u={id:d||e.id,name:e.name,alias:l};let m=null,h=null;if(t.user?.id&&l&&d)try{const e=await ll.fetchActiveUsersMap(l,d);if(c.current!==a)return;const r=e.get(t.user.id);if(r){const e=(e=>({placeId:Nl(e),placeName:wl(e)}))(r);m=e.placeId,h=e.placeName}}catch(r){}if(c.current!==a)return;p({alias:l,selectedUnit:u,placeId:m,placeName:h,activePlaceId:m,activePlaceName:h}),n&&await n.clear()}catch(r){}},[p,n,t.user,t.alias]),v=l(async()=>{const e=await yl.processCallback();if(e){const e=await yl.initialize();e&&e.isAuthenticated&&(p({user:e.user,companies:e.companies,alias:e.alias,isAuthenticated:!0,isLoading:!1,selectedUnit:e.selectedUnit,userId:e.userId,userAlias:e.userAlias,placeId:e.placeId,placeName:e.placeName,activePlaceId:e.activePlaceId,activePlaceName:e.activePlaceName}),n&&n.invalidateQueries({queryKey:["permission"]}))}return e},[p,n]),b=l(async()=>{await yl.logout(),f(),n&&await n.clear()},[f,n]),x=l(e=>{d(e)},[]),y=l(()=>{},[]),N=l(()=>{n&&n.invalidateQueries()},[n]);m(()=>{if(!t.isAuthenticated)return;let e=!0;const a=setInterval(async()=>{if(e)if(Ys.areAllTokensValid()){if(!Ys.isSupabaseTokenValid())try{await il.attemptRegeneration()||e&&b()}catch(a){e&&b()}}else e&&b()},6e5);return()=>{e=!1,clearInterval(a)}},[t.isAuthenticated,b]),m(()=>{let e=!0;return(async()=>{try{if(await new Promise(e=>setTimeout(e,100)),!e)return;const a=await yl.initialize();if(!e)return;a&&a.isAuthenticated?p({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&&h(!1)}catch(a){e&&(ol.handleError(a),h(!1))}})(),()=>{e=!1}},[p,h,b]);const w=s(()=>({...t,logout:b,processCallback:v,switchUnit:g,availableUnits:t.companies,isSearchVisible:i,setSearchVisible:x,clearSearch:y,refreshData:N}),[t.user,t.companies,t.alias,t.isAuthenticated,t.isLoading,t.selectedUnit,t.userId,t.userAlias,t.placeId,t.placeName,t.activePlaceId,t.activePlaceName,b,v,g,i,x,y,N]);return a(_l.Provider,{value:w,children:e})},kl=()=>{const e=c(_l);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Sl({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:i}){const[d,c]=tt(),u=Xa(),{alias:m,userId:p,isAuthenticated:h}=kl(),{t:f}=Ga(),g=l(a=>{const t=`${e}_${a}`,r=d.get(t);return r||(d.get(a)||"")},[d,e]),v=g("search"),b=g("sortField")||hr.sorting.defaultField,x=g("sortDirection")||hr.sorting.defaultDirection,y=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(hr.pagination.defaultPageSize)),w=v,_=s(()=>({search:w,sortField:b,sortDirection:x,page:y,limit:N,...n}),[w,b,x,y,N,n]),k=l(()=>a.getAll(_),[a,_]),S=Ja({queryKey:[e,m,p,_],queryFn:k,enabled:!!m&&h});if(!S)throw new Error(`useCrud: Query initialization failed for "${t}". Ensure QueryClientProvider is configured in your app root.`);const A=Za({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(_r.success.created(t)),i?.()},onError:e=>{C.error(`${_r.error.create(t)}: ${e.message}`)}}),E=Za({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(_r.success.updated(t)),i?.()},onError:e=>{C.error(`${_r.error.update(t)}: ${e.message}`)}}),D=Za({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(_r.success.deleted(t))},onError:e=>{C.error(`${_r.error.delete(t)}: ${e.message}`)}}),P=l(a=>{const t={...Object.fromEntries(d)};Object.entries(a).forEach(([a,r])=>{const n=`${e}_${a}`;""===r||0===r?delete t[n]:t[n]=String(r)}),delete t.sortField,delete t.sortDirection,c(t)},[d,c,e]),I=l(e=>{P({search:e,page:1})},[P]),T=l(e=>{P({sortField:e,sortDirection:b===e&&"asc"===x?"desc":"asc",page:1})},[b,x,P]),R=l(e=>{P({page:e})},[P]),M=l(e=>{P({limit:e,page:1})},[P]),L=l(()=>{const a=Object.fromEntries(d),t=`${e}_`,r=Object.fromEntries(Object.entries(a).filter(([e])=>!e.startsWith(t)));c(r)},[c,d,e]),[z,F]=o([]),U=l(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),j=l(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=l(()=>{F([])},[]),B=s(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),$=Za({mutationFn:async e=>{await Promise.all(e.map(e=>a.delete(e)))},onSuccess:(a,r)=>{u.invalidateQueries({queryKey:[e]}),C.success(f("bulk_delete_success",`${r.length} ${t}(s) deletado(s) com sucesso`)),O()},onError:e=>{C.error(f("bulk_delete_error",`Erro ao deletar itens: ${e.message}`))}}),V=l((e,a)=>{const t=a?a(e):e;e.id?E.mutate({id:e.id,data:t}):A.mutate({...t,alias:m})},[m,A,E]);return{entities:S?.data?.data||[],pagination:{data:S?.data?.data||[],currentPage:S?.data?.currentPage||1,totalPages:S?.data?.totalPages||1,totalItems:S?.data?.totalItems||0,itemsPerPage:S?.data?.itemsPerPage||hr.pagination.defaultPageSize,hasNextPage:S?.data?.hasNextPage||!1,hasPreviousPage:S?.data?.hasPreviousPage||!1},isLoading:S?.isLoading??!0,isCreating:A?.isPending??!1,isUpdating:E?.isPending??!1,isDeleting:D?.isPending??!1,error:S?.error||null,searchTerm:v,sortField:b,sortDirection:x,currentPage:y,itemsPerPage:N,queryKey:e,createEntity:A.mutate,updateEntity:(e,a)=>E.mutate({id:e,data:a}),deleteEntity:D.mutate,save:V,handleSearch:I,handleSort:T,handlePageChange:R,handleItemsPerPageChange:M,clearFilters:L,refetch:S.refetch,selectedIds:z,selectItem:U,selectAll:j,clearSelection:O,isAllSelected:B,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Al(e){const a=vl({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,r)=>Sl({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function El(e){const[a,t]=o(()=>"undefined"!=typeof window&&window.matchMedia(e).matches);return m(()=>{const a=window.matchMedia(e);t(a.matches);const r=e=>{t(e.matches)};return a.addEventListener("change",r),()=>a.removeEventListener("change",r)},[e]),a}function Dl(e=768){return El(`(max-width: ${e-1}px)`)}const Pl=n.forwardRef(({className:e,...t},r)=>a("table",{ref:r,className:Fi("w-full caption-bottom text-[13px] table-fixed",e),...t}));Pl.displayName="Table";const Il=n.forwardRef(({className:e,...t},r)=>a("thead",{ref:r,className:Fi("[&_tr]:border-b sticky top-0 z-[1] bg-background",e),...t}));Il.displayName="TableHeader";const Tl=n.forwardRef(({className:e,...t},r)=>a("tbody",{ref:r,className:Fi("[&_tr:last-child]:border-0",e),...t}));Tl.displayName="TableBody";const Rl=n.forwardRef(({className:e,...t},r)=>a("tfoot",{ref:r,className:Fi("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));Rl.displayName="TableFooter";const Ml=n.forwardRef(({className:e,...t},r)=>a("tr",{ref:r,className:Fi("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",e),...t}));Ml.displayName="TableRow";const Ll=n.forwardRef(({className:e,...t},r)=>a("th",{ref:r,className:Fi("h-9 px-4 py-2 text-left align-middle font-medium text-muted-foreground bg-background border-b [&:has([role=checkbox])]:pr-0",e),...t}));Ll.displayName="TableHead";const zl=n.forwardRef(({className:e,...t},r)=>a("td",{ref:r,className:Fi("px-4 py-2 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",e),...t}));zl.displayName="TableCell";const Fl=n.forwardRef(({className:e,...t},r)=>a("caption",{ref:r,className:Fi("mt-4 text-sm text-muted-foreground",e),...t}));function Ul({rows:e=5,columns:r=4}){return a("div",{className:"w-full",children:t("div",{className:"rounded-md border",children:[a("div",{className:"border-b bg-muted/50 px-4 py-3",children:a("div",{className:"flex space-x-4",children:Array.from({length:r}).map((e,t)=>a(Ps,{className:"h-4 w-24"},t))})}),a("div",{children:Array.from({length:e}).map((e,t)=>a("div",{className:"border-b px-4 py-3 last:border-0",children:a("div",{className:"flex space-x-4",children:Array.from({length:r}).map((e,t)=>a(Ps,{className:"h-4 w-20"},t))})},t))})]})})}function jl({count:e=3}){return a("div",{className:"space-y-4",children:Array.from({length:e}).map((e,r)=>t(Gi,{children:[t(Ki,{children:[a(Ps,{className:"h-4 w-3/4"}),a(Ps,{className:"h-3 w-1/2"})]}),a(Xi,{children:t("div",{className:"space-y-2",children:[a(Ps,{className:"h-3 w-full"}),a(Ps,{className:"h-3 w-2/3"})]})})]},r))})}function Ol({fields:e=4}){return t("div",{className:"space-y-4",children:[Array.from({length:e}).map((e,r)=>t("div",{className:"space-y-2",children:[a(Ps,{className:"h-4 w-24"}),a(Ps,{className:"h-10 w-full"})]},r)),t("div",{className:"flex justify-end space-x-2 pt-4",children:[a(Ps,{className:"h-10 w-20"}),a(Ps,{className:"h-10 w-20"})]})]})}function Bl(){return t("div",{className:"flex items-center justify-between p-4 border-b",children:[t("div",{className:"flex items-center space-x-3",children:[a(Ps,{className:"h-8 w-8 rounded-full"}),a(Ps,{className:"h-6 w-32"})]}),t("div",{className:"flex items-center space-x-2",children:[a(Ps,{className:"h-8 w-8"}),a(Ps,{className:"h-8 w-24"})]})]})}function $l(){return a("div",{className:"w-64 border-r bg-muted/10",children:t("div",{className:"p-4",children:[a(Ps,{className:"h-8 w-32 mb-6"}),a("div",{className:"space-y-2",children:Array.from({length:6}).map((e,r)=>t("div",{className:"flex items-center space-x-3 p-2",children:[a(Ps,{className:"h-4 w-4"}),a(Ps,{className:"h-4 w-20"})]},r))})]})})}Fl.displayName="TableCaption";const Vl={default:$,search:B,error:O};function ql({icon:e,title:r,description:n,action:i,className:o,variant:s="default"}){const{t:l}=Ga(),d=!!e,c=Vl[s];return t("div",{className:Fi("flex flex-col items-center justify-center py-12 px-4 text-center",o),children:[a("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-muted mb-4",children:d?e:a(c,{className:"h-8 w-8 text-muted-foreground"})}),a("h3",{className:"text-lg font-semibold mb-2",children:r}),n&&a("p",{className:"text-muted-foreground mb-6 max-w-sm",children:n}),i&&a($i,{onClick:i.onClick,variant:"outline",children:i.label})]})}function Wl({children:e,className:r}){const i=n.useRef(null),[o,s]=n.useState(!1);n.useEffect(()=>{const e=()=>{const e=i.current;e&&s(e.scrollWidth>e.clientWidth)};e();const a=new ResizeObserver(e);return i.current&&a.observe(i.current),()=>a.disconnect()},[e]);const l=a("div",{ref:i,className:`truncate w-full max-w-full ${r||""}`,children:e});return o?a(ps,{delayDuration:300,children:t(hs,{children:[a(fs,{asChild:!0,children:l}),a(gs,{side:"top",className:"max-w-[400px] break-words",children:e})]})}):l}const Hl=n.forwardRef(({direction:e,onMouseDown:t,isDragging:r,className:n},i)=>{const o="horizontal"===e;return a("div",{ref:i,onMouseDown:t,className:Fi("absolute z-20 select-none touch-none","transition-colors duration-150",o&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!o&&["bottom-0 left-0 w-full h-2 -mb-1","cursor-row-resize","hover:bg-primary/20","group flex items-center justify-center"],r&&"bg-primary/30",n),children:a("div",{className:Fi("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",o?"h-6 w-0.5":"w-6 h-0.5")})})});Hl.displayName="TableResizeHandle";const Gl=lt.Root,Kl=lt.Trigger,Yl=lt.Group,Ql=lt.Portal,Xl=lt.Sub,Jl=lt.RadioGroup,Zl=n.forwardRef(({className:e,inset:r,children:n,...i},o)=>t(lt.SubTrigger,{ref:o,className:Fi("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",e),...i,children:[n,a(U,{className:"ml-auto h-4 w-4"})]}));Zl.displayName=lt.SubTrigger.displayName;const ed=n.forwardRef(({className:e,...t},r)=>a(lt.SubContent,{ref:r,className:Fi("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));ed.displayName=lt.SubContent.displayName;const ad=n.forwardRef(({className:e,...t},r)=>a(lt.Portal,{children:a(lt.Content,{ref:r,className:Fi("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t})}));ad.displayName=lt.Content.displayName;const td=n.forwardRef(({className:e,inset:t,...r},n)=>a(lt.Item,{ref:n,className:Fi("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));td.displayName=lt.Item.displayName;const rd=n.forwardRef(({className:e,children:r,checked:n,...i},o)=>t(lt.CheckboxItem,{ref:o,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...i,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(lt.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),r]}));rd.displayName=lt.CheckboxItem.displayName;const nd=n.forwardRef(({className:e,children:r,...n},i)=>t(lt.RadioItem,{ref:i,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(lt.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));nd.displayName=lt.RadioItem.displayName;const id=n.forwardRef(({className:e,inset:t,...r},n)=>a(lt.Label,{ref:n,className:Fi("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",e),...r}));id.displayName=lt.Label.displayName;const od=n.forwardRef(({className:e,...t},r)=>a(lt.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-border",e),...t}));od.displayName=lt.Separator.displayName;const sd=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});sd.displayName="ContextMenuShortcut";const ld=({onEdit:e,onDelete:n,onToggleStatus:i,isActive:o=!0,canDelete:s=!0,customActions:l=[],renderAs:d})=>{const{t:c}=Ga(),u=[];if(e){const a={icon:V,label:c("edit"),onClick:e};u.push(a)}if(l.forEach(e=>{u.push(e)}),i){const e={icon:o?q:W,label:o?"Inativar":"Ativar",onClick:i};u.push(e)}if(s&&n){const e={icon:H,label:c("ap_delete"),onClick:n,destructive:!0};u.push(e)}const m="dropdown"===d?ss:td;return a(r,{children:u.map((e,r)=>t(m,{onClick:e.onClick,className:Fi("whitespace-normal cursor-pointer",e.destructive&&"text-destructive focus:text-destructive"),children:[a(e.icon,{className:"mr-2 h-4 w-4 flex-shrink-0"}),e.label]},r))})},dd=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:a(A,{size:12})})}),a(os,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:a(ld,{onEdit:e?a=>{a?.stopPropagation(),e?.()}:void 0,onDelete:r?e=>{e?.stopPropagation(),r?.()}:void 0,onToggleStatus:i?e=>{e?.stopPropagation(),i?.()}:void 0,isActive:o,canDelete:n&&!!r,customActions:s,renderAs:"dropdown"})})]}),cd=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:o=!0,customActions:s=[]})=>{const{t:l}=Ga();return a(ps,{delayDuration:200,children:t("div",{className:"flex items-center justify-end gap-0.5",children:[e&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e()},children:a(G,{size:14})})}),a(gs,{children:l("edit")})]}),s.map((e,r)=>{const n=e.icon;return t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e.onClick()},children:a(n,{size:14})})}),a(gs,{children:e.label})]},r)}),i&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:a(o?K:Y,{size:14})})}),a(gs,{children:o?"Inativar":"Ativar"})]}),r&&n&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:Fi("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:a(H,{size:14})})}),a(gs,{children:l("ap_delete")})]})]})})},ud=150;function md({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=o(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??ud,e),{});if(a){const e=localStorage.getItem(a);if(e)try{return JSON.parse(e)}catch{}}return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??ud,e),{})}),[s,d]=o(!1),[c,p]=o(null),h=u(0),f=u(0),g=l((e,a)=>{r&&(a.preventDefault(),a.stopPropagation(),d(!0),p(e),h.current=a.clientX,f.current=n[e]??ud)},[r,n]);m(()=>{if(!s||!c)return;const r=e.find(e=>e.key===c),n=r?.minWidth??60,o=r?.maxWidth??500,l=e=>{const a=e.clientX-h.current,r=Math.max(n,Math.min(o,f.current+a));i(e=>{const a={...e,[c]:r};return t?.(a),a})},u=()=>{d(!1),p(null),a&&i(e=>(localStorage.setItem(a,JSON.stringify(e)),e))};return document.addEventListener("mousemove",l),document.addEventListener("mouseup",u),()=>{document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",u)}},[s,c,e,a,t]),m(()=>(s?(document.body.style.cursor="col-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[s]);const v=l(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??ud,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:s,activeColumn:c,handleMouseDown:g,resetWidths:v}}const pd=v("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"}}),hd=n.forwardRef(({className:e,variant:t,size:r,...n},i)=>a(ct.Root,{ref:i,className:Fi(pd({variant:t,size:r,className:e})),...n}));hd.displayName=ct.Root.displayName;const fd=n.createContext({size:"default",variant:"default"}),gd=n.forwardRef(({className:e,variant:t,size:r,children:n,...i},o)=>a(dt.Root,{ref:o,className:Fi("flex items-center justify-center gap-1",e),...i,children:a(fd.Provider,{value:{variant:t,size:r},children:n})}));gd.displayName=dt.Root.displayName;const vd=n.forwardRef(({className:e,children:t,variant:r,size:i,...o},s)=>{const l=n.useContext(fd);return a(dt.Item,{ref:s,className:Fi(pd({variant:l.variant||r,size:l.size||i}),e),...o,children:t})});vd.displayName=dt.Item.displayName;const bd=p(function({onNew:e,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:o="",onSearchChange:s,searchPlaceholder:l,showBulkActions:d=!1,selectedCount:c=0,bulkActions:u=[],onBulkDelete:m,onClearSelection:p,customActions:h=[],filters:f,viewMode:g,onViewModeChange:v,showViewToggle:b=!1,availableViewModes:x=["table","list","grid"],rightSlot:y,className:N}){const{t:w}=Ga(),_=c>0,C=e&&n||h.length>0,k=f||b||y,S=i&&s;return C||S||k||d&&_?t("div",{className:Fi("flex-shrink-0 flex items-center px-4 py-1.5 bg-muted/50 border-b gap-4",N),children:[t("div",{className:"flex items-center gap-2 shrink-0",children:[e&&n&&t($i,{onClick:e,children:[a(Q,{size:16,className:"mr-2"}),r||"Novo"]}),h.map((e,r)=>{const n=e.icon;return t($i,{onClick:e.action,variant:e.variant||"outline",disabled:e.disabled,title:e.disabled?e.disabledReason:void 0,children:[n&&a(n,{size:16,className:"mr-2"}),e.label]},r)})]}),d&&_&&t("div",{className:"flex items-center gap-1 shrink-0 border-l pl-4",children:[a(Go,{variant:"secondary",className:"mr-1 tabular-nums",children:c}),t(ps,{delayDuration:200,children:[u.length>0?u.map((e,r)=>{const n=e.icon,i=e.disabled;return t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:Fi("h-8 w-8","destructive"===e.variant&&"text-destructive hover:text-destructive hover:bg-destructive/10"),disabled:i,onClick:()=>e.action([]),children:n?a(n,{size:16}):a("span",{className:"text-xs",children:e.label[0]})})}),a(gs,{children:e.label})]},r)}):t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:a(H,{size:16})})}),a(gs,{children:w("ap_delete")})]}),t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:a(E,{size:16})})}),a(gs,{children:w("clear_selection")})]})]})]}),S&&a("div",{className:"flex-1 flex justify-center max-w-md mx-auto",children:t("div",{className:"relative w-full",children:[a(B,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{type:"text",placeholder:l||"Pesquisar",value:o,onChange:e=>s?.(e.target.value),className:"pl-9 w-full"})]})}),k&&t("div",{className:"flex items-center gap-2 shrink-0 ml-auto",children:[f,b&&g&&v&&a(gd,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:x.map(e=>{const t=(e=>{switch(e){case"table":return Z;case"list":return J;case"grid":return X}})(e);return a(vd,{value:e,"aria-label":"Visualizar como "+("table"===e?"tabela":"list"===e?"lista":"grade"),children:a(t,{className:"h-4 w-4"})},e)})}),y]})]}):null}),xd=p(({checked:e,onCheckedChange:t})=>a(qo,{checked:e,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function yd(e){try{const a=localStorage.getItem(e);if(!a)return null;const t=JSON.parse(a);let r=t.groupByColumns||[];return 0===r.length&&t.groupByColumn&&(r=[t.groupByColumn]),{hiddenColumns:new Set(t.hiddenColumns||[]),columnOrder:t.columnOrder||[],groupByColumns:r}}catch{return null}}function Nd({columns:e,storageKey:a,enabled:t=!0,defaultHiddenColumns:r}){const n=s(()=>e.map(e=>String(e.key)),[e]),i=s(()=>new Set(r??[]),[r]),[d,c]=o(()=>{if(!t)return i;if(!a)return i;const e=yd(a);return e?.hiddenColumns??i}),[u,p]=o(()=>{if(!t||!a)return n;const e=yd(a)?.columnOrder;return e&&e.length>0?e:n}),[h,f]=o(()=>t&&a?yd(a)?.groupByColumns??[]:[]),[g,v]=o(new Set);m(()=>{t&&a&&function(e,a){try{localStorage.setItem(e,JSON.stringify({hiddenColumns:Array.from(a.hiddenColumns),columnOrder:a.columnOrder,groupByColumns:a.groupByColumns}))}catch{}}(a,{hiddenColumns:d,columnOrder:u,groupByColumns:h})},[d,u,h,a,t]),m(()=>{const a=new Set(e.map(e=>String(e.key))),t=new Set(u),r=[...a].filter(e=>!t.has(e));r.length>0&&p(e=>[...e.filter(e=>a.has(e)),...r])},[e]);const b=l(e=>d.has(e),[d]),x=l(e=>{c(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),y=l(()=>{c(new Set)},[]),N=l(()=>{if(c(i),p(n),f([]),v(new Set),a)try{localStorage.removeItem(a)}catch{}},[n,i,a]),w=l((e,a)=>{p(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r})},[]),_=l(e=>{v(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),C=l(e=>{f(e),v(new Set)},[]),k=l(e=>{f(a=>a.includes(e)?a:[...a,e])},[]),S=l(e=>{f(a=>a.filter(a=>a!==e)),v(a=>{const t=new Set;for(const r of a)r.includes(`${e}:`)||t.add(r);return t})},[]),A=l((e,a)=>{f(t=>{const r=[...t],[n]=r.splice(e,1);return r.splice(a,0,n),r}),v(new Set)},[]),E=h[0]??null,D=l(e=>{f(e?[e]:[]),v(new Set)},[]),P=s(()=>{if(!t)return e;const a=new Map(e.map(e=>[String(e.key),e]));return u.filter(e=>!d.has(e)&&a.has(e)).map(e=>a.get(e))},[e,u,d,t]),I=l(e=>{if(0===h.length)return[{groupKey:"__all__",groupValue:"",items:e,count:e.length,level:0}];return function e(a,t,r,n){if(0===t.length)return[{groupKey:n||"__leaf__",groupValue:"",items:a,count:a.length,level:r}];const[i,...o]=t,s=new Map;for(const l of a){const e=String(l[i]??"(vazio)");s.has(e)||s.set(e,[]),s.get(e).push(l)}return Array.from(s.entries()).map(([a,t])=>{const s=n?`${n}|${i}:${a}`:`${i}:${a}`,l=o.length>0?e(t,o,r+1,s):void 0;return{groupKey:s,groupValue:a,items:t,count:t.length,level:r,children:l}})}(e,h,0,"")},[h]);return{visibleColumns:P,allColumns:e,isColumnHidden:b,toggleColumn:x,showAllColumns:y,resetColumns:N,columnOrder:u,reorderColumns:w,groupByColumn:E,setGroupByColumn:D,groupByColumns:h,setGroupByColumns:C,addGroupByColumn:k,removeGroupByColumn:S,reorderGroupByColumns:A,getGroupedData:I,collapsedGroups:g,toggleGroupCollapse:_}}function wd({enabled:e=!1,onReorder:a}){const[t,r]=o(null),[n,i]=o(null),d=l(()=>{r(null),i(null)},[]),c=l((n,o)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),o&&a.dataTransfer.setData("application/column-key",o))},onDragOver:a=>{e&&null!==t&&(a.preventDefault(),a.dataTransfer.dropEffect="move")},onDragEnter:a=>{e&&null!==t&&(a.preventDefault(),i(n))},onDrop:r=>{r.preventDefault(),e&&null!==t&&t!==n?(a(t,n),d()):d()},onDragEnd:()=>{d()}}),[e,t,a,d]);return s(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:c}),[t,n,c])}function _d({columns:e,columnOrder:r,isColumnHidden:n,toggleColumn:i,showAllColumns:s,reorderColumns:l,groupByColumn:d,setGroupByColumn:c,groupByColumns:m=[],addGroupByColumn:p,removeGroupByColumn:h,resetColumns:f}){const{t:g}=Ga(),[v,b]=o(null),[x,y]=o(null),N=u(null),w=new Map(e.map(e=>[String(e.key),e])),_=r.filter(e=>w.has(e)).map(e=>w.get(e)),C=()=>{N.current=null,b(null),y(null)};_.some(e=>n(String(e.key)));const k=_.every(e=>!n(String(e.key)));return t(bs,{children:[a(xs,{asChild:!0,children:a($i,{variant:"outline",size:"icon",className:"h-8 w-8",children:a(ee,{size:16})})}),t(ys,{className:"w-[260px] p-0",align:"end",children:[a("div",{className:"px-3 py-2 border-b",children:a("span",{className:"text-sm font-medium",children:"Colunas"})}),a("div",{className:"max-h-[300px] overflow-auto py-1",children:a(ps,{delayDuration:300,children:_.map((e,r)=>{const o=String(e.key),s=n(o),u=!1!==e.hideable,f=!0===e.groupable,w=m.includes(o)||d===o;return t("div",{draggable:!0,onDragStart:()=>(e=>{N.current=e,b(e)})(r),onDragOver:e=>((e,a)=>{e.preventDefault(),y(a)})(e,r),onDrop:()=>(e=>{null!==N.current&&N.current!==e&&l(N.current,e),N.current=null,b(null),y(null)})(r),onDragEnd:C,className:Fi("flex items-center gap-2 px-3 py-1.5 text-sm cursor-grab active:cursor-grabbing","hover:bg-muted/50 transition-colors",v===r&&"opacity-50",x===r&&"border-t-2 border-primary"),children:[a(ae,{size:14,className:"text-muted-foreground shrink-0"}),a(qo,{checked:!s,onCheckedChange:()=>u&&i(o),disabled:!u,className:"shrink-0"}),a("span",{className:Fi("flex-1 truncate",s&&"text-muted-foreground"),children:e.header}),f&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:Fi("h-6 w-6 shrink-0",w&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),w?h?h(o):c?.(null):p?p(o):c?.(o)},children:a(te,{size:14})})}),a(gs,{children:g(w?"remove_grouping":"group_by_column")})]})]},o)})})}),t("div",{className:"border-t px-3 py-2 space-y-1",children:[a($i,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:k?()=>_.filter(e=>!1!==e.hideable).forEach(e=>i(String(e.key))):s,children:g(k?"deselect_all":"select_all_columns")}),f&&a($i,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Cd({columns:e,groupByColumns:r,addGroupByColumn:n,removeGroupByColumn:s,reorderGroupByColumns:l}){const[d,c]=o(!1),[u,m]=o(null),[p,h]=o(null),f=new Map(e.map(e=>[String(e.key),e])),g=()=>{m(null),h(null)},v=r.length>0;return t("div",{onDragOver:e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",c(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||c(!1)},onDrop:e=>{e.preventDefault(),c(!1);if(Array.from(e.dataTransfer.types).includes("application/group-chip-index"))return;const a=e.dataTransfer.getData("application/column-key");if(a&&!r.includes(a)){const e=f.get(a);e&&e.groupable&&n(a)}},className:Fi("flex items-center gap-2 px-4 py-2 min-h-[40px] border-b transition-colors",d&&"bg-primary/5 border-primary/30",!v&&"text-muted-foreground"),children:[a(te,{size:14,className:"shrink-0 text-muted-foreground"}),a("div",{className:"flex-1 flex items-center gap-1.5 flex-wrap",children:v?r.map((e,r)=>{const n=f.get(e);if(!n)return null;const o=u===r,d=p===r&&u!==r;return t(i.Fragment,{children:[r>0&&a("span",{className:"text-xs text-muted-foreground",children:"›"}),t(Go,{variant:"secondary",className:Fi("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",o&&"opacity-50",d&&"ring-2 ring-primary"),draggable:!0,onDragStart:e=>((e,a)=>{e.stopPropagation(),e.dataTransfer.setData("application/group-chip-index",String(a)),e.dataTransfer.effectAllowed="move",m(a)})(e,r),onDragOver:e=>((e,a)=>{e.preventDefault(),e.stopPropagation(),h(a)})(e,r),onDrop:e=>((e,a)=>{e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("application/group-chip-index");if(""!==t){const e=parseInt(t,10);isNaN(e)||e===a||l(e,a)}m(null),h(null)})(e,r),onDragEnd:g,children:[n.header,a("button",{onClick:a=>{a.stopPropagation(),s(e)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:a(E,{size:12})})]})]},e)}):a("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const kd=({manager:r,columns:n,onEdit:d,onView:c,onToggleStatus:u,onDelete:p,renderActions:h,customRowActions:f,enableBulkActions:g=!1,rowActionsVariant:v="dropdown",onNew:b,newButtonLabel:x,showNewButton:y=!0,customActions:N=[],hideActionBar:w,showActionBar:_=!0,showSearch:C=!1,searchValue:k,onSearchChange:S,searchPlaceholder:A,bulkActions:E=[],onBulkDelete:P,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M=!1,enableColumnResize:L=!0,resizeStorageKey:z,enableColumnManager:F=!0,columnManagerStorageKey:j,defaultHiddenColumns:O,enableGrouping:B=!1,enableExpandableRows:$=!1,renderExpandedContent:V,expandedRowIds:q,onToggleExpand:W,defaultExpandAll:H=!1,hideActionsColumn:G=!1})=>{const{t:K}=Ga(),{setSearchVisible:Y}=kl(),Q=Dl(),[X,J]=o(()=>H&&$?new Set(r.entities.map(e=>e.id)):new Set),Z=void 0!==q,ee=Z?new Set(q):X,ae=l(e=>{Z&&W?W(e):J(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[Z,W]),te=void 0!==w?!w:_;m(()=>{if(!C)return Y(!0),()=>Y(!1)},[Y,C]);const ie=Nd({columns:n,storageKey:j,enabled:F,defaultHiddenColumns:O}),oe=wd({enabled:F,onReorder:ie.reorderColumns}),se=F?ie.visibleColumns:n,{columnWidths:le,isDragging:de,activeColumn:ce,handleMouseDown:ue}=md({columns:se.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:500,defaultWidth:e.width??e.minWidth??150})),storageKey:z?`${z}-columns`:void 0,enabled:L}),me=s(()=>(()=>{if(L){const e=se.map(e=>le[String(e.key)]??e.width??e.minWidth??150),a=e.reduce((e,a)=>e+a,0);return se.map((t,r)=>({...t,calculatedWidth:e[r],style:{width:e[r]/a*100+"%"}}))}let e=0;const a=se.map(a=>{if(a.width)return e+=a.width,{...a,calculatedWidth:a.width,isFixed:!0};{const t=a.minWidth||120,r=a.weight||1;return e+=t,{...a,calculatedWidth:t,weight:r,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`}})})(),[se,L,le]),pe=b||N.length>0||C||g||I||M||F,he=te&&pe,fe=P||(()=>{r.bulkDelete?.(r.selectedIds)}),ge=e=>a(zl,{className:"text-center",children:h?h(e):"inline"===v?a("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:a(cd,{onEdit:d?()=>d(e):void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,customActions:f?f(e):[]})}):a(dd,{onEdit:d?()=>d(e):void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,customActions:f?f(e):[]})}),ve=e=>a(ad,{className:"w-[160px]",children:a(ld,{onEdit:d?()=>d(e):void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,canDelete:!!p,customActions:f?f(e):[],renderAs:"context"})}),be=F?a(_d,{columns:n,columnOrder:ie.columnOrder,isColumnHidden:ie.isColumnHidden,toggleColumn:ie.toggleColumn,showAllColumns:ie.showAllColumns,resetColumns:ie.resetColumns,reorderColumns:ie.reorderColumns,groupByColumn:B?ie.groupByColumn:void 0,setGroupByColumn:B?ie.setGroupByColumn:void 0,groupByColumns:B?ie.groupByColumns:void 0,addGroupByColumn:B?ie.addGroupByColumn:void 0,removeGroupByColumn:B?ie.removeGroupByColumn:void 0}):void 0;if(Q)return r.isLoading?a(jl,{count:3}):0===r.entities.length?a(ql,{title:e.t("no_items_found_empty"),description:e.t("no_data_to_display"),variant:"search"}):t("div",{className:"flex flex-col h-full",children:[he&&a(bd,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:E,onBulkDelete:fe,onClearSelection:r.clearSelection,customActions:N,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M}),a("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:r.entities.map(e=>t(Gl,{children:[a(Kl,{asChild:!0,children:a(Gi,{className:Fi("overflow-hidden cursor-pointer hover:bg-muted/50",g&&r.selectedIds.includes(e.id)&&"bg-muted"),onClick:a=>{a.stopPropagation(),g?r.selectItem(e.id):d?.(e)},children:a(Xi,{className:"p-4",children:t("div",{className:"flex items-start gap-3",children:[g&&a("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:a(xd,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),t("div",{className:"flex-1",children:[se.map(r=>t("div",{className:"flex justify-between items-start mb-2 last:mb-0",children:[t("span",{className:"text-sm font-medium text-muted-foreground min-w-0 mr-2",children:[r.header,":"]}),a("div",{className:"text-sm text-foreground text-right min-w-0 flex-1",children:r.render?r.render(e):String(e[r.key]??"")})]},String(r.key))),(d||c||h)&&a("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:h?h(e):a(dd,{onEdit:d?()=>{d(e)}:void 0,onDelete:p?()=>p(e):void 0,onToggleStatus:u?()=>u(e):void 0,isActive:e.is_actived,customActions:f?f(e):[]})})]})]})})})}),ve(e)]},e.id))})]});const xe=B&&ie.groupByColumns.length>0?ie.getGroupedData(r.entities):null,ye=null!==xe,Ne=($?1:0)+(g?1:0)+se.length+(G?0:1),we=e=>{const n=$&&ee.has(e.id);return t(i.Fragment,{children:[t(Gl,{children:[a(Kl,{asChild:!0,children:t(Ml,{className:Fi("cursor-pointer hover:bg-muted/50 relative",("inline"===v||G)&&"group",g&&r.selectedIds.includes(e.id)&&"bg-muted"),onClick:a=>{a.stopPropagation(),g?r.selectItem(e.id):d?.(e)},children:[$&&a(zl,{className:"w-[40px] px-2",children:a("button",{onClick:a=>{a.stopPropagation(),ae(e.id)},className:"p-1 rounded-sm hover:bg-muted transition-colors","aria-label":K(n?"collapse_row":"expand_row"),children:a(n?D:U,{size:16,className:"text-muted-foreground"})})}),g&&a(zl,{onClick:e=>e.stopPropagation(),children:a(xd,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),se.map(t=>a(zl,{className:t.className,children:a(Wl,{children:t.render?t.render(e):String(e[t.key]??"")})},String(t.key))),!G&&ge(e)]})}),ve(e)]}),n&&V&&a(Ml,{className:"bg-muted/30 hover:bg-muted/30",children:a(zl,{colSpan:Ne,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:V(e)})})})]},e.id)},_e=(e,r)=>{const{t:n}=Ga();return e.map(e=>{const n=ie.collapsedGroups.has(e.groupKey),o=16*e.level,s=Math.max(30,70-15*e.level);return t(i.Fragment,{children:[a(Ml,{className:Fi("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${s}%)`},onClick:()=>ie.toggleGroupCollapse(e.groupKey),children:a(zl,{colSpan:r,className:"py-2 px-4",children:t("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${o}px`},children:[a(n?U:D,{size:16}),a("span",{children:e.groupValue}),t("span",{className:"text-muted-foreground font-normal",children:["(",e.count,")"]})]})})}),!n&&(e.children?_e(e.children,r):e.items.map(we))]},e.groupKey)})};return t("div",{className:"flex flex-col h-full",children:[he&&a(bd,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:E,onBulkDelete:fe,onClearSelection:r.clearSelection,customActions:N,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M}),r.isLoading?a(Ul,{rows:5,columns:se.length}):t("div",{className:"flex flex-col h-full overflow-hidden",children:[B&&a(Cd,{columns:n,groupByColumns:ie.groupByColumns,addGroupByColumn:ie.addGroupByColumn,removeGroupByColumn:ie.removeGroupByColumn,reorderGroupByColumns:ie.reorderGroupByColumns}),a("div",{className:"flex-1 overflow-auto",children:t(Pl,{className:"table-fixed w-full",children:[t("colgroup",{children:[$&&a("col",{style:{width:"40px"}}),g&&a("col",{style:{width:"50px"}}),me.map((e,t)=>a("col",{style:e.style},t)),!G&&a("col",{style:{width:"inline"===v?"auto":"50px",minWidth:"50px"}})]}),a(Il,{children:t(Ml,{children:[$&&a(Ll,{className:"w-[40px]"}),g&&a(Ll,{className:"w-[50px]",children:a(xd,{checked:r.isAllSelected,onCheckedChange:r.selectAll})}),se.map((e,n)=>{const i=L&&!1!==e.resizable,o=ce===String(e.key),s=F?oe.getDragProps(n,String(e.key)):{},l=oe.dragFromIndex===n,d=oe.dragOverIndex===n&&oe.dragFromIndex!==n;return t(Ll,{className:Fi(e.className,!1!==e.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",F&&oe.isDragging&&"cursor-grabbing",l&&"opacity-50",d&&"border-l-2 border-primary"),onClick:!1!==e.sortable?()=>r.handleSort(String(e.key)):void 0,...s,children:[t("div",{className:"flex items-center "+(e.className?.includes("text-center")?"justify-center":""),children:[e.header,!1!==e.sortable&&(c=String(e.key),r.sortField!==c?null:"asc"===r.sortDirection?a(re,{size:14,className:"ml-1"}):a(ne,{size:14,className:"ml-1"}))]}),i&&a(Hl,{direction:"horizontal",onMouseDown:a=>ue(String(e.key),a),isDragging:o})]},String(e.key));var c}),!G&&a(Ll,{className:"w-[50px] text-center",children:be||e.t("actions")})]})}),a(Tl,{children:0===r.entities.length?a(Ml,{children:a(zl,{colSpan:Ne,className:"h-32",children:a(ql,{title:e.t("no_items_found_empty"),description:"Não há dados para exibir no momento.",variant:"search"})})}):ye?_e(xe,Ne):r.entities.map(we)})]})})]})]})};function Sd(e,a,t,r){const[n,i]=o({}),[l,d]=o({}),c=s(()=>e,[e]),u=e=>e instanceof Date&&!isNaN(e.getTime()),p=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{}}},h=(e,a)=>{if(e.computedValue&&"function"==typeof e.computedValue)try{return e.computedValue(a)}catch(t){return p(e)}},f=(e,a,t)=>{if(e.required&&(""===a||null==a||Array.isArray(a)&&0===a.length))return`${e.label} é obrigatório`;if(e.validation){let n;if("function"==typeof e.validation?n=e.validation:e.validation.custom&&"function"==typeof e.validation.custom&&(n=e.validation.custom),n)try{const e=n(a,t);if(e)return e}catch(r){}}};m(()=>{if(!r)return;const e=a=>{const t=[];return a.forEach(a=>{t.push(a),a.fields&&t.push(...e(a.fields))}),t},n=e(c),o={};n.forEach(e=>{let t;if(a&&void 0!==a[e.name]){if(t=a[e.name],null==t&&(t=""),"date"===e.type&&t)if("string"==typeof t){const e=new Date(t);u(e)&&(t=e.toISOString().split("T")[0])}else u(t)&&(t=t.toISOString().split("T")[0])}else t=p(e);o[e.name]=t}),n.forEach(e=>{const a=h(e,o);void 0!==a&&(o[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(o[e]=a[e])}),i(o),d({}),t&&t(o)},[c,a,t,r]);const g=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...g(e.fields))}),a},v=()=>{const e=g(c),a={};return e.forEach(e=>{const t=f(e,n[e.name],n);t&&(a[e.name]=t)}),d(a),0===Object.keys(a).length};return{formData:n,errors:l,updateField:(e,a)=>{i(r=>{const n={...r,[e]:a},i=((e,a)=>{let t={...a};const r=e=>{const a=[];return e.forEach(e=>{a.push(e),e.fields&&a.push(...r(e.fields))}),a};return r(c).filter(a=>a.dependsOn===e).forEach(e=>{const a=h(e,t);void 0!==a&&(t={...t,[e.name]:a})}),t})(e,n);return t&&t(i),i}),l[e]&&d(a=>{const t={...a};return delete t[e],t});const r=g(c).find(a=>a.name===e);if(r){const t=f(r,a,n);t&&d(a=>({...a,[e]:t}))}},validateForm:v,handleSubmit:e=>a=>{a&&(a.preventDefault(),a.stopPropagation()),v()&&e(n)}}}const Ad=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Ed=({value:e="#3b82f6",onChange:r,label:n,customColorLabel:i,presetColorsLabel:o})=>{const{t:s}=Ga(),l=i??s("custom_color"),d=o??s("preset_colors");return t("div",{className:"space-y-2",children:[n&&a(Hi,{children:n}),t(bs,{children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[a("div",{className:"h-4 w-4 rounded border mr-2",style:{backgroundColor:e}}),e]})}),a(ys,{className:"w-64",children:t("div",{className:"space-y-3",children:[t("div",{children:[a(Hi,{htmlFor:"color-input",children:l}),a(qi,{id:"color-input",type:"color",value:e,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),t("div",{children:[a(Hi,{children:d}),a("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Ad.map(e=>a("button",{className:"h-8 w-8 rounded border-2 border-border hover:border-primary",style:{backgroundColor:e},onClick:()=>r?.(e),"aria-label":`Selecionar cor ${e}`},e))})]})]})})]})]})},Dd=n.forwardRef(({className:e,children:r,...n},i)=>t(ut.Root,{ref:i,className:Fi("relative overflow-hidden",e),...n,children:[a(ut.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),a(Pd,{}),a(ut.Corner,{})]}));Dd.displayName=ut.Root.displayName;const Pd=n.forwardRef(({className:e,orientation:t="vertical",...r},n)=>a(ut.ScrollAreaScrollbar,{ref:n,orientation:t,className:Fi("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),...r,children:a(ut.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));Pd.displayName=ut.ScrollAreaScrollbar.displayName;const Id=[{name:"alarm",filled:!1},{name:"account_box",filled:!0},{name:"announcement",filled:!0},{name:"assessment",filled:!0},{name:"assignment",filled:!0},{name:"bookmark",filled:!0},{name:"build",filled:!0},{name:"change_history",filled:!1},{name:"credit_card",filled:!1},{name:"date_range",filled:!0},{name:"extension",filled:!0},{name:"face",filled:!0},{name:"favorite",filled:!0},{name:"store",filled:!0},{name:"group_work",filled:!0},{name:"home",filled:!0},{name:"label",filled:!0},{name:"lightbulb_2",filled:!1},{name:"list",filled:!0},{name:"line_weight",filled:!0},{name:"question_answer",filled:!0},{name:"mode_heat",filled:!0},{name:"reorder",filled:!0},{name:"warning",filled:!0},{name:"room",filled:!0},{name:"settings",filled:!0},{name:"shopping_cart",filled:!0},{name:"work",filled:!0},{name:"star_rate",filled:!0},{name:"monetization_on",filled:!0},{name:"view_list",filled:!0},{name:"visibility",filled:!0},{name:"error",filled:!0},{name:"equalizer",filled:!0},{name:"release_alert",filled:!0},{name:"mic",filled:!0},{name:"videocam",filled:!0},{name:"call",filled:!0},{name:"chat",filled:!0},{name:"chat_bubble",filled:!0},{name:"email",filled:!0},{name:"link",filled:!0},{name:"report",filled:!0},{name:"flag",filled:!0},{name:"attach_file",filled:!0},{name:"attachment",filled:!0},{name:"attach_money",filled:!0},{name:"bubble_chart",filled:!0},{name:"folder",filled:!0},{name:"business",filled:!0},{name:"device_hub",filled:!0},{name:"flash_on",filled:!0},{name:"image",filled:!0},{name:"lens",filled:!0},{name:"photo_camera",filled:!0},{name:"style",filled:!0},{name:"view_compact",filled:!0},{name:"wb_incandescent",filled:!0},{name:"directions_bus",filled:!0},{name:"directions_car",filled:!0},{name:"flight",filled:!0},{name:"hotel",filled:!0},{name:"local_offer",filled:!0},{name:"restaurant",filled:!0},{name:"restaurant_menu",filled:!0},{name:"local_shipping",filled:!0},{name:"all_inclusive",filled:!0},{name:"business_center",filled:!0},{name:"notifications",filled:!0},{name:"share",filled:!0}];function Td({name:e,filled:t,className:r}){return a("span",{className:`material-symbols-outlined ${r??""}`,style:t?{fontVariationSettings:"'FILL' 1"}:void 0,children:e})}const Rd=({value:e=null,onChange:r,label:n,noIconLabel:i="SEM ÍCONE"})=>{const[s,l]=o(!1),d=e?(c=e,Id.find(e=>e.name===c)):null;var c;const u=e=>{r?.(e),l(!1)};return t("div",{className:"space-y-2",children:[n&&a(Hi,{children:n}),t(bs,{open:s,onOpenChange:l,children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",className:"justify-start text-left font-normal gap-2",children:[d?a(Td,{name:d.name,filled:d.filled,className:"text-xl text-muted-foreground"}):a("span",{className:"text-muted-foreground text-sm",children:i}),a(D,{className:"ml-auto h-4 w-4 opacity-50"})]})}),a(ys,{className:"w-72 p-3",align:"start",children:t("div",{className:"space-y-3",children:[a(Dd,{className:"h-64",children:a("div",{className:"grid grid-cols-7 gap-1",children:Id.map(t=>a("button",{type:"button",className:"flex items-center justify-center p-1.5 rounded hover:bg-accent transition-colors "+(e===t.name?"bg-primary/10 text-primary":"text-muted-foreground"),onClick:()=>u(t.name),title:t.name,children:a(Td,{name:t.name,filled:t.filled,className:"text-2xl"})},t.name))})}),a("button",{type:"button",className:"w-full py-2 text-sm font-semibold text-foreground hover:bg-accent rounded transition-colors border-t pt-3",onClick:()=>u(null),children:i})]})})]})]})},Md=n.forwardRef(({className:e,...t},r)=>a(mt.Root,{className:Fi("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:r,children:a(mt.Thumb,{className:Fi("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")})}));Md.displayName=mt.Root.displayName;const Ld=(e={})=>{const{user:a,alias:t}=kl(),{enabled:r=!0,status:n="active"}=e;return Ja({queryKey:["qualiex-users",t,n],queryFn:()=>ll.getUsers(t,n),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},zd=({value:t,onChange:r,multiple:n=!1,label:i,required:d,placeholder:c,icon:u,maxDisplayedBadges:p,className:h,disabled:f,enabled:g,displayFormat:v="name",customDisplayFn:b,filterFn:x,sortOptions:y=!0,popoverContainer:N,onOpen:w,onClose:_})=>{const{t:C}=Ga(),{data:k=[],isLoading:S,error:A}=Ld({enabled:g}),[E,D]=o(new Map),P=s(()=>t?Array.isArray(t)?t.filter(Boolean):[t].filter(Boolean):[],[t]),I=s(()=>{if(0===P.length||0===k.length)return"";const e=new Set(k.map(e=>e.userId||e.id||""));return P.filter(a=>a&&!e.has(a)&&!E.has(a)).sort().join(",")},[P,k,E]);m(()=>{if(!I)return;const e=I.split(",");let a=!1;const t=Ys.extractTokenData();return t?.alias&&t?.companyId?(ll.fetchUsers(t.alias,t.companyId,"all").then(t=>{a||D(a=>{const r=new Map(a);for(const n of e){const e=t.find(e=>e.userId===n||e.id===n);e&&r.set(n,{...e,isActive:e.isActive??!1})}return r})}).catch(()=>{}),()=>{a=!0}):void 0},[I]);const T=s(()=>x?k.filter(x):k,[k,x]),R=s(()=>{if(0===P.length)return T;const a=new Set(T.map(e=>e.userId||e.id||"")),t=P.filter(e=>e&&!a.has(e));if(0===t.length)return T;const r=t.map(a=>{const t=E.get(a);return t||{userId:a,id:a,userName:e.t("inactive_user"),userEmail:"",isActive:!1}});return[...T,...r]},[T,P,E]),M=l(a=>{let t;if("custom"===v&&b)t=b(a);else{const e=a.userName||"";switch(v){case"name-email":t=a.userEmail?`${e} (${a.userEmail})`:e;break;case"name-role":t=a.roleName?`${e} - ${a.roleName}`:e;break;default:t=e}}return!1===a.isActive?`${t} (${e.t("inactive")})`:t},[v,b]);return a(Rs,{multiple:n,value:t??(n?[]:""),onChange:r,options:R,isLoading:S,error:A,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:M,placeholder:c||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:C("no_results"),label:i,required:d,icon:u,maxDisplayedBadges:p,disabled:f,className:h,sortOptions:y,popoverContainer:N,onOpen:w,onClose:_})};function Fd({title:e,sections:r,initialData:n,onSubmit:d,onCancel:c,open:m,submitButtonText:p,isLoading:h=!1,usersData:f}){const[g,v]=o(r?.[0]?.id||""),b=u(null),[x,y]=o(null),N=l(e=>{b.current=e,y(e)},[]),w=s(()=>r&&Array.isArray(r)?r.flatMap(e=>e.fields.flatMap(e=>"group"===e.type?e.fields||[]:e)):[],[r]),{formData:_,errors:C,updateField:k,handleSubmit:S}=Sd(w,n,void 0,m),A=s(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(_):e.disabled||!1})):[],[r,_]),E=s(()=>{const e=A.find(e=>e.id===g);if(e&&!e.disabled)return g;const a=A.find(e=>!e.disabled);return a?.id||g},[A,g]);i.useEffect(()=>{E!==g&&v(E)},[E,g]);const D=A.find(e=>e.id===E),P=e=>{const r=(e.computedValue,_[e.name]),n=void 0!==r?r:"",i=C[e.name];switch(e.type){case"group":const r="horizontal"===e.layout,o=r?`flex gap-3 w-full ${e.className||""}`:"space-y-3",s=r?Fi("space-y-2 w-full",e.wrapperClassName):Fi("space-y-2",e.className,e.wrapperClassName);return t("div",{className:s,children:[e.label,a("div",{className:o,children:e.fields?.map(e=>P(e))})]},e.name);case"user-select":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(zd,{value:n||"",onChange:a=>k(e.name,a),placeholder:e.placeholder,disabled:e.disabled,className:i?"border-destructive":""}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"textarea":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Wo,{id:e.name,value:n||"",onChange:a=>{k(e.name,a.target.value)},placeholder:e.placeholder,disabled:e.disabled,rows:e.rows,maxLength:e.maxLength,className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"select":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(Mo,{value:String(n),onValueChange:a=>{k(e.name,a),e.onValueChange&&e.onValueChange(a)},disabled:e.disabled,children:[a(Fo,{className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,children:a(zo,{placeholder:e.placeholder})}),a(Oo,{children:e.options?.map(e=>a($o,{value:e.value,children:e.label},e.value))})]}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"multiselect":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Rs,{options:e.options||[],value:Array.isArray(n)?n:[],onChange:a=>k(e.name,a),placeholder:e.placeholder,disabled:e.disabled,error:i,popoverContainer:x,getOptionValue:e=>String(e.value),getOptionLabel:e=>e.label}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"date":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"date",value:String(n),onChange:a=>k(e.name,a.target.value),placeholder:e.placeholder,disabled:e.disabled,className:Fi("w-full",i?"border-destructive":"",e.disabled?"bg-muted cursor-not-allowed":"")}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"color":return t("div",{children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"color",value:n||e.defaultValue||"#000000",onChange:a=>k(e.name,a.target.value),className:"h-10"}),i&&a("p",{className:"text-sm text-destructive mt-1",children:i})]},e.name);case"color-picker":return t("div",{children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ed,{value:n||e.defaultValue||"#3b82f6",onChange:a=>k(e.name,a)}),i&&a("p",{className:"text-sm text-destructive mt-1",children:i})]},e.name);case"icon-picker":return t("div",{children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Rd,{value:n||e.defaultValue||null,onChange:a=>k(e.name,a)}),i&&a("p",{className:"text-sm text-destructive mt-1",children:i})]},e.name);case"custom":if(!e.component)return null;const l=e.component,d="function"==typeof e.componentProps?e.componentProps(_):e.componentProps||{};return t("div",{className:`space-y-2 ${e.className||""}`,children:[e.label&&t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(l,{value:n,onChange:a=>{k(e.name,a),e.onValueChange&&e.onValueChange(a)},disabled:e.disabled,error:i,popoverContainer:x,...d}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"number":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"number",value:null!=n?String(n):"",onChange:a=>{const t=a.target.value,r=""===t?null:Number(t);k(e.name,r)},placeholder:e.placeholder,disabled:e.disabled,className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,min:e.min,step:e.step||"1"}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"checkbox":return t("div",{className:`flex items-center space-x-2 ${e.className||""}`,children:[a(qo,{id:e.name,checked:!!n,onCheckedChange:a=>k(e.name,a),disabled:e.disabled}),t(Hi,{htmlFor:e.name,className:"cursor-pointer",children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name);case"switch":return t("div",{className:`flex items-center justify-between space-x-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Md,{id:e.name,checked:!!n,onCheckedChange:a=>k(e.name,a),disabled:e.disabled}),i&&a("p",{className:"text-sm text-destructive mt-2",children:i})]},e.name);default:return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Hi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(qi,{id:e.name,type:"text",value:n||"",onChange:a=>{k(e.name,a.target.value)},placeholder:e.placeholder,disabled:e.disabled,className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,readOnly:e.disabled}),i&&a("p",{className:"text-sm text-destructive",children:i})]},e.name)}},I=l(()=>{if(!D)return null;if(D.disabled)return t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[a("div",{className:"rounded-full bg-muted p-3 mb-4",children:a("svg",{className:"h-6 w-6 text-muted-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:a("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m0 0v2m0-2h2m-2 0H9m3-8V9m0-4V3"})})}),a("h3",{className:"text-lg font-semibold mb-2",children:"Seção não disponível"}),a("p",{className:"text-muted-foreground max-w-sm",children:"Complete as informações obrigatórias na seção i18n.t('ap_general_info') para acessar esta seção."})]});if(D.component){const e=D.component;return a(e,{formData:_,updateField:k,errors:C,users:f,disabled:D.disabled})}return a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:D.fields.map(P)})},[D,_,k,C,f,P]),T=t("div",{className:"flex flex-col max-h-[80vh]",children:[A.length>1&&a("div",{className:"flex-shrink-0 p-4 border-b",children:a("div",{className:"flex space-x-2",children:A.map(e=>a($i,{variant:E===e.id?"action-primary":"action-secondary",size:"sm",onClick:()=>(e=>{const a=A.find(a=>a.id===e);a&&!a.disabled&&v(e)})(e.id),disabled:e.disabled,className:e.disabled?"opacity-50 cursor-not-allowed":"",children:e.title},e.id))})}),a("div",{className:"flex-1 overflow-y-auto px-2 md:px-4 py-4",children:h?a("div",{className:"flex items-center justify-center py-12",children:a("div",{className:"text-muted-foreground",children:"Carregando..."})}):t("form",{onSubmit:S(d),className:"space-y-3 md:space-y-4",children:[I(),t("div",{className:"flex justify-end space-x-2 pt-4",children:[a($i,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),a($i,{type:"submit",disabled:h,children:p||"Salvar"})]})]})})]});return a(mo,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:t(bo,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[t(xo,{showSeparator:!0,children:[a(wo,{children:e}),a(_o,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),T]})})}function Ud({currentPage:e,totalPages:n,totalItems:i,itemsPerPage:o,onPageChange:s,onItemsPerPageChange:l,variant:d="full"}){const{t:c}=Ga();if(0===i)return null;const u=(e-1)*o+1,m=Math.min(e*o,i);return t("div",{className:"flex items-center justify-between px-4 py-3 gap-4",children:[a("div",{className:"flex items-center gap-2",children:"full"===d&&t(r,{children:[a("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:c("rows_per_page","Linhas por página")}),t(Mo,{value:String(o),onValueChange:e=>l(Number(e)),children:[a(Fo,{className:"h-8 w-[70px]",children:a(zo,{})}),t(Oo,{children:[a($o,{value:"10",children:"10"}),a($o,{value:"25",children:"25"}),a($o,{value:"50",children:"50"}),a($o,{value:"100",children:"100"})]})]})]})}),t("div",{className:"text-sm text-muted-foreground text-center hidden sm:block",children:[u,"-",m," ",c("of","de")," ",i," ",c("items","itens")]}),t("div",{className:"flex items-center gap-1",children:[a($i,{variant:"outline",size:"sm",onClick:()=>s(1),disabled:1===e,className:"h-8 w-8 p-0",children:a(ie,{size:16})}),a($i,{variant:"outline",size:"sm",onClick:()=>s(e-1),disabled:1===e,className:"h-8 w-8 p-0",children:a(oe,{size:16})}),t("div",{className:"flex items-center gap-1 px-2",children:[a("span",{className:"text-sm font-medium",children:e}),a("span",{className:"text-sm text-muted-foreground",children:c("of","de")}),a("span",{className:"text-sm font-medium",children:n})]}),a($i,{variant:"outline",size:"sm",onClick:()=>s(e+1),disabled:e===n,className:"h-8 w-8 p-0",children:a(U,{size:16})}),a($i,{variant:"outline",size:"sm",onClick:()=>s(n),disabled:e===n,className:"h-8 w-8 p-0",children:a(se,{size:16})})]})]})}function jd({manager:e}){return a(Ud,{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 Od={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Bd={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},$d={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Vd({children:e,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:o=!1,className:s}){return a("div",{className:Fi("flex","column"===t?"flex-col":"flex-row",Od[r],Bd[n],$d[i],o&&"flex-wrap",s),children:e})}function qd({manager:e,filters:n,inline:i=!1}){const{t:o}=Ga(),{isSearchVisible:s}=kl(),l=e.searchTerm,d=t(r,{children:[n.some(e=>"search"===e.type)&&!s&&t("div",{className:"relative flex-1",children:[a(B,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(qi,{placeholder:"Pesquisar",value:e.searchTerm,onChange:a=>e.handleSearch(a.target.value),className:"pl-10"})]}),n.filter(e=>"select"===e.type&&e.options).map((e,r)=>t(Mo,{value:e.value||"",onValueChange:a=>e.onChange?.(a),children:[a(Fo,{className:"w-[180px]",children:a(zo,{placeholder:e.placeholder})}),a(Oo,{children:e.options.map(e=>a($o,{value:e.value,children:e.label},e.value))})]},`select-${r}`)),n.filter(e=>"custom"===e.type&&e.component).map((e,t)=>{const r=e.component;return a("div",{className:i?"":"w-full sm:w-auto",children:a(r,{...e.props})},`custom-${t}`)}),l&&t($i,{variant:"outline",onClick:e.clearFilters,className:"whitespace-nowrap",children:[a(E,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?a("div",{className:"flex items-center gap-2",children:d}):a(Vd,{direction:"column",gap:"md",className:"mb-6",children:a(Vd,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:d})})}function Wd({manager:e,config:r,formSections:n,onSave:i,onToggleStatus:s,defaultSort:l}){e&&e.queryKey;const{setSearchVisible:d}=kl(),[c,u]=tt(),[p,h]=o(!1),[f,g]=o(null),[v,b]=o({isOpen:!1,entityId:null,entityName:""}),[x,y]=o({isOpen:!1,count:0});m(()=>(d(!0),()=>{d(!1)}),[d]),m(()=>{if(l&&e){const a=`${e.queryKey}_sortField`,t=`${e.queryKey}_sortDirection`;if(!c.has(a)&&!c.has(t)){const e=Object.fromEntries(c);e[a]=l.column,e[t]=l.direction,u(e)}}},[]);const N=n.length>0?e=>{r.onEdit?r.onEdit(e):(g(e),h(!0))}:void 0,w="function"==typeof e?.deleteEntity?e=>{b({isOpen:!0,entityId:e.id,entityName:e.title||e.name||"Item"})}:void 0,_=()=>{b({isOpen:!1,entityId:null,entityName:""})},C=void 0!==r.hideNewButton?!r.hideNewButton:r.showNewButton??!0,k=(r.customActions||[]).map(e=>({label:e.label,icon:e.icon,action:e.action,variant:"destructive"===e.variant?"default":e.variant,disabled:e.disabled,disabledReason:e.disabledReason}));return t("div",{className:"flex-1 flex flex-col h-full",children:[(r.showActionBar??!0)&&a(bd,{onNew:()=>{r.onNew?r.onNew():(g(null),h(!0))},newButtonLabel:r.newButtonLabel,showNewButton:C,showSearch:r.showSearch,searchValue:e.searchTerm,onSearchChange:e.handleSearch,searchPlaceholder:r.searchPlaceholder,showBulkActions:r.enableBulkActions,selectedCount:e.selectedIds.length,bulkActions:r.bulkActions,onBulkDelete:()=>{y({isOpen:!0,count:e.selectedIds.length})},onClearSelection:e.clearSelection,customActions:k,filters:r.filters&&r.filters.length>0?a(qd,{manager:e,filters:r.filters,inline:!0}):void 0}),a("div",{className:"flex-1 flex flex-col overflow-hidden",children:r.customListView?a("div",{className:"flex-1 overflow-auto p-4",children:r.customListView(e.entities,e)}):a(kd,{manager:e,columns:r.columns,onEdit:N,onDelete:w,onToggleStatus:s,enableBulkActions:r.enableBulkActions,customRowActions:r.customRowActions,enableColumnManager:!0,columnManagerStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-columns`,resizeStorageKey:`crud-${r.entityName.toLowerCase().replace(/\s+/g,"-")}-resize`,defaultHiddenColumns:r.defaultHiddenColumns})}),a("div",{className:"flex-shrink-0 border-t bg-background",children:a(jd,{manager:e})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&a(Fd,{open:p,title:f?`Editar ${r.entityName}`:`Novo ${r.entityName}`,sections:n,initialData:f||void 0,onSubmit:e=>{i(e),h(!1),g(null)},onCancel:()=>{h(!1),g(null)},isLoading:e.isLoading,submitButtonText:f?"Atualizar":"Criar"}),a(mo,{open:v.isOpen,onOpenChange:_,children:t(bo,{size:"sm",variant:"destructive",children:[a(xo,{showSeparator:!0,children:a(wo,{children:"Você tem certeza absoluta?"})}),a("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:t("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",a("strong",{children:v.entityName}),". Esta ação não pode ser desfeita."]})}),t(No,{children:[a($i,{variant:"outline",onClick:_,children:"Cancelar"}),a($i,{variant:"destructive",onClick:()=>{v.entityId&&"function"==typeof e?.deleteEntity&&(e.deleteEntity(v.entityId),b({isOpen:!1,entityId:null,entityName:""}))},disabled:e.isDeleting,children:e.isDeleting?"Excluindo...":"Sim, excluir"})]})]})}),a(mo,{open:x.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),children:t(bo,{size:"sm",variant:"destructive",children:[a(xo,{showSeparator:!0,children:a(wo,{children:"Você tem certeza absoluta?"})}),a("div",{className:"flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",children:t("p",{className:"text-sm text-muted-foreground",children:["Você está prestes a excluir ",a("strong",{children:x.count})," ",1===x.count?r.entityName:r.entityNamePlural,". Esta ação não pode ser desfeita."]})}),t(No,{children:[a($i,{variant:"outline",onClick:()=>y({isOpen:!1,count:0}),children:"Cancelar"}),a($i,{variant:"destructive",onClick:()=>{e.bulkDelete?.(e.selectedIds),y({isOpen:!1,count:0})},disabled:e.isBulkDeleting,children:e.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Hd(e){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:o,onToggleStatus:s}=e,l=t??r,d={entityName:n.entityName,entityNamePlural:n.entityNamePlural,filters:n.filters||[],columns:n.columns,cardFields:n.cardFields||[],enableBulkActions:n.enableBulkActions??!1,bulkActions:n.bulkActions||[],customActions:n.customActions,customRowActions:n.customRowActions,customListView:n.customListView,onEdit:o||n.onEdit,onNew:n.onNew,useCustomRouting:n.useCustomRouting,hideNewButton:n.hideNewButton,showNewButton:n.showNewButton,newButtonLabel:n.newButtonLabel,showSearch:n.showSearch,searchPlaceholder:n.searchPlaceholder,showActionBar:n.showActionBar};return a(Wd,{manager:l,config:d,formSections:n.formSections,onSave:i,onToggleStatus:s,defaultSort:n.defaultSort})}}function Gd(e,a,t){return r=>{if(r.id){const a=t(r);e.updateEntity(r.id,a)}else{const t=a(r);e.createEntity(t)}}}function Kd(e,a,t={}){const r=[];return Object.keys(a).forEach(e=>{if("id"!==e&&!e.endsWith("_at")){const t=a[e],n={key:e,header:Qd(e),label:Qd(e),...Yd(e,t),sortable:!0,searchable:"string"==typeof t};r.push(n)}}),{title:e,columns:r,searchPlaceholder:`Buscar ${e.toLowerCase()}...`,itemsPerPage:10,enableCreate:!0,enableEdit:!0,enableDelete:!0,enableSearch:!0,enableFilters:!1,...t}}function Yd(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 Qd(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Xd=({children:n})=>{const{isAuthenticated:o,isLoading:s}=kl();if(i.useEffect(()=>{if(s)return;if(o)return;if(Ys.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 r=vr(),n=window.location.pathname+window.location.search+window.location.hash;["/","/login","/callback"].includes(window.location.pathname)||localStorage.setItem("auth_return_url",n);(async()=>{r?await yl.loginDev():yl.loginProd()})()},[o,s]),s&&!o)return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Carregando..."})}),t(Xi,{className:"text-center",children:[a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),a("p",{className:"text-muted-foreground",children:"Verificando autenticação..."})]})]})});if(!o){const r=new URLSearchParams(window.location.search).has("access_token")||new URLSearchParams(window.location.hash.substring(1)).has("access_token");return a("div",r?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Processando..."})}),t(Xi,{className:"text-center",children:[a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),a("p",{className:"text-muted-foreground",children:"Processando tokens..."})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Iniciando..."})}),t(Xi,{className:"text-center",children:[a("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"}),a("p",{className:"text-muted-foreground",children:vr()?e.t("auto_login"):e.t("redirecting_auth")})]})]})})}return a(r,{children:n})};function Jd(e={}){const{paramName:a="alias"}=e,t=rt(),{alias:r,companies:n}=kl(),i=t[a]||null;return s(()=>{if(!i)return{urlAlias:null,isAliasMismatch:!1,isValidAlias:!1,isMissing:!0,matchedCompany:null};const e=n?.find(e=>e.alias===i)||null,a=!!e;return{urlAlias:i,isAliasMismatch:a&&i!==r,isValidAlias:a,isMissing:!1,matchedCompany:e}},[i,r,n])}function Zd({children:e,paramName:n="alias"}){const i=nt(),s=it(),d=rt(),{alias:c,isAuthenticated:p,isLoading:h,switchUnit:f}=kl(),{urlAlias:g,isAliasMismatch:v,isValidAlias:b,isMissing:x,matchedCompany:y}=Jd({paramName:n}),[N,w]=o(!1),_=u(!1),C=n in d,k=l(e=>{const a=d[n],{pathname:t,search:r,hash:i}=s;if(a){const n=t.split("/"),o=n.findIndex(e=>e===a);if(o>=0)return n[o]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[d,n,s]);return m(()=>{if(C&&!h&&p&&c&&!_.current)if(x)i(k(c),{replace:!0});else if(!g||b){if(v&&y&&!_.current){(async()=>{_.current=!0,w(!0);try{await f(y)}catch(e){c&&i(k(c),{replace:!0})}finally{_.current=!1,w(!1)}})()}}else i(k(c),{replace:!0})},[C,h,p,c,x,g,b,v,y,f,k,i]),h||!p?a(r,{children:e}):N?a("div",{className:"flex items-center justify-center min-h-screen",children:t("div",{className:"flex flex-col items-center gap-3",children:[a(Yo,{size:"lg"}),a("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):a(r,{children:e})}function ec(){const{alias:e}=kl(),{pathname:t,search:r,hash:n}=it();return e?a(ot,{to:`/${e}${t}${r}${n}`,replace:!0}):null}const ac=v("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4",{variants:{variant:{info:"bg-[hsl(var(--alert-info-bg))] border-[hsl(var(--alert-info-border))] text-[hsl(var(--alert-info-foreground))] [&>svg]:text-[hsl(var(--alert-info-foreground))]",warning:"bg-[hsl(var(--alert-warning-bg))] border-[hsl(var(--alert-warning-border))] text-[hsl(var(--alert-warning-foreground))] [&>svg]:text-[hsl(var(--alert-warning-foreground))]",danger:"bg-[hsl(var(--alert-danger-bg))] border-[hsl(var(--alert-danger-border))] text-[hsl(var(--alert-danger-foreground))] [&>svg]:text-[hsl(var(--alert-danger-foreground))]",success:"bg-[hsl(var(--alert-success-bg))] border-[hsl(var(--alert-success-border))] text-[hsl(var(--alert-success-foreground))] [&>svg]:text-[hsl(var(--alert-success-foreground))]"}},defaultVariants:{variant:"info"}}),tc={info:ce,warning:ce,danger:de,success:le},rc=n.forwardRef(({className:e,variant:r="info",showIcon:n=!0,children:i,...o},s)=>{const l=tc[r||"info"];return t("div",{ref:s,role:"alert",className:Fi(ac({variant:r}),e),...o,children:[n&&a(l,{className:"h-4 w-4"}),i]})});rc.displayName="Alert";const nc=n.forwardRef(({className:e,...t},r)=>a("h5",{ref:r,className:Fi("mb-1 font-medium leading-none tracking-tight",e),...t}));nc.displayName="AlertTitle";const ic=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("text-sm [&_p]:leading-relaxed",e),...t}));ic.displayName="AlertDescription";const oc=()=>{const{processCallback:e}=kl(),n=nt(),[i,s]=o(null),[l,d]=o(!1);m(()=>{(async()=>{try{if(await e()){window.history.replaceState({},document.title,"/");const e=localStorage.getItem("auth_return_url");localStorage.removeItem("auth_return_url"),n(e||"/",{replace:!0})}else s("Falha na autenticação. Tente novamente.")}catch(a){localStorage.removeItem("auth_return_url"),s(a?.message||"Erro durante a autenticação. Tente novamente.")}})()},[e,n]);const c=async()=>{d(!0),s(null);try{await e()||s("Falha na autenticação. Tente novamente.")}catch(a){s(a?.message||"Erro ao tentar novamente.")}finally{d(!1)}},u=()=>{window.location.href="/"};return a("div",i?{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:t(Yi,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[a(O,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),t(Xi,{className:"space-y-4",children:[a(rc,{variant:"danger",children:a(ic,{children:i})}),a("div",{className:"text-sm text-muted-foreground",children:a("p",{children:"Se o problema persistir, verifique se a URL de callback está configurada corretamente no provedor OAuth."})}),t("div",{className:"flex gap-2",children:[a($i,{onClick:c,disabled:l,className:"flex-1",children:t(r,l?{children:[a(Yo,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[a(ue,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),a($i,{onClick:u,variant:"outline",className:"flex-1",children:"Voltar ao Início"})]})]})]})}:{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),t(Xi,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(Yo,{size:"lg"})}),a("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},sc=()=>{const{t:e}=Ga();return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Gi,{className:"w-full max-w-md",children:[a(Ki,{className:"text-center",children:a(Yi,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),t(Xi,{className:"text-center space-y-4",children:[a("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),a($i,{onClick:async()=>{vr()?await yl.loginDev():yl.loginProd()},className:"w-full",size:"lg",children:vr()?e("dev_login"):e("login_with_qualiex")})]})]})})},lc=d(void 0);function dc({children:e,actions:t}){const{t:r}=Ga(),[n,i]=o({}),[d,c]=o(t);m(()=>{c(t)},[t]);const u=l(()=>i({}),[]),p=s(()=>({metadata:n,setMetadata:i,clearMetadata:u,headerActions:d,setHeaderActions:c}),[n,u,d]);return a(lc.Provider,{value:p,children:e})}function cc(){const e=c(lc);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function uc(e){const{setMetadata:a,clearMetadata:t}=cc(),r=u({});m(()=>{const n=JSON.stringify(r.current.breadcrumbs)!==JSON.stringify(e.breadcrumbs);return(r.current.title!==e.title||r.current.subtitle!==e.subtitle||n)&&(r.current={title:e.title,subtitle:e.subtitle,breadcrumbs:e.breadcrumbs},a(e)),()=>t()},[e.title,e.subtitle,e.breadcrumbs,a,t])}function mc(e){return{queryClient:e.queryClient||new et({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var pc={actions:"Ações",activate:"Ativar",add_first_item:"Adicione seu primeiro item para começar",add_item:"Adicionar Item",advanced_filter:"Filtro avançado",all:"Todos",allow:"Permitir",allowed_items:"Itens permitidos",also_discover:"Conheça também",alt_text:"Texto Alternativo",anonymous:"Anônimo",ap_action_plan:"Plano de Ação",ap_action_type:"Tipo de Ação",ap_add:"Adicionar",ap_add_comment_placeholder:"Adicionar comentário...",ap_add_cost:"Adicionar custo",ap_add_predecessor:"Adicionar predecessor",ap_attachments:"Anexos",ap_belongs_to:"Pertence a",ap_cause:"Causa",ap_change_status:"Alterar Status",ap_checker:"Verificador",ap_clear:"Limpar",ap_comments:"Comentários",ap_cost_description:"Descrição do custo",ap_costs:"Custos",ap_delete:"Excluir",ap_description:"Descrição",ap_description_placeholder:"Descreva o plano de ação",ap_duration_days:"Duração (dias)",ap_edit_progress:"Editar Progresso",ap_end_date:"Data de Término",ap_estimated_cost:"Custo Estimado",ap_file_duplicate:"Arquivo duplicado",ap_file_upload_error:"Erro ao enviar arquivo",ap_general:"Geral",ap_general_info:"Informações Gerais",ap_history:"Histórico",ap_justification:"Justificativa",ap_justification_placeholder:"Justificativa do plano de ação",ap_name:"Nome",ap_new_action:"Nova Ação",ap_no_attachments:"Nenhum anexo",ap_no_comments:"Nenhum comentário",ap_no_costs:"Nenhum custo registrado",ap_no_history:"Nenhum registro no histórico",ap_no_predecessors:"Nenhum predecessor adicionado",ap_no_progress:"Sem dados de progresso disponíveis",ap_overall_progress:"Progresso geral",ap_place:"Local",ap_plan_name_placeholder:"Nome do plano de ação",ap_predecessors:"Predecessores",ap_priority:"Prioridade",ap_priority_high:"Alta",ap_priority_low:"Baixa",ap_priority_medium:"Média",ap_progress:"Progresso",ap_progress_comment_placeholder:"Adicione um comentário sobre o progresso",ap_progress_percent:"Progresso (%)",ap_report:"Reportar",ap_report_progress:"Reportar progresso",ap_reporting:"Reportando...",ap_reports_history:"Histórico de reportes",ap_responsible:"Responsável",ap_select_action:"Selecione uma ação",ap_select_cause:"Selecione a causa",ap_select_checker:"Selecione o verificador",ap_select_date:"Selecione a data",ap_select_parent:"Selecione a ação pai",ap_select_place:"Selecione o local",ap_select_priority:"Selecione a prioridade",ap_select_responsible:"Selecione o responsável",ap_select_type:"Selecione o tipo",ap_start_date:"Data de Início",ap_status_canceled:"Cancelada",ap_status_done:"Concluída",ap_status_effectiveness_check:"Verificação de eficácia",ap_status_running:"Em andamento",ap_status_suspended:"Suspensa",ap_status_waiting_start:"Aguardando início",ap_time_label:"Tempo",ap_time_spent:"Tempo gasto (HH:MM)",ap_total_cost:"Custo total realizado",ap_total_time:"Tempo total",ap_type_corrective:"Corretiva",ap_type_immediate:"Imediata",ap_type_improvement:"Oportunidade de Melhoria",ap_type_preventive:"Preventiva",ap_type_standardization:"Padronização",ap_value:"Valor (R$)",ap_via_app:"Via app",approval_approve:"Aprovar",approval_execute_action:"Executar ação",approval_opinion:"Parecer *",approval_read_less:"Ler menos",approval_read_more:"Ler mais",approval_reprove_radio:"Reprovar e retornar para etapa",approval_search_approver:"Buscar aprovador...",approval_select_approver:"Selecionar aprovador",approval_select_approver_placeholder:"Selecione um aprovador...",approval_select_step:"Selecione a etapa",approval_step_label:"Etapa",approval_user_group:"Grupo de usuários",audit_description:"Descrição",audit_esign:"Assinatura eletrônica",audit_not_informed:"Não informado",audit_references:"Referências",audit_security:"Segurança",audit_trail:"Trilha de Auditoria",auth_error:"Erro durante a autenticação. Tente novamente.",auth_failed:"Falha na autenticação. Tente novamente.",auto_login:"Fazendo login automático...",back:"Voltar",bulk_delete_error:"Erro ao excluir itens em lote",bulk_delete_success:"Itens excluídos com sucesso",cancel:"Cancelar",change_photo:"Trocar foto",cannot_be_own_leader:"Um líder não pode ser seu próprio superior",clear_filters:"Limpar filtros",clear_formatting:"Limpar Formatação",clear_search:"Limpar busca",clear_selection:"Limpar seleção",close:"Fechar",collapse_row:"Recolher linha",columns:"Colunas",conclude:"Concluir",confirm_removal:"Confirmar remoção",could_not_load_info:"Não foi possível carregar as informações",current:"Atual",custom_color:"Cor personalizada",dashboard_advanced_filter:"Filtro avançado",dashboard_all_access:"Todos os colaboradores terão acesso",dashboard_average:"Média",dashboard_code:"Código",dashboard_distinct_count:"Contagem distinta",dashboard_edit:"Editar Dashboard",dashboard_exit_fullscreen:"Sair do fullscreen",dashboard_export_chart:"Exportar gráfico",dashboard_export_table:"Exportar tabela",dashboard_max_value:"Valor máximo",dashboard_min_value:"Valor mínimo",dashboard_my:"Meus dashboards",dashboard_new:"Novo Dashboard",dashboard_no_data:"A consulta não retornou itens para o seu perfil.",dashboard_no_refresh:"Não atualizar",dashboard_normal_page:"Página normal",dashboard_not_shared:"Não compartilhado",dashboard_only_mine:"Somente meus",dashboard_only_overdue:"Somente atrasados",dashboard_only_responsible:"Somente o responsável terá acesso",dashboard_open_query:"Open query",dashboard_remove_favorite:"Remover favorito",dashboard_responsible:"Responsável",dashboard_select_groups:"Selecione grupos, locais e colaboradores específicos",dashboard_shared_unit:"Compartilhado com todos os colaboradores da unidade",dashboard_status:"Situação",dashboard_title:"Título",dashboard_wait_refresh:"Aguarde para atualizar novamente",dashboard_work_done:"Trabalho executado",dashboard_work_planned:"Trabalho planejado",deactivate:"Inativar",deselect_all:"Deselecionar todas",dev_login:"Login Desenvolvimento",download:"Download",edit:"Editar",edit_profile:"Editar Perfil",edit_name:"Editar Nome",electronic_signature:"Assinatura Eletrônica",embed_code:"Código embed",embedded_content:"Embedded content",enter_code:"Digite o código",enter_password:"Digite sua senha",error_authentication:"Erro de Autenticação",error_connection:"Erro de Conexão",error_copied_clipboard:"Os detalhes do erro foram copiados para a área de transferência.",error_loading:"Erro ao carregar",error_loading_data:"Erro ao carregar dados",error_session_expired:"Sessão Expirada",error_token_expired:"Token de autenticação expirado. Faça login novamente.",esign_code_description:"Um código de verificação foi enviado para o seu e-mail. Insira o código abaixo para confirmar a operação.",esign_code_error:"Erro ao validar o código. Tente novamente.",esign_invalid_code:"Código inválido. Tente novamente.",esign_invalid_password:"Senha incorreta. Tente novamente.",esign_password_description:"Digite sua senha para confirmar a operação.",esign_password_error:"Erro ao validar a senha. Tente novamente.",esign_resend_error:"Erro ao reenviar o código.",expand_row:"Expandir linha",expiration_date:"Data de expiração",file_error:"Erro no arquivo",file_upload:"Upload de arquivo",go_to_next_page:"Ir para próxima página",go_to_previous_page:"Ir para página anterior",group_by_column:"Agrupar por esta coluna",heading_1:"Título 1",heading_2:"Título 2",heading_3:"Título 3",image_description:"Descrição da imagem",import_flows:"Fluxos de Importação",import_manage:"Gerencie seus fluxos de importação",inactive:"inativo",inactive_user:"[Usuário inativo]",input_type:"Tipo de entrada",invalid_form:"Formulário inválido. Preencha todos os campos obrigatórios.",italic:"Itálico",item_details:"Detalhes do item",items:"itens",items_per_page:"Itens por página",know_saber_gestao:"Conheça o Saber Gestão",know_staff:"Conheça Staff",language:"Idioma",last_update:"Última atualização",leader:"Líder",leader_create_error:"Erro ao criar líder",leader_not_found:"Líder não encontrado",leader_promoted_success:"Líder promovido com sucesso",leader_remove_error:"Erro ao remover líder",leader_removed_success:"Líder removido com sucesso",leader_update_error:"Erro ao atualizar líder",leader_updated_success:"Líder atualizado com sucesso",leadership_add_root:"Adicionar Líder Raiz",leadership_add_subordinate:"Adicionar Liderado",leadership_cycle_error:"Esta associação criaria um ciclo na hierarquia",leadership_define_leader:"Definir Líder",leadership_immediate_superior:"Superior Imediato",leadership_make_root:"Tornar Líder Raiz",leadership_make_root_short:"Tornar Raiz",leadership_no_hierarchy:"Nenhuma hierarquia de liderança encontrada.",leadership_no_members:"Nenhum membro na equipe",leadership_no_user_selected:"Nenhum usuário selecionado",leadership_no_users_available:"Nenhum usuário disponível",leadership_no_users_found:"Nenhum usuário encontrado",leadership_remove_team:"Remover da equipe",leadership_select_subordinates:"Selecione pelo menos um liderado",learn_qualiex:"Aprenda a usar o Qualiex",leave_without_saving:"Sair sem salvar",lines_per_page:"Linhas por página",link:"Link",login_with_qualiex:"Entrar com Qualiex",manage_access:"Gerenciar Acessos",mind_map_add_child:"Adicionar filho",mind_map_add_sibling:"Adicionar irmão",mind_map_aria_label:"Mapa mental",mind_map_collapse_all:"Colapsar tudo",mind_map_delete_node:"Excluir nó",mind_map_expand_all:"Expandir tudo",mind_map_export_image:"Exportar como imagem",mind_map_export_json:"Exportar como JSON",mind_map_fit_to_screen:"Ajustar à tela",mind_map_redo:"Refazer",mind_map_undo:"Desfazer",mind_map_zoom_in:"Aproximar",mind_map_zoom_out:"Afastar",modules:"Módulos",more_options:"Mais opções",msg_create_error:"Erro ao criar registro",msg_created_success:"Registro criado com sucesso",msg_delete_error:"Erro ao excluir registro",msg_deleted_success:"Registro excluído com sucesso",msg_load_error:"Erro ao carregar dados",msg_update_error:"Erro ao atualizar registro",msg_updated_success:"Registro atualizado com sucesso",new_document:"Novo Documento",new_folder:"Nova Pasta",new_item:"Novo Item",next:"Próximo",no_access_page:"Parece que você não tem acesso a essa página",no_data_to_display:"Não há dados para exibir no momento.",no_errors_recorded:"Nenhum erro registrado",no_image_selected:"Nenhuma imagem selecionada",no_item_selected:"Nenhum item selecionado",no_items_found:"Nenhum item encontrado",no_items_found_empty:"Nenhum item encontrado",no_place_found:"Nenhum local encontrado",no_place_selected:"Sem local",no_products:"Sem produtos",no_reports_found:"Nenhum relatório encontrado",no_results:"Nenhum resultado encontrado",no_search_results:"Nenhum resultado para a busca",no_video_selected:"Nenhum vídeo selecionado",not_authenticated:"Não autenticado",not_available:"Não disponível",of:"de",open_popover:"Abrir Popover",open_wiki:"Abrir Wiki",ordered_list:"Lista Ordenada",page:"Página",paste_embed_code:"Cole o código embed aqui",permissions:"Permissões",preset_colors:"Cores predefinidas",preview:"Visualizar",redirecting_auth:"Redirecionando para autenticação...",refresh_data:"Atualizar dados",remove:"Remover",remove_grouping:"Remover agrupamento",replace:"Substituir",report:"Relatório",request_date:"Data da solicitação",required_field:"Campo obrigatório",resend_code:"Reenviar código",restricted_access:"Acesso restrito",rows_per_page:"Registros por página",save:"Salvar",save_as_draft:"Salvar como Rascunho",save_as_template:"Salvar como Modelo",saving:"Salvando...",search:"Pesquisar",search_placeholder:"Pesquisar...",search_report_placeholder:"Buscar relatório...",search_user_placeholder:"Buscar usuário...",select_all:"Selecionar todos",select_all_columns:"Selecionar todas",select_all_items:"Selecionar todos",select_at_least_one:"Selecione pelo menos um item",select_at_least_one_item:"Selecione ao menos um item",select_date:"Selecione uma data",select_file_format:"Selecione o formato do arquivo",select_items_to_add:"Selecione itens para adicionar...",select_placeholder:"Selecione...",selected:"Selecionados",session_expired:"Sua sessão expirou. Você será redirecionado para fazer login novamente.",sign_access_error:"Erro ao acessar serviço de assinatura",sign_api_key_info:"Informe a API Key do provedor de assinatura",sign_api_key_input:"Insira a API Key do provedor de assinatura",sign_api_key_placeholder:"Insira a chave de API",sign_api_key_required:"Chave de API obrigatória",sign_attempt:"Tentativa de assinatura",sign_auth_required:"Autenticação necessária para assinar",sign_click_to_select:"Clique para selecionar documento",sign_config_save_err:"Erro ao salvar configuração de assinatura",sign_config_save_error:"Erro ao salvar configuração de assinatura",sign_config_saved:"Configuração de assinatura salva",sign_config_saved_success:"Configuração de assinatura salva com sucesso",sign_configured:"Assinatura configurada",sign_configured_unit:"Assinatura digital configurada para esta unidade",sign_digital_config:"Configuração de Assinatura Digital",sign_doc_available:"Documento assinado disponível para download",sign_doc_load_error:"Erro ao carregar documento",sign_doc_process_error:"Erro ao processar documento",sign_doc_sent:"Documento enviado para assinatura",sign_download_signed:"Baixar documento assinado",sign_email_fallback:"E-mail de fallback para assinatura",sign_environment:"Ambiente de assinatura",sign_fetch_failed:"Falha ao buscar documento assinado",sign_file_not_allowed:"Extensão de arquivo não permitida",sign_file_type_not_allowed:"Tipo de arquivo não permitido",sign_incorrect_data:"O signatário reportou dados incorretos.",sign_login_required:"Login necessário para assinar",sign_login_to_sign:"Faça login para utilizar a assinatura digital.",sign_monthly_limit:"Limite mensal de assinaturas atingido",sign_no_access:"Não foi possível obter o acesso para assinatura. Tente novamente.",sign_not_configured:"Assinatura não configurada",sign_not_configured_unit:"Assinatura digital ainda não configurada para esta unidade",sign_preparing_doc:"Preparando documento para assinatura",sign_process_error:"Erro ao processar assinatura",sign_save_config:"Salvar configuração",sign_save_config_btn:"Salvar Configuração",sign_select_pdf:"Selecione um arquivo PDF",sign_sending_doc:"Enviando documento para assinatura",sign_signed_success:"Documento assinado com sucesso",sign_signer_unavailable:"Signer ID não disponível",sign_try_again:"Tentar novamente",sign_update_config:"Atualizar configuração",sign_update_config_btn:"Atualizar Configuração",sign_waiting_provider:"Aguardando provedor de assinatura",sign_widget_error:"Erro no widget de assinatura",something_went_wrong:"Algo deu errado",state:"Estado",status:"Status",status_completed:"Concluído",status_error:"Erro",status_expired:"Expirado",status_processing:"Processando",status_waiting:"Aguardando",steps:"Etapas",subordinates_add_error:"Erro ao adicionar subordinados",subordinates_added_success:"Subordinados adicionados com sucesso",subordinates_sync_error:"Erro ao sincronizar subordinados",subordinates_synced_success:"Subordinados sincronizados com sucesso",team_all_groups:"Todos os grupos",terms_confirm_reading:"Confirmar leitura",terms_confirmation_available:"Confirmação disponível em",terms_of_use:"Termos de Uso",terms_read_agree:"Li e concordo",terms_see_later:"Ver depois",terms_updated:"Termos de Uso Atualizados",terms_view:"Visualizar termo de uso",terms_view_short:"View term",try_adjust_search:"Tente ajustar sua busca",try_again:"Tentar Novamente",unit_not_selected:"Nenhuma unidade selecionada",unknown_error:"Erro desconhecido",unsaved_changes:"Alterações não salvas",unsaved_changes_description:"Existem alterações não salvas. Deseja sair sem salvar?",updates:"Atualizações",user:"Usuário",user_info:"Informações do Usuário",user_photo:"Foto do usuário",users_already_leaders:"Usuários já são líderes",verification_code:"Código de verificação",video:"Vídeo",video_title:"Título do vídeo",view_report:"Visualizar relatório",want_to_know_more:"Quero conhecer mais",write_content_here:"Escreva o conteúdo aqui..."},hc={actions:"Actions",activate:"Activate",add_first_item:"Add your first item to get started",add_item:"Add Item",advanced_filter:"Advanced filter",all:"All",allow:"Allow",allowed_items:"Allowed items",also_discover:"Also discover",alt_text:"Alternative Text",anonymous:"Anonymous",ap_action_plan:"Action Plan",ap_action_type:"Action type",ap_add:"Add",ap_add_comment_placeholder:"Add a comment...",ap_add_cost:"Add cost",ap_add_predecessor:"Add predecessor",ap_attachments:"Attachments",ap_belongs_to:"Belongs to",ap_cause:"Cause",ap_change_status:"Change Status",ap_checker:"Checker",ap_clear:"Clear",ap_comments:"Comments",ap_cost_description:"Cost description",ap_costs:"Costs",ap_delete:"Delete",ap_description:"Description",ap_description_placeholder:"Describe the action plan",ap_duration_days:"Duration (days)",ap_edit_progress:"Edit Progress",ap_end_date:"End date",ap_estimated_cost:"Estimated cost",ap_file_duplicate:"Duplicate file",ap_file_upload_error:"Error uploading file",ap_general:"General",ap_general_info:"General Information",ap_history:"History",ap_justification:"Justification",ap_justification_placeholder:"Action plan justification",ap_name:"Name",ap_new_action:"New Action",ap_no_attachments:"No attachments",ap_no_comments:"No comments",ap_no_costs:"No costs recorded",ap_no_history:"No history records",ap_no_predecessors:"No predecessors added",ap_no_progress:"No progress data available",ap_overall_progress:"Overall progress",ap_place:"Place",ap_plan_name_placeholder:"Action plan name",ap_predecessors:"Predecessors",ap_priority:"Priority",ap_priority_high:"High",ap_priority_low:"Low",ap_priority_medium:"Medium",ap_progress:"Progress",ap_progress_comment_placeholder:"Add a comment about the progress",ap_progress_percent:"Progress (%)",ap_report:"Report",ap_report_progress:"Report progress",ap_reporting:"Reporting...",ap_reports_history:"Reports history",ap_responsible:"Responsible",ap_select_action:"Select an action",ap_select_cause:"Select cause",ap_select_checker:"Select checker",ap_select_date:"Select date",ap_select_parent:"Select parent action",ap_select_place:"Select place",ap_select_priority:"Select priority",ap_select_responsible:"Select responsible",ap_select_type:"Select type",ap_start_date:"Start date",ap_status_canceled:"Canceled",ap_status_done:"Completed",ap_status_effectiveness_check:"Effectiveness check",ap_status_running:"In progress",ap_status_suspended:"Suspended",ap_status_waiting_start:"Waiting to start",ap_time_label:"Time",ap_time_spent:"Time spent (HH:MM)",ap_total_cost:"Total realized cost",ap_total_time:"Total time",ap_type_corrective:"Corrective",ap_type_immediate:"Immediate",ap_type_improvement:"Improvement Opportunity",ap_type_preventive:"Preventive",ap_type_standardization:"Standardization",ap_value:"Value",ap_via_app:"Via app",approval_approve:"Approve",approval_execute_action:"Execute action",approval_opinion:"Opinion *",approval_read_less:"Read less",approval_read_more:"Read more",approval_reprove_radio:"Reject and return to step",approval_search_approver:"Search approver...",approval_select_approver:"Select approver",approval_select_approver_placeholder:"Select an approver...",approval_select_step:"Select the step",approval_step_label:"Step",approval_user_group:"User group",audit_description:"Description",audit_esign:"Electronic signature",audit_not_informed:"Not informed",audit_references:"References",audit_security:"Security",audit_trail:"Audit Trail",auth_error:"Error during authentication. Try again.",auth_failed:"Authentication failed. Try again.",auto_login:"Logging in automatically...",back:"Back",bulk_delete_error:"Error deleting items in bulk",bulk_delete_success:"Items deleted successfully",cancel:"Cancel",change_photo:"Change photo",cannot_be_own_leader:"A leader cannot be their own superior",clear_filters:"Clear filters",clear_formatting:"Clear Formatting",clear_search:"Clear search",clear_selection:"Clear selection",close:"Close",collapse_row:"Collapse row",columns:"Columns",conclude:"Finish",confirm_removal:"Confirm removal",could_not_load_info:"Could not load the information",current:"Current",custom_color:"Custom color",dashboard_advanced_filter:"Advanced filter",dashboard_all_access:"All collaborators will have access",dashboard_average:"Average",dashboard_code:"Code",dashboard_distinct_count:"Distinct count",dashboard_edit:"Edit Dashboard",dashboard_exit_fullscreen:"Exit fullscreen",dashboard_export_chart:"Export chart",dashboard_export_table:"Export table",dashboard_max_value:"Maximum value",dashboard_min_value:"Minimum value",dashboard_my:"My dashboards",dashboard_new:"New Dashboard",dashboard_no_data:"The query returned no items for your profile.",dashboard_no_refresh:"Do not refresh",dashboard_normal_page:"Normal page",dashboard_not_shared:"Not shared",dashboard_only_mine:"Only mine",dashboard_only_overdue:"Only overdue",dashboard_only_responsible:"Only the responsible will have access",dashboard_open_query:"Open query",dashboard_remove_favorite:"Remove favorite",dashboard_responsible:"Responsible",dashboard_select_groups:"Select groups, places and specific collaborators",dashboard_shared_unit:"Shared with all unit collaborators",dashboard_status:"Status",dashboard_title:"Title",dashboard_wait_refresh:"Wait to refresh again",dashboard_work_done:"Work done",dashboard_work_planned:"Work planned",deactivate:"Deactivate",deselect_all:"Deselect all",dev_login:"Development Login",download:"Download",edit:"Edit",edit_profile:"Edit Profile",edit_name:"Edit Name",electronic_signature:"Electronic Signature",embed_code:"Embed code",embedded_content:"Embedded content",enter_code:"Enter the code",enter_password:"Enter your password",error_authentication:"Authentication Error",error_connection:"Connection Error",error_copied_clipboard:"Error details were copied to the clipboard.",error_loading:"Error loading",error_loading_data:"Error loading data",error_session_expired:"Session Expired",error_token_expired:"Authentication token expired. Please log in again.",esign_code_description:"A verification code was sent to your email. Enter the code below to confirm the operation.",esign_code_error:"Error validating code. Try again.",esign_invalid_code:"Invalid code. Try again.",esign_invalid_password:"Incorrect password. Try again.",esign_password_description:"Enter your password to confirm the operation.",esign_password_error:"Error validating password. Try again.",esign_resend_error:"Error resending code.",expand_row:"Expand row",expiration_date:"Expiration date",file_error:"File error",file_upload:"File upload",go_to_next_page:"Go to next page",go_to_previous_page:"Go to previous page",group_by_column:"Group by this column",heading_1:"Heading 1",heading_2:"Heading 2",heading_3:"Heading 3",image_description:"Image description",import_flows:"Import Flows",import_manage:"Manage your import flows",inactive:"inactive",inactive_user:"[Inactive user]",input_type:"Input type",invalid_form:"Invalid form. Fill in all required fields.",italic:"Italic",item_details:"Item details",items:"items",items_per_page:"Items per page",know_saber_gestao:"Discover Saber Gestão",know_staff:"Discover Staff",language:"Language",last_update:"Last update",leader:"Leader",leader_create_error:"Error creating leader",leader_not_found:"Leader not found",leader_promoted_success:"Leader promoted successfully",leader_remove_error:"Error removing leader",leader_removed_success:"Leader removed successfully",leader_update_error:"Error updating leader",leader_updated_success:"Leader updated successfully",leadership_add_root:"Add Root Leader",leadership_add_subordinate:"Add Subordinate",leadership_cycle_error:"This association would create a cycle in the hierarchy",leadership_define_leader:"Define Leader",leadership_immediate_superior:"Immediate Superior",leadership_make_root:"Make Root Leader",leadership_make_root_short:"Make Root",leadership_no_hierarchy:"No leadership hierarchy found.",leadership_no_members:"No team members",leadership_no_user_selected:"No user selected",leadership_no_users_available:"No users available",leadership_no_users_found:"No users found",leadership_remove_team:"Remove from team",leadership_select_subordinates:"Select at least one subordinate",learn_qualiex:"Learn how to use Qualiex",leave_without_saving:"Leave without saving",lines_per_page:"Lines per page",link:"Link",login_with_qualiex:"Login with Qualiex",manage_access:"Manage Access",mind_map_add_child:"Add child",mind_map_add_sibling:"Add sibling",mind_map_aria_label:"Mind map",mind_map_collapse_all:"Collapse all",mind_map_delete_node:"Delete node",mind_map_expand_all:"Expand all",mind_map_export_image:"Export as image",mind_map_export_json:"Export as JSON",mind_map_fit_to_screen:"Fit to screen",mind_map_redo:"Redo",mind_map_undo:"Undo",mind_map_zoom_in:"Zoom in",mind_map_zoom_out:"Zoom out",modules:"Modules",more_options:"More options",msg_create_error:"Error creating record",msg_created_success:"Record created successfully",msg_delete_error:"Error deleting record",msg_deleted_success:"Record deleted successfully",msg_load_error:"Error loading data",msg_update_error:"Error updating record",msg_updated_success:"Record updated successfully",new_document:"New Document",new_folder:"New Folder",new_item:"New Item",next:"Next",no_access_page:"It seems you don't have access to this page",no_data_to_display:"No data to display at this time.",no_errors_recorded:"No errors recorded",no_image_selected:"No image selected",no_item_selected:"No item selected",no_items_found:"No items found",no_items_found_empty:"No items found",no_place_found:"No place found",no_place_selected:"No place",no_products:"No products",no_reports_found:"No reports found",no_results:"No results found",no_search_results:"No results for the search",no_video_selected:"No video selected",not_authenticated:"Not authenticated",not_available:"Not available",of:"of",open_popover:"Open Popover",open_wiki:"Open Wiki",ordered_list:"Ordered List",page:"Page",paste_embed_code:"Paste the embed code here",permissions:"Permissions",preset_colors:"Preset colors",preview:"Preview",redirecting_auth:"Redirecting to authentication...",refresh_data:"Refresh data",remove:"Remove",remove_grouping:"Remove grouping",replace:"Replace",report:"Report",request_date:"Request date",required_field:"Required field",resend_code:"Resend code",restricted_access:"Restricted access",rows_per_page:"Rows per page",save:"Save",save_as_draft:"Save as Draft",save_as_template:"Save as Template",saving:"Saving...",search:"Search",search_placeholder:"Search...",search_report_placeholder:"Search report...",search_user_placeholder:"Search user...",select_all:"Select all",select_all_columns:"Select all",select_all_items:"Select all",select_at_least_one:"Select at least one item",select_at_least_one_item:"Select at least one item",select_date:"Select a date",select_file_format:"Select the file format",select_items_to_add:"Select items to add...",select_placeholder:"Select...",selected:"Selected",session_expired:"Your session has expired. You will be redirected to log in again.",sign_access_error:"Error accessing signature service",sign_api_key_info:"Enter the signature provider API Key",sign_api_key_input:"Enter the signature provider API Key",sign_api_key_placeholder:"Enter API key",sign_api_key_required:"API key is required",sign_attempt:"Signature attempt",sign_auth_required:"Authentication required to sign",sign_click_to_select:"Click to select document",sign_config_save_err:"Error saving signature configuration",sign_config_save_error:"Error saving signature configuration",sign_config_saved:"Signature configuration saved",sign_config_saved_success:"Signature configuration saved successfully",sign_configured:"Signature configured",sign_configured_unit:"Digital signature configured for this unit",sign_digital_config:"Digital Signature Configuration",sign_doc_available:"Signed document available for download",sign_doc_load_error:"Error loading document",sign_doc_process_error:"Error processing document",sign_doc_sent:"Document sent for signature",sign_download_signed:"Download signed document",sign_email_fallback:"Signature fallback email",sign_environment:"Signature environment",sign_fetch_failed:"Failed to fetch signed document",sign_file_not_allowed:"File extension not allowed",sign_file_type_not_allowed:"File type not allowed",sign_incorrect_data:"The signer reported incorrect data.",sign_login_required:"Login required to sign",sign_login_to_sign:"Log in to use the digital signature.",sign_monthly_limit:"Monthly signature limit reached",sign_no_access:"Could not obtain access for signing. Try again.",sign_not_configured:"Signature not configured",sign_not_configured_unit:"Digital signature not yet configured for this unit",sign_preparing_doc:"Preparing document for signature",sign_process_error:"Error processing signature",sign_save_config:"Save configuration",sign_save_config_btn:"Save Configuration",sign_select_pdf:"Select a PDF file",sign_sending_doc:"Sending document for signature",sign_signed_success:"Document signed successfully",sign_signer_unavailable:"Signer ID not available",sign_try_again:"Try again",sign_update_config:"Update configuration",sign_update_config_btn:"Update Configuration",sign_waiting_provider:"Waiting for signature provider",sign_widget_error:"Signature widget error",something_went_wrong:"Something went wrong",state:"State",status:"Status",status_completed:"Completed",status_error:"Error",status_expired:"Expired",status_processing:"Processing",status_waiting:"Waiting",steps:"Steps",subordinates_add_error:"Error adding subordinates",subordinates_added_success:"Subordinates added successfully",subordinates_sync_error:"Error syncing subordinates",subordinates_synced_success:"Subordinates synced successfully",team_all_groups:"All groups",terms_confirm_reading:"Confirm reading",terms_confirmation_available:"Confirmation available at",terms_of_use:"Terms of Use",terms_read_agree:"I have read and agree",terms_see_later:"See later",terms_updated:"Terms of Use Updated",terms_view:"View terms of use",terms_view_short:"View term",try_adjust_search:"Try adjusting your search",try_again:"Try Again",unit_not_selected:"No unit selected",unknown_error:"Unknown error",unsaved_changes:"Unsaved changes",unsaved_changes_description:"There are unsaved changes. Do you want to leave without saving?",updates:"Updates",user:"User",user_info:"User Information",user_photo:"User photo",users_already_leaders:"Users are already leaders",verification_code:"Verification code",video:"Video",video_title:"Video title",view_report:"View report",want_to_know_more:"I want to know more",write_content_here:"Write content here..."},fc={actions:"Acciones",activate:"Activar",add_first_item:"Agregue su primer elemento para comenzar",add_item:"Agregar Elemento",advanced_filter:"Filtro avanzado",all:"Todos",allow:"Permitir",allowed_items:"Elementos permitidos",also_discover:"Conozca también",alt_text:"Texto Alternativo",anonymous:"Anónimo",ap_action_plan:"Plan de Acción",ap_action_type:"Tipo de acción",ap_add:"Agregar",ap_add_comment_placeholder:"Agregar comentario...",ap_add_cost:"Agregar costo",ap_add_predecessor:"Agregar predecesor",ap_attachments:"Anexos",ap_belongs_to:"Pertenece a",ap_cause:"Causa",ap_change_status:"Cambiar Estado",ap_checker:"Verificador",ap_clear:"Limpiar",ap_comments:"Comentarios",ap_cost_description:"Descripción del costo",ap_costs:"Costos",ap_delete:"Eliminar",ap_description:"Descripción",ap_description_placeholder:"Describa el plan de acción",ap_duration_days:"Duración (días)",ap_edit_progress:"Editar Progreso",ap_end_date:"Fecha de finalización",ap_estimated_cost:"Costo estimado",ap_file_duplicate:"Archivo duplicado",ap_file_upload_error:"Error al subir archivo",ap_general:"General",ap_general_info:"Información General",ap_history:"Historial",ap_justification:"Justificación",ap_justification_placeholder:"Justificación del plan de acción",ap_name:"Nombre",ap_new_action:"Nueva Acción",ap_no_attachments:"Sin anexos",ap_no_comments:"Sin comentarios",ap_no_costs:"Ningún costo registrado",ap_no_history:"Sin registros en el historial",ap_no_predecessors:"Sin predecesores agregados",ap_no_progress:"Sin datos de progreso disponibles",ap_overall_progress:"Progreso general",ap_place:"Lugar",ap_plan_name_placeholder:"Nombre del plan de acción",ap_predecessors:"Predecesores",ap_priority:"Prioridad",ap_priority_high:"Alta",ap_priority_low:"Baja",ap_priority_medium:"Media",ap_progress:"Progreso",ap_progress_comment_placeholder:"Agregue un comentario sobre el progreso",ap_progress_percent:"Progreso (%)",ap_report:"Reportar",ap_report_progress:"Reportar progreso",ap_reporting:"Reportando...",ap_reports_history:"Historial de reportes",ap_responsible:"Responsable",ap_select_action:"Seleccione una acción",ap_select_cause:"Seleccione la causa",ap_select_checker:"Seleccione el verificador",ap_select_date:"Seleccione la fecha",ap_select_parent:"Seleccione la acción padre",ap_select_place:"Seleccione el lugar",ap_select_priority:"Seleccione la prioridad",ap_select_responsible:"Seleccione el responsable",ap_select_type:"Seleccione el tipo",ap_start_date:"Fecha de inicio",ap_status_canceled:"Cancelada",ap_status_done:"Completada",ap_status_effectiveness_check:"Verificación de eficacia",ap_status_running:"En progreso",ap_status_suspended:"Suspendida",ap_status_waiting_start:"Esperando inicio",ap_time_label:"Tiempo",ap_time_spent:"Tiempo dedicado (HH:MM)",ap_total_cost:"Costo total realizado",ap_total_time:"Tiempo total",ap_type_corrective:"Correctiva",ap_type_immediate:"Inmediata",ap_type_improvement:"Oportunidad de Mejora",ap_type_preventive:"Preventiva",ap_type_standardization:"Estandarización",ap_value:"Valor",ap_via_app:"Vía app",approval_approve:"Aprobar",approval_execute_action:"Ejecutar acción",approval_opinion:"Opinión *",approval_read_less:"Leer menos",approval_read_more:"Leer más",approval_reprove_radio:"Rechazar y retornar a etapa",approval_search_approver:"Buscar aprobador...",approval_select_approver:"Seleccionar aprobador",approval_select_approver_placeholder:"Seleccione un aprobador...",approval_select_step:"Seleccione la etapa",approval_step_label:"Etapa",approval_user_group:"Grupo de usuarios",audit_description:"Descripción",audit_esign:"Firma electrónica",audit_not_informed:"No informado",audit_references:"Referencias",audit_security:"Seguridad",audit_trail:"Pista de Auditoría",auth_error:"Error durante la autenticación. Intente de nuevo.",auth_failed:"Fallo en la autenticación. Intente de nuevo.",auto_login:"Iniciando sesión automáticamente...",back:"Volver",bulk_delete_error:"Error al eliminar elementos en lote",bulk_delete_success:"Elementos eliminados exitosamente",cancel:"Cancelar",change_photo:"Cambiar foto",cannot_be_own_leader:"Un líder no puede ser su propio superior",clear_filters:"Limpiar filtros",clear_formatting:"Limpiar Formato",clear_search:"Limpiar búsqueda",clear_selection:"Limpiar selección",close:"Cerrar",collapse_row:"Contraer fila",columns:"Columnas",conclude:"Concluir",confirm_removal:"Confirmar eliminación",could_not_load_info:"No se pudo cargar la información",current:"Actual",custom_color:"Color personalizado",dashboard_advanced_filter:"Filtro avanzado",dashboard_all_access:"Todos los colaboradores tendrán acceso",dashboard_average:"Promedio",dashboard_code:"Código",dashboard_distinct_count:"Conteo distinto",dashboard_edit:"Editar Dashboard",dashboard_exit_fullscreen:"Salir de pantalla completa",dashboard_export_chart:"Exportar gráfico",dashboard_export_table:"Exportar tabla",dashboard_max_value:"Valor máximo",dashboard_min_value:"Valor mínimo",dashboard_my:"Mis dashboards",dashboard_new:"Nuevo Dashboard",dashboard_no_data:"La consulta no devolvió elementos para su perfil.",dashboard_no_refresh:"No actualizar",dashboard_normal_page:"Página normal",dashboard_not_shared:"No compartido",dashboard_only_mine:"Solo míos",dashboard_only_overdue:"Solo atrasados",dashboard_only_responsible:"Solo el responsable tendrá acceso",dashboard_open_query:"Abrir consulta",dashboard_remove_favorite:"Quitar favorito",dashboard_responsible:"Responsable",dashboard_select_groups:"Seleccione grupos, lugares y colaboradores específicos",dashboard_shared_unit:"Compartido con todos los colaboradores de la unidad",dashboard_status:"Situación",dashboard_title:"Título",dashboard_wait_refresh:"Espere para actualizar nuevamente",dashboard_work_done:"Trabajo ejecutado",dashboard_work_planned:"Trabajo planificado",deactivate:"Desactivar",deselect_all:"Deseleccionar todas",dev_login:"Login Desarrollo",download:"Descargar",edit:"Editar",edit_profile:"Editar Perfil",edit_name:"Editar Nombre",electronic_signature:"Firma Electrónica",embed_code:"Código embed",embedded_content:"Contenido embebido",enter_code:"Ingrese el código",enter_password:"Ingrese su contraseña",error_authentication:"Error de Autenticación",error_connection:"Error de Conexión",error_copied_clipboard:"Los detalles del error se copiaron al portapapeles.",error_loading:"Error al cargar",error_loading_data:"Error al cargar datos",error_session_expired:"Sesión Expirada",error_token_expired:"Token de autenticación expirado. Inicie sesión nuevamente.",esign_code_description:"Un código de verificación fue enviado a su correo. Ingrese el código a continuación para confirmar la operación.",esign_code_error:"Error al validar el código. Intente de nuevo.",esign_invalid_code:"Código inválido. Intente de nuevo.",esign_invalid_password:"Contraseña incorrecta. Intente de nuevo.",esign_password_description:"Ingrese su contraseña para confirmar la operación.",esign_password_error:"Error al validar la contraseña. Intente de nuevo.",esign_resend_error:"Error al reenviar el código.",expand_row:"Expandir fila",expiration_date:"Fecha de expiración",file_error:"Error en el archivo",file_upload:"Subir archivo",go_to_next_page:"Ir a la página siguiente",go_to_previous_page:"Ir a la página anterior",group_by_column:"Agrupar por esta columna",heading_1:"Título 1",heading_2:"Título 2",heading_3:"Título 3",image_description:"Descripción de la imagen",import_flows:"Flujos de Importación",import_manage:"Gestione sus flujos de importación",inactive:"inactivo",inactive_user:"[Usuario inactivo]",input_type:"Tipo de entrada",invalid_form:"Formulario inválido. Complete todos los campos obligatorios.",italic:"Itálica",item_details:"Detalles del elemento",items:"elementos",items_per_page:"Elementos por página",know_saber_gestao:"Conozca Saber Gestión",know_staff:"Conozca Staff",language:"Idioma",last_update:"Última actualización",leader:"Líder",leader_create_error:"Error al crear líder",leader_not_found:"Líder no encontrado",leader_promoted_success:"Líder promovido exitosamente",leader_remove_error:"Error al eliminar líder",leader_removed_success:"Líder eliminado exitosamente",leader_update_error:"Error al actualizar líder",leader_updated_success:"Líder actualizado exitosamente",leadership_add_root:"Agregar Líder Raíz",leadership_add_subordinate:"Agregar Subordinado",leadership_cycle_error:"Esta asociación crearía un ciclo en la jerarquía",leadership_define_leader:"Definir Líder",leadership_immediate_superior:"Superior Inmediato",leadership_make_root:"Hacer Líder Raíz",leadership_make_root_short:"Hacer Raíz",leadership_no_hierarchy:"No se encontró jerarquía de liderazgo.",leadership_no_members:"Ningún miembro en el equipo",leadership_no_user_selected:"Ningún usuario seleccionado",leadership_no_users_available:"Ningún usuario disponible",leadership_no_users_found:"Ningún usuario encontrado",leadership_remove_team:"Quitar del equipo",leadership_select_subordinates:"Seleccione al menos un subordinado",learn_qualiex:"Aprenda a usar Qualiex",leave_without_saving:"Salir sin guardar",lines_per_page:"Líneas por página",link:"Enlace",login_with_qualiex:"Iniciar sesión con Qualiex",manage_access:"Gestionar Accesos",mind_map_add_child:"Agregar hijo",mind_map_add_sibling:"Agregar hermano",mind_map_aria_label:"Mapa mental",mind_map_collapse_all:"Colapsar todo",mind_map_delete_node:"Eliminar nodo",mind_map_expand_all:"Expandir todo",mind_map_export_image:"Exportar como imagen",mind_map_export_json:"Exportar como JSON",mind_map_fit_to_screen:"Ajustar a la pantalla",mind_map_redo:"Rehacer",mind_map_undo:"Deshacer",mind_map_zoom_in:"Acercar",mind_map_zoom_out:"Alejar",modules:"Módulos",more_options:"Más opciones",msg_create_error:"Error al crear registro",msg_created_success:"Registro creado exitosamente",msg_delete_error:"Error al eliminar registro",msg_deleted_success:"Registro eliminado exitosamente",msg_load_error:"Error al cargar datos",msg_update_error:"Error al actualizar registro",msg_updated_success:"Registro actualizado exitosamente",new_document:"Nuevo Documento",new_folder:"Nueva Carpeta",new_item:"Nuevo Elemento",next:"Siguiente",no_access_page:"Parece que no tienes acceso a esta página",no_data_to_display:"No hay datos para mostrar en este momento.",no_errors_recorded:"Sin errores registrados",no_image_selected:"Ninguna imagen seleccionada",no_item_selected:"Ningún elemento seleccionado",no_items_found:"No se encontraron elementos",no_items_found_empty:"Ningún elemento encontrado",no_place_found:"Ningún lugar encontrado",no_place_selected:"Sin lugar",no_products:"Sin productos",no_reports_found:"Ningún informe encontrado",no_results:"No se encontraron resultados",no_search_results:"Sin resultados para la búsqueda",no_video_selected:"Ningún vídeo seleccionado",not_authenticated:"No autenticado",not_available:"No disponible",of:"de",open_popover:"Abrir Popover",open_wiki:"Abrir Wiki",ordered_list:"Lista Ordenada",page:"Página",paste_embed_code:"Pegue el código embed aquí",permissions:"Permisos",preset_colors:"Colores predefinidos",preview:"Vista previa",redirecting_auth:"Redirigiendo a autenticación...",refresh_data:"Actualizar datos",remove:"Eliminar",remove_grouping:"Quitar agrupación",replace:"Reemplazar",report:"Informe",request_date:"Fecha de solicitud",required_field:"Campo obligatorio",resend_code:"Reenviar código",restricted_access:"Acceso restringido",rows_per_page:"Registros por página",save:"Guardar",save_as_draft:"Guardar como Borrador",save_as_template:"Guardar como Plantilla",saving:"Guardando...",search:"Buscar",search_placeholder:"Buscar...",search_report_placeholder:"Buscar informe...",search_user_placeholder:"Buscar usuario...",select_all:"Seleccionar todo",select_all_columns:"Seleccionar todas",select_all_items:"Seleccionar todos",select_at_least_one:"Seleccione al menos un elemento",select_at_least_one_item:"Seleccione al menos un elemento",select_date:"Seleccione una fecha",select_file_format:"Seleccione el formato del archivo",select_items_to_add:"Seleccione elementos para agregar...",select_placeholder:"Seleccionar...",selected:"Seleccionados",session_expired:"Su sesión ha expirado. Será redirigido para iniciar sesión nuevamente.",sign_access_error:"Error al acceder al servicio de firma",sign_api_key_info:"Ingrese la API Key del proveedor de firma",sign_api_key_input:"Ingrese la API Key del proveedor de firma",sign_api_key_placeholder:"Ingrese la clave de API",sign_api_key_required:"Clave de API obligatoria",sign_attempt:"Intento de firma",sign_auth_required:"Autenticación requerida para firmar",sign_click_to_select:"Haga clic para seleccionar documento",sign_config_save_err:"Error al guardar configuración de firma",sign_config_save_error:"Error al guardar configuración de firma",sign_config_saved:"Configuración de firma guardada",sign_config_saved_success:"Configuración de firma guardada exitosamente",sign_configured:"Firma configurada",sign_configured_unit:"Firma digital configurada para esta unidad",sign_digital_config:"Configuración de Firma Digital",sign_doc_available:"Documento firmado disponible para descarga",sign_doc_load_error:"Error al cargar documento",sign_doc_process_error:"Error al procesar documento",sign_doc_sent:"Documento enviado para firma",sign_download_signed:"Descargar documento firmado",sign_email_fallback:"Correo de respaldo para firma",sign_environment:"Ambiente de firma",sign_fetch_failed:"Error al obtener documento firmado",sign_file_not_allowed:"Extensión de archivo no permitida",sign_file_type_not_allowed:"Tipo de archivo no permitido",sign_incorrect_data:"El firmante reportó datos incorrectos.",sign_login_required:"Inicio de sesión requerido para firmar",sign_login_to_sign:"Inicie sesión para usar la firma digital.",sign_monthly_limit:"Límite mensual de firmas alcanzado",sign_no_access:"No se pudo obtener acceso para firma. Intente de nuevo.",sign_not_configured:"Firma no configurada",sign_not_configured_unit:"Firma digital aún no configurada para esta unidad",sign_preparing_doc:"Preparando documento para firma",sign_process_error:"Error al procesar firma",sign_save_config:"Guardar configuración",sign_save_config_btn:"Guardar Configuración",sign_select_pdf:"Seleccione un archivo PDF",sign_sending_doc:"Enviando documento para firma",sign_signed_success:"Documento firmado exitosamente",sign_signer_unavailable:"ID del firmante no disponible",sign_try_again:"Intentar de nuevo",sign_update_config:"Actualizar configuración",sign_update_config_btn:"Actualizar Configuración",sign_waiting_provider:"Esperando proveedor de firma",sign_widget_error:"Error en el widget de firma",something_went_wrong:"Algo salió mal",state:"Estado",status:"Estado",status_completed:"Completado",status_error:"Error",status_expired:"Expirado",status_processing:"Procesando",status_waiting:"Esperando",steps:"Etapas",subordinates_add_error:"Error al agregar subordinados",subordinates_added_success:"Subordinados agregados exitosamente",subordinates_sync_error:"Error al sincronizar subordinados",subordinates_synced_success:"Subordinados sincronizados exitosamente",team_all_groups:"Todos los grupos",terms_confirm_reading:"Confirmar lectura",terms_confirmation_available:"Confirmación disponible en",terms_of_use:"Términos de Uso",terms_read_agree:"He leído y acepto",terms_see_later:"Ver después",terms_updated:"Términos de Uso Actualizados",terms_view:"Ver términos de uso",terms_view_short:"Ver término",try_adjust_search:"Intente ajustar su búsqueda",try_again:"Intentar de Nuevo",unit_not_selected:"Ninguna unidad seleccionada",unknown_error:"Error desconocido",unsaved_changes:"Cambios sin guardar",unsaved_changes_description:"Hay cambios sin guardar. ¿Desea salir sin guardar?",updates:"Actualizaciones",user:"Usuario",user_info:"Información del Usuario",user_photo:"Foto del usuario",users_already_leaders:"Los usuarios ya son líderes",verification_code:"Código de verificación",video:"Video",video_title:"Título del vídeo",view_report:"Ver informe",want_to_know_more:"Quiero conocer más",write_content_here:"Escriba el contenido aquí..."};const gc="true"===import.meta.env.VITE_I18N_DEBUG_MODE;function vc(a,t){e.addResourceBundle(a,"app",t,!0,!0)}gc&&e.use({type:"postProcessor",name:"debugKeys",process:(e,a)=>`🔑 ${Array.isArray(a)?a[0]:a}`}),e.use(Ka).init({resources:{"pt-BR":{core:pc},"en-US":{core:hc},"es-ES":{core:fc}},fallbackLng:"pt-BR",lng:"pt-BR",defaultNS:"app",fallbackNS:"core",ns:["core"],interpolation:{escapeValue:!1},react:{useSuspense:!1},saveMissing:!1,returnEmptyString:!1,parseMissingKeyHandler:e=>e,postProcess:gc?["debugKeys"]:[]});const bc=d(void 0),xc={locale:hi,timezone:gi,datetimeFormat:fi},yc=async()=>{},Nc=({children:e})=>a(bc.Provider,{value:{...xc,setLocale:yc,setTimezone:yc,setDatetimeFormat:yc,isLoading:!1},children:e}),wc=()=>{const e=c(bc);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},_c=d({moduleAlias:null});function Cc({moduleAlias:e=null,children:t}){return a(_c.Provider,{value:{moduleAlias:e},children:t})}function kc(){return c(_c)}const Sc=pt.Root,Ac=pt.CollapsibleTrigger,Ec=pt.CollapsibleContent;class Dc extends h{constructor(a){super(a),this.copyErrorDetails=()=>{const a=Qs.getErrors().slice(0,2),t=`\n=== ERRO ATUAL ===\n${this.state.error?.message||e.t("unknown_error")}\n\nStack Trace:\n${this.state.error?.stack||e.t("not_available")}\n\n=== ÚLTIMOS ERROS ===\n${a.map((e,a)=>`${a+1}. [${new Date(e.timestamp).toLocaleTimeString()}] ${e.message}`).join("\n")||e.t("no_errors_recorded")}\n `.trim();navigator.clipboard.writeText(t),C.success("Detalhes copiados!",{description:e.t("error_copied_clipboard")})},this.state={hasError:!1,showDetails:!1}}static getDerivedStateFromError(e){if(import.meta.env.DEV)throw e;return{hasError:!0,error:e}}componentDidCatch(e,a){if(import.meta.env.DEV)throw e;Qs.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const r=Qs.getErrors().slice(0,2);return a("div",{className:"flex items-center justify-center min-h-screen p-4",children:t(Gi,{className:"w-full max-w-2xl",children:[t(Ki,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(de,{className:"h-12 w-12 text-destructive"})}),a(Yi,{children:e.t("something_went_wrong")})]}),t(Xi,{className:"space-y-4",children:[a("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),t(Sc,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[a(Ac,{asChild:!0,children:t($i,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[a(D,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),t(Ec,{className:"mt-4 space-y-4",children:[t("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[t("div",{children:[a("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📋 Erro Atual"}),t("div",{className:"text-sm space-y-2",children:[a("p",{className:"font-medium text-destructive",children:this.state.error?.message||e.t("unknown_error")}),this.state.error?.stack&&a(Dd,{className:"h-32 w-full rounded border bg-muted p-2",children:a("pre",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:this.state.error.stack})})]})]}),r.length>0&&t("div",{className:"pt-3 border-t",children:[a("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:"📜 Últimos Erros"}),a("div",{className:"space-y-2",children:r.map((e,r)=>a("div",{className:"text-sm p-2 rounded bg-muted/50",children:t("div",{className:"flex items-start gap-2",children:[t("span",{className:"font-medium text-muted-foreground shrink-0",children:[r+1,"."]}),t("div",{className:"flex-1 min-w-0",children:[a("div",{className:"flex items-center gap-2 flex-wrap",children:t("span",{className:"text-xs text-muted-foreground",children:["[",new Date(e.timestamp).toLocaleTimeString(),"]"]})}),a("p",{className:"text-sm break-words",children:e.message})]})]})},e.id))})]})]}),t($i,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[a(me,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),a($i,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Pc=ht.Root,Ic=n.forwardRef(({className:e,...t},r)=>a(ht.List,{ref:r,className:Fi("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),...t}));Ic.displayName=ht.List.displayName;const Tc=n.forwardRef(({className:e,...t},r)=>a(ht.Trigger,{ref:r,className:Fi("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}));Tc.displayName=ht.Trigger.displayName;const Rc=n.forwardRef(({className:e,...t},r)=>a(ht.Content,{ref:r,className:Fi("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));function Mc({className:e}){return t("svg",{className:e,width:"32",height:"34",viewBox:"0 0 32 34",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a("path",{d:"M0.5 11.7455C0.5 10.2633 2.25695 9.52546 3.36816 10.4399L22.4346 26.1528C23.3588 26.9137 23.229 28.3353 22.1953 28.9301L16.3418 32.2963C15.7961 32.6097 15.1199 32.6098 14.5742 32.2963L1.36133 24.7006C0.832671 24.3966 0.500052 23.8398 0.5 23.2289V11.7455Z",stroke:"currentColor"}),a("path",{d:"M14.612 0.735352C15.1576 0.421927 15.833 0.421964 16.3786 0.735352L25.3776 5.90723V5.9082C26.5447 6.5808 26.5183 8.24018 25.3298 8.875L25.3307 8.87598L13.9333 14.9697L13.9323 14.9688C13.3016 15.3066 12.5233 15.2301 11.9733 14.7773L4.90302 8.9541C3.97881 8.19317 4.1086 6.77256 5.14227 6.17773L14.612 0.735352Z",stroke:"currentColor"}),a("path",{d:"M28.1066 9.7966C29.2466 9.18579 30.6895 9.9732 30.6896 11.2937V23.0691C30.6895 23.6825 30.3539 24.2382 29.8264 24.5417L29.8254 24.5427L27.3449 25.9607C26.7486 26.3015 26.0057 26.264 25.4494 25.8747L25.341 25.7917L16.6076 18.5974C15.6649 17.821 15.8224 16.3676 16.8937 15.7937V15.7927L28.1066 9.79758V9.7966Z",stroke:"currentColor"})]})}function Lc({className:e}){return t("svg",{className:e,width:"18",height:"33",viewBox:"0 0 18 33",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a("path",{d:"M0.524143 8.74979C1.44754 8.74979 2.36325 8.74979 3.30973 8.74979C3.30973 8.90069 3.30973 9.05162 3.30973 9.19497C3.30973 9.79101 3.64061 10.1154 4.24082 10.1154C6.8879 10.1154 9.54268 10.1154 12.1898 10.1154C12.7592 10.1154 13.1286 9.77589 13.1132 9.27793C13.0978 8.8856 12.8054 8.5612 12.3745 8.51594C11.2279 8.38767 10.0736 8.26696 8.91938 8.1387C7.72666 8.01043 6.52625 7.88216 5.33352 7.74635C4.71792 7.67845 4.10232 7.61811 3.48672 7.53511C2.00928 7.32386 0.754978 6.06386 0.547213 4.61526C0.331752 3.10631 1.00122 1.73316 2.34015 0.963593C2.89419 0.646712 3.5021 0.503353 4.14848 0.503353C6.84943 0.503353 9.55038 0.495808 12.2513 0.503353C14.0904 0.510898 15.5448 1.71808 15.8603 3.49865C15.8988 3.7099 15.8988 3.92116 15.9065 4.13996C15.9141 4.2984 15.9065 4.44928 15.9065 4.61526C14.9677 4.61526 14.0443 4.61526 13.0978 4.61526C13.0978 4.44928 13.0978 4.28329 13.0978 4.1173C13.0901 3.58162 12.7592 3.25719 12.2206 3.24965C9.53499 3.24965 6.84943 3.24965 4.17157 3.24965C3.69448 3.24965 3.36359 3.52881 3.30203 3.97396C3.24816 4.3512 3.51749 4.73597 3.90224 4.8265C4.10231 4.87177 4.31008 4.88687 4.51784 4.9095C5.8183 5.05285 7.12645 5.19622 8.42691 5.33957C9.71198 5.48292 10.997 5.63382 12.2898 5.75453C13.1824 5.83753 13.9981 6.08649 14.6906 6.68253C16.1604 7.92742 16.3066 10.2588 14.9984 11.6696C14.2443 12.4845 13.3132 12.8844 12.1975 12.8844C9.5273 12.8844 6.84944 12.8844 4.17927 12.8844C2.55562 12.8844 1.21669 11.9563 0.678043 10.4549C0.539533 9.98715 0.470277 9.38356 0.524143 8.74979Z",stroke:"currentColor"}),a("path",{d:"M8.21913 24.2393C8.21913 24.2317 8.21913 24.2317 8.21913 24.2393ZM8.21913 24.2393C8.98863 24.2393 9.75812 24.2619 10.5199 24.2317C11.7511 24.1789 12.9285 23.1378 13.067 21.9381C13.1439 21.3119 13.1285 20.6706 13.1131 20.0368C13.067 18.6335 11.8743 17.4339 10.443 17.3962C8.96554 17.3584 7.4881 17.366 6.00296 17.3962C4.70251 17.4263 3.54055 18.4373 3.37896 19.6973C3.29431 20.3462 3.3097 21.0101 3.34048 21.6665C3.40204 23.017 4.58708 24.1789 5.96449 24.2317C6.7186 24.2619 7.46502 24.2393 8.21913 24.2393ZM13.1439 15.427C13.7441 14.8385 14.3367 14.2575 14.9138 13.6917C15.5756 14.333 16.2296 14.9818 16.9222 15.6608C16.8914 15.6759 16.8298 15.7061 16.7837 15.7438C16.2604 16.2493 15.7448 16.7624 15.2216 17.2679C15.1446 17.3434 15.1369 17.4037 15.1908 17.4943C15.7064 18.3845 15.9526 19.3427 15.9295 20.3613C15.9141 20.9799 15.9526 21.6062 15.8603 22.2097C15.5371 24.2846 14.352 25.7332 12.3975 26.5782C11.7126 26.8724 10.9816 26.9931 10.2352 26.9931C8.89629 26.9931 7.56504 26.9931 6.22611 26.9931C3.49438 26.9931 1.20897 25.1899 0.631845 22.5719C0.56259 22.2475 0.524115 21.9155 0.51642 21.5835C0.508725 20.9422 0.470242 20.2933 0.547192 19.6596C0.816518 17.3584 2.08619 15.7967 4.27927 14.9516C4.84101 14.7328 5.42584 14.6347 6.02605 14.6347C7.4958 14.6347 8.96554 14.6272 10.4276 14.6423C11.3279 14.6498 12.1667 14.9064 12.9516 15.3289C13.0131 15.3591 13.067 15.3892 13.1439 15.427Z",stroke:"currentColor"}),a("path",{d:"M0.508791 28.3813C1.43989 28.3813 2.3633 28.3813 3.2944 28.3813C3.31748 28.4945 3.32516 28.6001 3.35594 28.7058C3.50984 29.2943 4.01772 29.7017 4.63332 29.7319C4.76414 29.7394 4.89496 29.7394 5.02578 29.7394C7.22655 29.7394 9.4273 29.7394 11.6281 29.7394C12.3206 29.7394 12.8439 29.3923 13.0363 28.7963C13.0747 28.668 13.0978 28.5323 13.1286 28.3889C14.0443 28.3889 14.9677 28.3889 15.9142 28.3889C15.9219 28.7435 15.868 29.0906 15.7757 29.4301C15.2986 31.1955 13.6519 32.4782 11.7897 32.4857C9.39653 32.5008 7.01108 32.5083 4.61794 32.4857C2.44025 32.4706 0.624216 30.7353 0.508791 28.6077C0.501096 28.5322 0.508791 28.4643 0.508791 28.3813Z",stroke:"currentColor"})]})}Rc.displayName=ht.Content.displayName;const zc={init(e){!function(e){try{return void function(e,a,t,r,n,i,o){a.getElementById("clarity-script")||(e[t]=e[t]||function(){(e[t].q=e[t].q||[]).push(arguments)},(i=a.createElement(r)).async=1,i.src="https://www.clarity.ms/tag/"+n+"?ref=npm",i.id="clarity-script",(o=a.getElementsByTagName(r)[0]).parentNode.insertBefore(i,o))}(window,document,"clarity","script",e)}catch(a){return}}(e)},setTag(e,a){window.clarity("set",e,a)},identify(e,a,t,r){window.clarity("identify",e,a,t,r)},consent(e=!0){window.clarity("consent",e)},consentV2(e={ad_Storage:"granted",analytics_Storage:"granted"}){window.clarity("consentv2",e)},upgrade(e){window.clarity("upgrade",e)},event(e){window.clarity("event",e)}},Fc="forlogic_";function Uc(){return"undefined"!=typeof window&&"function"==typeof window.clarity}function jc(){return"undefined"!=typeof window&&"piggyback"===window.__forlogicClarityMode}function Oc(e){return jc()?`${Fc}${e}`:e}function Bc(e){return jc()?`${Fc}${e}`:e}function $c(e){try{e()}catch(a){import.meta.env.DEV}}function Vc(e){for(const[a,t]of Object.entries(e))null!=t&&""!==t&&zc.setTag(Bc(a),t)}function qc({module:e,isContracted:a,sourceModule:t,alias:r}){Uc()&&$c(()=>{Vc({clicked_module:e.name,clicked_module_id:e.softwareAlias,is_contracted:String(a),source_module:t,alias:r}),zc.event(Oc("module_menu_click"))})}function Wc({module:e,sourceModule:a,alias:t}){Uc()&&$c(()=>{Vc({clicked_module:e.name,clicked_module_id:e.softwareAlias,is_contracted:"false",source_module:a,alias:t}),zc.event(Oc("module_interest_click"))})}function Hc({resource:e,sourceModule:a,alias:t}){Uc()&&$c(()=>{Vc({footer_resource:e,source_module:a,alias:t}),zc.event(Oc("module_footer_click"))})}function Gc({educaUrl:e="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n,alias:i,sourceModule:o}){const{t:s}=Ga(),l=zi(e||n||"https://educacao.sabergestao.com.br/{alias}/fe",i),d=e=>{Hc({resource:e,sourceModule:o,alias:i})};return t("div",{className:"flex-shrink-0 pt-4",children:[a(Zi,{className:"mb-4"}),t("div",{className:"grid grid-cols-1 min-[480px]:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3",children:[t("div",{className:"bg-primary text-primary-foreground rounded-lg p-4 relative overflow-hidden",children:[t("div",{className:"relative z-10",children:[a("h4",{className:"font-semibold text-sm text-white",children:s("learn_qualiex")}),t("a",{href:l,target:"_blank",rel:"noopener noreferrer",onClick:()=>d("educa"),className:"inline-flex items-center gap-1 text-sm text-white underline underline-offset-2 hover:opacity-80 mt-2",children:["Conheça o ForLogic Educa",a(pe,{className:"h-3.5 w-3.5"})]})]}),a(Mc,{className:"absolute right-2 bottom-2 w-16 h-16 text-[#043481] pointer-events-none"})]}),t("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[t("div",{className:"relative z-10",children:[a("h4",{className:"font-semibold text-sm text-foreground",children:s("know_saber_gestao")}),t("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:()=>d("saber-gestao"),className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",a(pe,{className:"h-3.5 w-3.5"})]})]}),a(Lc,{className:"absolute right-2 bottom-2 w-12 h-16 text-[#E0E0E0] pointer-events-none"})]}),t("div",{className:"bg-muted rounded-lg p-4 relative overflow-hidden",children:[t("div",{className:"relative z-10",children:[a("h4",{className:"font-semibold text-sm text-foreground",children:"Dúvidas sobre os módulos?"}),t("a",{href:n||"https://wiki.qualiex.com/",target:"_blank",rel:"noopener noreferrer",onClick:()=>d("wiki"),className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Consulte nossa Wiki",a(pe,{className:"h-3.5 w-3.5"})]})]}),a(he,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}const Kc=[{id:"qualiex",label:"Qualiex",modules:[{name:"Análises",description:"Análise de dados",color:"bg-[#002338]",softwareAlias:"analysis",url:"https://apps4.qualiex.com/analysis/{alias}"},{name:"Atas e Decisões",description:"Gestão de atas e decisões",color:"bg-[#7DB3B2]",softwareAlias:"decisions",url:"https://apps4.qualiex.com/decisions/{alias}"},{name:"Auditorias",description:"Gestão de auditorias",color:"bg-[#912F71]",softwareAlias:"audit",url:"https://apps4.qualiex.com/audit/{alias}"},{name:"Configurações",description:"Configurações gerais",color:"bg-[#5C6BC0]",softwareAlias:"common",url:"https://apps4.qualiex.com/common/{alias}"},{name:"Documentos",description:"Gestão de documentos",color:"bg-[#1D43A6]",softwareAlias:"docs",url:"https://apps4.qualiex.com/docs/{alias}"},{name:"Fluxos",description:"Gestão de fluxos",color:"bg-[#8BFFE0]",softwareAlias:"flow",url:"https://apps4.qualiex.com/flow/{alias}"},{name:"Fornecedores",description:"Gestão de fornecedores",color:"bg-[#5C5094]",softwareAlias:"suppliers",url:"https://apps4.qualiex.com/suppliers/{alias}"},{name:"Mapeamentos",description:"Mapeamento de dados pessoais",color:"bg-[#62416B]",softwareAlias:"mapping",url:"https://apps4.qualiex.com/mapping/{alias}"},{name:"Metrologia",description:"Gestão de metrologia",color:"bg-[#8CC74F]",softwareAlias:"metrology",url:"https://apps4.qualiex.com/metrology/{alias}"},{name:"Ocorrências",description:"Gestão de ocorrências",color:"bg-[#EE7121]",softwareAlias:"occurrences",url:"https://apps4.qualiex.com/occurrences/{alias}"},{name:"OKR",description:"Objetivos e resultados-chave",color:"bg-[#4A90D9]",softwareAlias:"okr",url:"https://okr.qualiex.com/{alias}"},{name:"Planos",description:"Planos de ação",color:"bg-[#FBC02D]",softwareAlias:"plans",url:"https://apps4.qualiex.com/plans/{alias}"},{name:"Portal do Fornecedor",description:"Portal do Fornecedor",color:"bg-[#26A69A]",softwareAlias:"suppliers-portal",url:"https://portaldofornecedor.qualiex.com/{alias}"},{name:"Riscos",description:"Gestão de riscos",color:"bg-[#ED7096]",softwareAlias:"risks",url:"https://apps4.qualiex.com/risks/{alias}"},{name:"Competências",description:"Gestão de competências",color:"bg-[#9B4F96]",softwareAlias:"competencies",url:"https://competencias.sabergestao.com.br/{alias}"},{name:"Desempenho",description:"Gestão de desempenho",color:"bg-[#4A90D9]",softwareAlias:"performance",url:"https://desempenho.sabergestao.com.br/{alias}"},{name:"Educação",description:"Plataforma de ensino",color:"bg-[#00BCD4]",softwareAlias:"education",url:"https://educacao.sabergestao.com.br/{alias}"},{name:"PDI",description:"Plano de desenvolvimento individual",color:"bg-[#7CB342]",softwareAlias:"pdi",url:"https://pdi.sabergestao.com.br/{alias}"},{name:"Pulso",description:"Pesquisas de clima",color:"bg-[#F5A623]",softwareAlias:"pulse",url:"https://nr1pulso.sabergestao.com.br/{alias}"},{name:"Treinamentos",description:"Gestão de treinamentos",color:"bg-[#26A69A]",softwareAlias:"staff",url:"https://treinamentos.sabergestao.com.br/{alias}"}]},{id:"classico",label:"Clássicos",modules:[{name:"Action",description:"Planos de ação",color:"bg-[#fbe356]",url:"https://apps1.qualiex.com/action?unitalias={alias}"},{name:"Audit",description:"Gestão de auditorias",color:"bg-[#ca76b5]",url:"https://apps1.qualiex.com/audit?unitalias={alias}"},{name:"Configurações v3",description:"Configurações",color:"bg-[#5C6BC0]",url:"https://apps3.qualiex.com/{alias}/common"},{name:"Dashboards v1",description:"Dashboards",color:"bg-[#EC407A]",url:"https://apps1.qualiex.com/shared/dashboard?unitalias={alias}"},{name:"Docs v1",description:"Gestão de Documentos",color:"bg-[#58b4db]",url:"https://apps1.qualiex.com/docs?unitalias={alias}"},{name:"Indicators",description:"Gestão de Indicadores",color:"bg-[#f91b1d]",url:"https://apps1.qualiex.com/indicators?unitalias={alias}"},{name:"Meeting",description:"Gestão de reuniões",color:"bg-[#96c2c1]",url:"https://apps1.qualiex.com/meeting?unitalias={alias}"},{name:"Metrology v3",description:"Gestão de Metrologia",color:"bg-[#afd884]",url:"https://apps3.qualiex.com/{alias}/metrology/"},{name:"Planner",description:"Planejamento estratégico",color:"bg-[#4dc6f4]",url:"https://apps3.qualiex.com/{alias}/planner/m"},{name:"Relatórios v1",description:"Relatórios",color:"bg-[#FFA726]",url:"https://apps1.qualiex.com/common/reports?unitalias={alias}"},{name:"Risks",description:"Gestão de riscos",color:"bg-[#ef7b9e]",url:"https://apps1.qualiex.com/risks?unitalias={alias}"},{name:"Staff",description:"Avaliação de competências",color:"bg-[#0978d6]",url:"https://apps1.qualiex.com/staff?unitalias={alias}"},{name:"Supply",description:"Avaliação de fornecedores",color:"bg-[#8276b7]",url:"https://apps1.qualiex.com/supply?unitalias={alias}"},{name:"Tracker1",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker1?unitalias={alias}"},{name:"Tracker2",description:"Gestão de ocorrências",color:"bg-[#fe883b]",url:"https://apps1.qualiex.com/tracker2?unitalias={alias}"}]}];function Yc({module:e,onClick:r}){return t("button",{type:"button",onClick:r,className:"flex items-start gap-3 p-2 rounded-lg transition-colors text-left w-full group hover:bg-muted/50",children:[a("div",{className:Fi("w-4 h-4 rounded-sm shrink-0 mt-0.5",e.color)}),t("div",{className:"min-w-0",children:[a("div",{className:"font-medium transition-colors text-foreground group-hover:text-primary",children:e.name}),e.description&&a("div",{className:"text-sm text-muted-foreground truncate",children:e.description})]})]})}function Qc(e,a){if(0===e.length)return e;const t=Math.ceil(e.length/a),r=[];for(let n=0;n<t;n++)for(let i=0;i<a;i++){const a=i*t+n;a<e.length&&r.push(e[a])}return r}function Xc({modules:e,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const s=function(){const[e,a]=o(4);return m(()=>{const e=()=>{window.matchMedia("(min-width: 1280px)").matches?a(4):window.matchMedia("(min-width: 768px)").matches?a(3):window.matchMedia("(min-width: 640px)").matches?a(2):a(1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),e}(),l=[...e].sort((e,a)=>e.name.localeCompare(a.name)),d=void 0!==n,c=d?l.filter(e=>n.includes(e.name)):l,u=d?l.filter(e=>!n.includes(e.name)):[],p=Qc(c,s),h=Qc(u,s),f=(e,a)=>{a?r?.(e):i?.(e)};return t("div",{className:"space-y-6",children:[p.length>0&&a("section",{children:a("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:p.map(e=>a(Yc,{module:e,onClick:()=>f(e,!0)},e.name))})}),h.length>0&&t("section",{className:"bg-neutral-100 dark:bg-neutral-800 rounded-lg p-4 mt-4",children:[a("h3",{className:"text-sm font-medium text-muted-foreground mb-3",children:"Conheça também"}),a("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-1",children:h.map(e=>a(Yc,{module:e,onClick:()=>f(e,!1)},e.name))})]})]})}function Jc({onModuleClick:e,contractedModules:r,onModuleInterest:n,nonContractedUrl:i="https://qualiex.com/",educaUrl:s="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:d,alias:c,sourceModule:u}){const[m,p]=o("qualiex"),h=e=>{Wc({module:e,sourceModule:u,alias:c}),window.open(i,"_blank","noopener,noreferrer"),n?.(e)};return t("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[t(Pc,{value:m,onValueChange:p,className:"flex-1 flex flex-col min-h-0",children:[a(Ic,{className:"w-fit shrink-0",children:Kc.map(e=>t(Tc,{value:e.id,children:[e.label,t("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),Kc.map(t=>a(Rc,{value:t.id,className:"flex-1 mt-4 overflow-auto pr-2",children:a(Xc,{modules:t.modules,onModuleClick:a=>{return n=a,i=t.id,qc({module:n,isContracted:"qualiex"!==i||!r||r.includes(n.name),sourceModule:u,alias:c}),void e?.(n);var n,i},contractedModules:"qualiex"===t.id?r:void 0,onModuleInterest:h})},t.id))]}),a(Gc,{educaUrl:s,saberGestaoUrl:l,wikiUrl:d,alias:c,sourceModule:u})]})}const Zc={analysis:12,decisions:13,audit:1,common:0,competencies:23,performance:24,docs:17,education:25,flow:7,suppliers:15,"suppliers-portal":16,mapping:11,metrology:8,control:18,msa:21,occurrences:3,okr:26,pdi:27,plans:6,"strategy-extension":14,pulse:28,boards:10,risks:4,fmea:20,staff:19,"control-plan":22},eu=6e5;function au(e){const{moduleAlias:a}=kc(),{alias:t,user:r,isAuthenticated:n}=kl(),i=e??a,o=r?.id??null,d=n&&!!t&&!!o,{data:c=[],isLoading:u}=Ja({queryKey:["qualiex-associations",o,t],queryFn:()=>ll.fetchUserAssociations(o,t),enabled:d,staleTime:eu,gcTime:12e5}),m=s(()=>t&&0!==c.length?c.find(e=>e.companyAlias===t)??null:null,[c,t]),p=l(e=>{if(!m)return!1;return(Array.isArray(e)?e:[e]).every(e=>{const a=Zc[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:s(()=>!i||p(i),[i,p]),isLoading:d&&u,role:s(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:p}}function tu(e){const{association:a}=au();return s(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=Kc.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=Zc[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function ru({open:e,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:d,sourceModule:c}){const{alias:u}=kl(),m=tu(i);return a(mo,{open:e,onOpenChange:r,children:t(bo,{size:"lg",className:"overflow-hidden flex flex-col",children:[a(xo,{className:"sr-only",children:a(wo,{children:"Módulos"})}),a(Jc,{onModuleClick:e=>{n?n(e):e.url&&Li(zi(e.url,u||void 0))},contractedModules:m,onModuleInterest:o,educaUrl:s,saberGestaoUrl:l,wikiUrl:d,alias:u||void 0,sourceModule:c})]})})}function nu({open:r,onOpenChange:n,onModuleClick:i,contractedModules:o,onModuleInterest:l,userName:d,unitName:c,units:u=[],currentAlias:m,onUnitChange:p,onLogout:h,educaUrl:f,saberGestaoUrl:g,wikiUrl:v,blocking:b=!0,size:x="lg",children:y,sourceModule:N}){const{t:w}=Ga(),_=s(()=>{if(!u.length)return[];const e=new Map;u.forEach(a=>e.set(a.alias,a));const a=Array.from(e.values()),t=a.find(e=>e.alias===m),r=a.filter(e=>e.alias!==m).sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"}));return t?[t,...r]:r},[u,m]);return a(mo,{open:r,onOpenChange:b?void 0:n,children:t(bo,{size:x,variant:"destructive",className:"overflow-hidden flex flex-col max-h-[85vh]",onPointerDownOutside:b?e=>e.preventDefault():void 0,onEscapeKeyDown:b?e=>e.preventDefault():void 0,children:[t("div",{className:"flex items-start justify-between gap-4 flex-shrink-0",children:[t("div",{className:"flex flex-col gap-1.5 text-left",children:[a(wo,{children:w("no_access_page")}),a(_o,{children:"Selecione um módulo para continuar navegando!"})]}),t("div",{className:"flex items-center gap-2 shrink-0",children:[_.length>1&&t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[a(fe,{className:"h-4 w-4 shrink-0"}),a("span",{className:"truncate text-xs",children:c||"Unidade"}),a(D,{className:"h-3 w-3 shrink-0"})]})}),a(os,{align:"end",className:"max-h-[300px] overflow-auto",children:_.map(e=>t(ss,{onClick:()=>p?.(e),className:e.alias===m?"bg-muted":"",children:[a(fe,{className:"mr-2 h-4 w-4 shrink-0"}),a("span",{className:"truncate",children:e.name}),e.alias===m&&a(Go,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},e.alias))})]}),t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"ghost",size:"sm",className:"gap-2",children:[a("div",{className:"w-7 h-7 bg-primary rounded-full flex items-center justify-center",children:a(ge,{className:"h-3.5 w-3.5 text-primary-foreground"})}),a(D,{className:"h-3 w-3"})]})}),t(os,{align:"end",children:[t("div",{className:"px-2 py-1.5",children:[a("p",{className:"text-sm font-medium",children:d||e.t("user")}),a("p",{className:"text-xs text-muted-foreground",children:c})]}),a(us,{}),t(ss,{onClick:h,children:[a(ve,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})]})]}),y?t("div",{className:"flex-1 min-h-0 overflow-auto flex flex-col",children:[a("div",{className:"flex-1",children:y}),a(Gc,{educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m,sourceModule:N})]}):a(Jc,{onModuleClick:i,contractedModules:o,onModuleInterest:l,educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m,sourceModule:N})]})})}function iu(e,a){const{t:t}=Ga();return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function ou({children:e,contractedModules:t,onModuleClick:n,onModuleInterest:i,educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:d="https://sabergestao.com.br/",wikiUrl:c,bypassPaths:u,accessDeniedRoutes:m,sourceModule:p}){const{t:h}=Ga(),{hasAccess:f,isLoading:g,association:v}=au(),{user:b,alias:x,companies:y,isAuthenticated:N,isLoading:w,logout:_,switchUnit:C}=kl(),k=tu(t),S=s(()=>y?.length?x&&y.find(e=>e.alias===x)||y[0]:null,[y,x]),A=s(()=>y?.length?y.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[y]),E=l(e=>{const a=y?.find(a=>a.alias===e.alias);if(!a)return;const{pathname:t,search:r,hash:n}=window.location;if(x){const e=t.split("/"),i=e.indexOf(x);if(i>=0)return e[i]=a.alias,void(window.location.href=e.join("/")+r+n)}C(a)},[x,C,y]),D=l(e=>{n?n(e):e.url&&Li(zi(e.url,x||void 0))},[n,x]),P=s(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>iu(e,[a]));return a?m[a]:void 0},[m]);return w||!N||u?.length&&iu(window.location.pathname,u)?a(r,{children:e}):g?a("div",{className:"flex items-center justify-center min-h-screen",children:a(Yo,{size:"lg"})}):f?a(r,{children:e}):a(nu,{open:!0,onModuleClick:D,contractedModules:k,onModuleInterest:i,userName:b?.name,unitName:S?.name,units:A,currentAlias:x||void 0,onUnitChange:E,onLogout:_,educaUrl:o,saberGestaoUrl:d,wikiUrl:c,sourceModule:p,blocking:!0,children:P})}function su({title:e,description:r,image:n,icon:i,ctaLabel:o,onCtaClick:s,children:l}){const{t:d}=Ga(),c=o??d("want_to_know_more");return t("div",{className:"flex flex-col items-center text-center gap-6 py-8 px-4",children:[!l&&(n||i)&&a("div",{className:"flex items-center justify-center",children:n?a("img",{src:n,alt:e,className:"max-h-48 w-auto object-contain rounded-lg"}):i?a("div",{className:"w-24 h-24 rounded-2xl bg-primary/10 flex items-center justify-center",children:a(i,{className:"h-12 w-12 text-primary"})}):null}),t("div",{className:"space-y-3 max-w-lg",children:[a("h3",{className:"text-xl font-semibold text-foreground",children:e}),a("p",{className:"text-sm text-muted-foreground leading-relaxed",children:r})]}),l?a("div",{className:"w-full",children:l}):s?t($i,{onClick:s,size:"lg",className:"gap-2",children:[a(be,{className:"h-4 w-4"}),c]}):null]})}let lu=!1;function du(){if(lu||"undefined"==typeof document)return;lu=!0;for(const a of["https://fonts.googleapis.com","https://fonts.gstatic.com"])if(!document.querySelector(`link[href="${a}"]`)){const e=document.createElement("link");e.rel="preconnect",e.href=a,a.includes("gstatic")&&(e.crossOrigin="anonymous"),document.head.appendChild(e)}const e=["https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap","https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200&display=swap"];for(const a of e)if(!document.querySelector(`link[href="${a}"]`)){const e=document.createElement("link");e.rel="stylesheet",e.href=a,document.head.appendChild(e)}}function cu({projectId:e,mode:a="auto"}){const{user:t,alias:r,isAuthenticated:n}=kl();m(()=>{if("undefined"!=typeof window&&"disabled"!==a&&e&&!vr()&&!window.__forlogicClarityOwned)if("function"!=typeof window.clarity)try{zc.init(e),window.__forlogicClarityOwned=!0,window.__forlogicClarityMode="owned"}catch(t){import.meta.env.DEV,window.__forlogicClarityMode="inactive"}else window.__forlogicClarityMode="piggyback"},[e,a]),m(()=>{if("undefined"!=typeof window&&"disabled"!==a&&n&&t&&"function"==typeof window.clarity)try{const e=t.email||t.identifier||"anonymous";zc.identify(e,void 0,"modules-menu",t.name||void 0),r&&zc.setTag("alias",r),"boolean"==typeof t.isSysAdmin&&zc.setTag("isSysAdmin",String(t.isSysAdmin))}catch(e){import.meta.env.DEV}},[t,r,n,a])}function uu({children:r,queryClient:n,moduleAlias:o,moduleAccessGuardProps:s,appTranslations:l,clarityProjectId:d,clarityMode:c="auto"}){du();const[u]=i.useState(()=>new et({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),m=n??u;i.useEffect(()=>{if(l)for(const[e,a]of Object.entries(l))vc(e,a)},[l]);const p={sourceModule:o,...s};return t(Dc,{children:[a(pu,{}),a(Ya,{i18n:e,children:a(at,{client:m,children:t(Cl,{children:[a(mu,{projectId:d,mode:c}),a(Nc,{children:a(Cc,{moduleAlias:o,children:a(ou,{...p,children:r})})})]})})})]})}function mu({projectId:e,mode:a}){return cu({projectId:e,mode:a}),null}function pu(){const e=Xs(import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY),r=!!import.meta.env.VITE_SUPABASE_PK_OVERRIDE;if(!e||r||!import.meta.env.DEV)return null;const n={background:"rgba(0,0,0,.2)",padding:"1px 4px",borderRadius:4};return t("div",{style:{position:"fixed",top:0,left:0,right:0,zIndex:99999,background:"#dc2626",color:"#fff",padding:"8px 16px",fontSize:"13px",fontFamily:"Inter, system-ui, sans-serif",textAlign:"center",lineHeight:1.4},children:[a("strong",{children:"⚠️ Legacy Supabase Key Detectada"})," — O ",a("code",{style:n,children:"VITE_SUPABASE_PUBLISHABLE_KEY"})," contém uma anon key JWT legada. Adicione ",a("code",{style:n,children:'VITE_SUPABASE_PK_OVERRIDE="sb_publishable_..."'})," no .env para corrigir."]})}const hu=ft.Root,fu=n.forwardRef(({className:e,...t},r)=>a(ft.Item,{ref:r,className:Fi("border-b",e),...t}));fu.displayName="AccordionItem";const gu=n.forwardRef(({className:e,children:r,...n},i)=>a(ft.Header,{className:"flex",children:t(ft.Trigger,{ref:i,className:Fi("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[r,a(D,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));gu.displayName=ft.Trigger.displayName;const vu=n.forwardRef(({className:e,children:t,...r},n)=>a(ft.Content,{ref:n,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...r,children:a("div",{className:Fi("pb-4 pt-0",e),children:t})}));vu.displayName=ft.Content.displayName;const bu=n.forwardRef(({className:e,...t},r)=>a(gt.Root,{ref:r,className:Fi("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));bu.displayName=gt.Root.displayName;const xu=n.forwardRef(({className:e,...t},r)=>a(gt.Image,{ref:r,className:Fi("aspect-square h-full w-full",e),...t}));xu.displayName=gt.Image.displayName;const yu=n.forwardRef(({className:e,...t},r)=>a(gt.Fallback,{ref:r,className:Fi("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));yu.displayName=gt.Fallback.displayName;const Nu=n.forwardRef(({...e},t)=>a("nav",{ref:t,"aria-label":"breadcrumb",...e}));Nu.displayName="Breadcrumb";const wu=n.forwardRef(({className:e,...t},r)=>a("ol",{ref:r,className:Fi("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",e),...t}));wu.displayName="BreadcrumbList";const _u=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Fi("inline-flex items-center gap-1.5",e),...t}));_u.displayName="BreadcrumbItem";const Cu=n.forwardRef(({asChild:e,className:t,...r},n)=>a(e?g:"a",{ref:n,className:Fi("transition-colors hover:text-foreground",t),...r}));Cu.displayName="BreadcrumbLink";const ku=n.forwardRef(({className:e,...t},r)=>a("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Fi("font-normal text-foreground",e),...t}));ku.displayName="BreadcrumbPage";const Su=({children:e,className:t,...r})=>a("li",{role:"presentation","aria-hidden":"true",className:Fi("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:e??a(U,{})});Su.displayName="BreadcrumbSeparator";const Au=({className:e,...r})=>t("span",{role:"presentation","aria-hidden":"true",className:Fi("flex h-9 w-9 items-center justify-center",e),...r,children:[a(xe,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Mais"})]});Au.displayName="BreadcrumbEllipsis";const Eu=v("flex items-center",{variants:{orientation:{horizontal:"flex-row [&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}}),Du=n.forwardRef(({className:e,orientation:t,...r},n)=>a("div",{ref:n,className:Fi(Eu({orientation:t}),e),...r}));function Pu({className:e,classNames:t,showOutsideDays:r=!0,...n}){return a(vt,{showOutsideDays:r,className:Fi("p-3 pointer-events-auto",e),locale:ci,classNames:{months:"relative flex flex-col gap-4 sm:flex-row",month:"flex flex-col gap-4",month_caption:"flex h-9 w-full items-center justify-center px-8",caption_label:"text-sm font-medium",nav:"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1 px-1",button_previous:Fi(Bi({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Fi(Bi({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),month_grid:"w-full border-collapse",weekdays:"flex",weekday:"text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal w-9",week:"mt-2 flex w-full",day:"group/day relative h-9 w-9 select-none p-0 text-center text-sm [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md focus-within:relative focus-within:z-20",day_button:Fi(Bi({variant:"ghost"}),"h-9 w-9 p-0 font-normal transition-none aria-selected:opacity-100"),range_start:"bg-accent rounded-l-md",range_end:"bg-accent rounded-r-md",range_middle:"rounded-none aria-selected:bg-accent aria-selected:text-accent-foreground",selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground rounded-md",today:"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",outside:"text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",disabled:"text-muted-foreground opacity-50",hidden:"invisible",...t},components:{Chevron:({orientation:e})=>a("left"===e?oe:U,{className:"h-4 w-4"})},...n})}Du.displayName="ButtonGroup",Pu.displayName="Calendar";const Iu={Root:function({children:e,className:t}){return a("div",{className:Fi("space-y-4",t),children:e})},Item:function({children:e,onClick:t,className:r}){return a(Gi,{className:Fi("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:a(Xi,{className:"p-4",children:e})})},Field:function({label:e,value:r,className:n}){return t("div",{className:Fi("flex justify-between items-center text-sm",n),children:[t("span",{className:"text-muted-foreground font-medium",children:[e,":"]}),a("span",{className:"text-foreground",children:r})]})}};function Tu({date:e,onDateChange:r,placeholder:n,disabled:i=!1,className:o,disabledDates:s}){const{t:l}=Ga(),d=n??l("select_date");return t(bs,{children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",disabled:i,className:Fi("w-full justify-start text-left font-normal",!e&&"text-muted-foreground",o),children:[a(ye,{className:"mr-2 h-4 w-4"}),e?_(e,"d 'de' MMMM 'de' yyyy",{locale:ci}):a("span",{children:d})]})}),a(ys,{className:"w-auto p-0",align:"start",children:a(Pu,{mode:"single",selected:e,onSelect:r,disabled:s,initialFocus:!0,className:"pointer-events-auto"})})]})}const Ru=({shouldScaleBackground:e=!0,...t})=>a(bt.Root,{shouldScaleBackground:e,...t});Ru.displayName="Drawer";const Mu=bt.Trigger,Lu=bt.Portal,zu=bt.Close,Fu=n.forwardRef(({className:e,...t},r)=>a(bt.Overlay,{ref:r,className:Fi("fixed inset-0 z-50 bg-black/80",e),...t}));Fu.displayName=bt.Overlay.displayName;const Uu=n.forwardRef(({className:e,children:r,...n},i)=>t(Lu,{children:[a(Fu,{}),t(bt.Content,{ref:i,className:Fi("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",e),...n,children:[a("div",{className:"mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted"}),r]})]}));Uu.displayName="DrawerContent";const ju=({className:e,...t})=>a("div",{className:Fi("grid gap-1.5 p-4 text-center sm:text-left",e),...t});ju.displayName="DrawerHeader";const Ou=({className:e,...t})=>a("div",{className:Fi("mt-auto flex flex-col gap-2 p-4",e),...t});Ou.displayName="DrawerFooter";const Bu=n.forwardRef(({className:e,...t},r)=>a(bt.Title,{ref:r,className:Fi("text-lg font-semibold leading-none tracking-tight",e),...t}));Bu.displayName=bt.Title.displayName;const $u=n.forwardRef(({className:e,...t},r)=>a(bt.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));$u.displayName=bt.Description.displayName;const Vu={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))]"},qu={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Wu({children:e,cols:t="auto-fit",gap:r="md",className:n}){return a("div",{className:Fi("grid",Vu[t],qu[r],n),children:e})}const Hu=xt.Root,Gu=xt.Trigger,Ku=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,...n},i)=>a(xt.Content,{ref:i,align:t,sideOffset:r,className:Fi("z-50 w-64 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),...n}));Ku.displayName=xt.Content.displayName;const Yu=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-slot":"input-group",className:Fi("flex min-w-0 items-center rounded-md border border-input bg-background","focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background","has-[input:disabled]:cursor-not-allowed has-[input:disabled]:opacity-50","has-[textarea:disabled]:cursor-not-allowed has-[textarea:disabled]:opacity-50",e),...t}));Yu.displayName="InputGroup";const Qu=v("flex items-center justify-center text-sm text-muted-foreground shrink-0",{variants:{align:{"inline-start":"border-r border-input px-3","inline-end":"border-l border-input px-3","block-start":"border-b border-input px-3 py-2 w-full justify-start","block-end":"border-t border-input px-3 py-2 w-full justify-start"}},defaultVariants:{align:"inline-start"}}),Xu=n.forwardRef(({className:e,align:t,...r},n)=>a("div",{ref:n,"data-slot":"input-group-addon",className:Fi(Qu({align:t}),e),...r}));Xu.displayName="InputGroupAddon";const Ju=v("",{variants:{size:{xs:"h-6 px-2 text-xs","icon-xs":"h-6 w-6",sm:"h-7 px-3 text-xs","icon-sm":"h-7 w-7"}},defaultVariants:{size:"xs"}}),Zu=n.forwardRef(({className:e,size:t,variant:r="ghost",...n},i)=>a($i,{ref:i,"data-slot":"input-group-button",variant:r,className:Fi(Ju({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",e),...n}));Zu.displayName="InputGroupButton";const em=n.forwardRef(({className:e,...t},r)=>a(qi,{ref:r,"data-slot":"input-group-control",className:Fi("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));em.displayName="InputGroupInput";const am=n.forwardRef(({className:e,...t},r)=>a(Wo,{ref:r,"data-slot":"input-group-control",className:Fi("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));am.displayName="InputGroupTextarea";const tm=n.forwardRef(({className:e,...t},r)=>a("h1",{ref:r,className:Fi("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",e),...t}));tm.displayName="H1";const rm=n.forwardRef(({className:e,...t},r)=>a("h2",{ref:r,className:Fi("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",e),...t}));rm.displayName="H2";const nm=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Fi("scroll-m-20 text-2xl font-semibold tracking-tight",e),...t}));nm.displayName="H3";const im=n.forwardRef(({className:e,...t},r)=>a("h4",{ref:r,className:Fi("scroll-m-20 text-xl font-semibold tracking-tight",e),...t}));im.displayName="H4";const om=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("leading-7 [&:not(:first-child)]:mt-6",e),...t}));om.displayName="P";const sm=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("text-xl text-muted-foreground",e),...t}));sm.displayName="Lead";const lm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Fi("text-lg font-semibold",e),...t}));lm.displayName="Large";const dm=n.forwardRef(({className:e,...t},r)=>a("small",{ref:r,className:Fi("text-sm font-medium leading-none",e),...t}));dm.displayName="Small";const cm=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));cm.displayName="Muted";const um=n.forwardRef(({className:e,...t},r)=>a("code",{ref:r,className:Fi("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",e),...t}));um.displayName="InlineCode";const mm=n.forwardRef(({className:e,...t},r)=>a("blockquote",{ref:r,className:Fi("mt-6 border-l-2 pl-6 italic",e),...t}));mm.displayName="Blockquote";const pm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Fi("my-6 ml-6 list-disc [&>li]:mt-2",e),...t}));pm.displayName="List";const hm=n.forwardRef(({className:e,children:r,...n},i)=>t(yt.Root,{ref:i,className:Fi("relative z-10 flex max-w-max flex-1 items-center justify-center",e),...n,children:[r,a(Nm,{})]}));hm.displayName=yt.Root.displayName;const fm=n.forwardRef(({className:e,...t},r)=>a(yt.List,{ref:r,className:Fi("group flex flex-1 list-none items-center justify-center space-x-1",e),...t}));fm.displayName=yt.List.displayName;const gm=yt.Item,vm=v("group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"),bm=n.forwardRef(({className:e,children:r,...n},i)=>t(yt.Trigger,{ref:i,className:Fi(vm(),"group",e),...n,children:[r," ",a(D,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));bm.displayName=yt.Trigger.displayName;const xm=n.forwardRef(({className:e,...t},r)=>a(yt.Content,{ref:r,className:Fi("left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",e),...t}));xm.displayName=yt.Content.displayName;const ym=yt.Link,Nm=n.forwardRef(({className:e,...t},r)=>a("div",{className:Fi("absolute left-0 top-full flex justify-center"),children:a(yt.Viewport,{className:Fi("origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",e),ref:r,...t})}));Nm.displayName=yt.Viewport.displayName;const wm=n.forwardRef(({className:e,...t},r)=>a(yt.Indicator,{ref:r,className:Fi("top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",e),...t,children:a("div",{className:"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md"})}));function _m({items:e,maxItems:n=3,className:i}){const o=e.length>n?[e[0],...e.slice(-(n-1))]:e,s=e.length>n;return a(Nu,{className:i,children:a(wu,{children:o.map((e,n)=>{const i=s&&1===n;return t(_u,{children:[!(0===n)&&a(Su,{}),i&&t(r,{children:[a(Au,{}),a(Su,{})]}),e.isCurrentPage?a(ku,{children:e.label}):a(Cu,{asChild:!0,children:a(st,{to:e.href||"/",children:e.label})})]},e.label)})})})}function Cm(){const e=it();return(()=>{const a=e.pathname.split("/").filter(Boolean),t=[{label:"Exemplos",href:"/"}];let r="";return a.forEach((e,n)=>{r+=`/${e}`;const i=n===a.length-1,o=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:o,href:i?void 0:r,isCurrentPage:i})}),t})()}wm.displayName=yt.Indicator.displayName;const km=({className:e,...t})=>a("nav",{role:"navigation","aria-label":"pagination",className:Fi("mx-auto flex w-full justify-center",e),...t});km.displayName="Pagination";const Sm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Fi("flex flex-row items-center gap-1",e),...t}));Sm.displayName="PaginationContent";const Am=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Fi("",e),...t}));Am.displayName="PaginationItem";const Em=({className:e,isActive:t,size:r="icon",...n})=>a("a",{"aria-current":t?"page":void 0,className:Fi(Bi({variant:t?"outline":"ghost",size:r}),e),...n});Em.displayName="PaginationLink";const Dm=({className:r,...n})=>t(Em,{"aria-label":e.t("go_to_previous_page"),size:"default",className:Fi("gap-1 pl-2.5",r),...n,children:[a(oe,{className:"h-4 w-4"}),a("span",{children:"Previous"})]});Dm.displayName="PaginationPrevious";const Pm=({className:r,...n})=>t(Em,{"aria-label":e.t("go_to_next_page"),size:"default",className:Fi("gap-1 pr-2.5",r),...n,children:[a("span",{children:"Next"}),a(U,{className:"h-4 w-4"})]});Pm.displayName="PaginationNext";const Im=({className:e,...r})=>t("span",{"aria-hidden":!0,className:Fi("flex h-9 w-9 items-center justify-center",e),...r,children:[a(xe,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"More pages"})]});Im.displayName="PaginationEllipsis";const Tm=n.forwardRef(({className:e,value:t,...r},n)=>a(Nt.Root,{ref:n,className:Fi("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...r,children:a(Nt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Tm.displayName=Nt.Root.displayName;const Rm=n.forwardRef(({className:e,...t},r)=>a(wt.Root,{className:Fi("grid gap-2",e),...t,ref:r}));Rm.displayName=wt.Root.displayName;const Mm=n.forwardRef(({className:e,...t},r)=>a(wt.Item,{ref:r,className:Fi("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:a(wt.Indicator,{className:"flex items-center justify-center",children:a(j,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Mm.displayName=wt.Item.displayName;const Lm=({className:e,...t})=>a(_t.PanelGroup,{className:Fi("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),zm=_t.Panel,Fm=({withHandle:e,className:t,...r})=>a(_t.PanelResizeHandle,{className:Fi("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...r,children:e&&a("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:a(ae,{className:"h-2.5 w-2.5"})})}),Um=Ma.Root,jm=Ma.Trigger,Om=Ma.Close,Bm=Ma.Portal,$m=n.forwardRef(({className:e,...t},r)=>a(Ma.Overlay,{className:Fi("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:r}));$m.displayName=Ma.Overlay.displayName;const Vm=v("fixed z-50 flex flex-col bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b max-h-[70vh] data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t max-h-[70vh] data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),qm=n.forwardRef(({side:e="right",className:r,children:n,...i},o)=>t(Bm,{children:[a($m,{}),t(Ma.Content,{ref:o,className:Fi(Vm({side:e}),r),...i,children:[n,t(Ma.Close,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-0 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[a(E,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]})]}));qm.displayName=Ma.Content.displayName;const Wm=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Fi("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(Zi,{className:"mt-2"})]});Wm.displayName="SheetHeader";const Hm=({className:e,...t})=>a("div",{className:Fi("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",e),...t});Hm.displayName="SheetBody";const Gm=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(Zi,{className:"mb-4"}),a("div",{className:Fi("flex flex-row justify-end gap-2",e),...n,children:r})]});Gm.displayName="SheetFooter";const Km=n.forwardRef(({className:e,...t},r)=>a(Ma.Title,{ref:r,className:Fi("text-lg font-semibold text-foreground",e),...t}));Km.displayName=Ma.Title.displayName;const Ym=n.forwardRef(({className:e,...t},r)=>a(Ma.Description,{ref:r,className:Fi("text-sm text-muted-foreground",e),...t}));Ym.displayName=Ma.Description.displayName;const Qm="sidebar:state",Xm=n.createContext(null);function Jm(){const e=n.useContext(Xm);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const Zm=n.forwardRef(({defaultOpen:e=!0,open:t,onOpenChange:r,className:i,style:o,children:s,...l},d)=>{const c=Dl(),[u,m]=n.useState(!1),[p,h]=n.useState(()=>{if("undefined"!=typeof window){const a=localStorage.getItem(Qm);return null!==a?"true"===a:e}return e}),f=t??p,g=n.useCallback(e=>{const a="function"==typeof e?e(f):e;r?r(a):h(a),"undefined"!=typeof window&&localStorage.setItem(Qm,String(a))},[r,f]),v=n.useCallback(()=>c?m(e=>!e):g(e=>!e),[c,g,m]);n.useEffect(()=>{const e=e=>{"b"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),v())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[v]);const b=f?"expanded":"collapsed",x=n.useMemo(()=>({state:b,open:f,setOpen:g,isMobile:c,openMobile:u,setOpenMobile:m,toggleSidebar:v}),[b,f,g,c,u,m,v]);return a(Xm.Provider,{value:x,children:a(ps,{delayDuration:0,children:a("div",{className:Fi("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar sidebar-container",i),style:{"--sidebar-width":"16rem","--sidebar-width-icon":"4rem",...o},ref:d,...l,children:s})})})});Zm.displayName="SidebarProvider";const ep=n.forwardRef(({side:e="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:o,...s},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Jm();return"none"===n?a("div",{className:Fi("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...s,children:o}):d?a(Um,{open:u,onOpenChange:m,...s,children:t(qm,{"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:[a(Km,{className:"sr-only",children:"Menu de Navegação"}),a("div",{className:"flex h-full w-full flex-col",children:o})]})}):t("div",{ref:l,className:"group peer hidden md:block text-sidebar-foreground","data-state":c,"data-collapsible":"collapsed"===c?n:"","data-variant":r,"data-side":e,children:[a("div",{className:Fi("duration-200 relative h-[calc(100svh-var(--header-height,0px))] w-[--sidebar-width] bg-transparent transition-[width] ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180","floating"===r||"inset"===r?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),a("div",{className:Fi("duration-200 fixed z-30 hidden w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex overflow-visible","top-[var(--header-height,0px)] h-[calc(100svh-var(--header-height,0px))]","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"===r||"inset"===r?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",i),...s,children:a("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col overflow-visible 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:o})})]})});ep.displayName="Sidebar";const ap=n.forwardRef(({className:e,onClick:r,...n},i)=>{const{toggleSidebar:o}=Jm();return t($i,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Fi("h-7 w-7",e),onClick:e=>{r?.(e),o()},...n,children:[a(Ne,{}),a("span",{className:"sr-only",children:"Toggle Sidebar"})]})});ap.displayName="SidebarTrigger";const tp=n.forwardRef(({className:e,...t},r)=>{const{toggleSidebar:n}=Jm();return a("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Fi("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})});tp.displayName="SidebarRail";const rp=n.forwardRef(({className:e,...t},r)=>a("main",{ref:r,className:Fi("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}));rp.displayName="SidebarInset";const np=n.forwardRef(({className:e,...t},r)=>a(qi,{ref:r,"data-sidebar":"input",className:Fi("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",e),...t}));np.displayName="SidebarInput";const ip=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"header",className:Fi("flex flex-col gap-2 p-2",e),...t}));ip.displayName="SidebarHeader";const op=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"footer",className:Fi("flex flex-col gap-2 p-2",e),...t}));op.displayName="SidebarFooter";const sp=n.forwardRef(({className:e,...t},r)=>a(Zi,{ref:r,"data-sidebar":"separator",className:Fi("mx-2 w-auto bg-sidebar-border",e),...t}));sp.displayName="SidebarSeparator";const lp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"content",className:Fi("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t}));lp.displayName="SidebarContent";const dp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group",className:Fi("relative flex w-full min-w-0 flex-col p-2",e),...t}));dp.displayName="SidebarGroup";const cp=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"div",{ref:n,"data-sidebar":"group-label",className:Fi("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}));cp.displayName="SidebarGroupLabel";const up=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"button",{ref:n,"data-sidebar":"group-action",className:Fi("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}));up.displayName="SidebarGroupAction";const mp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group-content",className:Fi("w-full text-sm",e),...t}));mp.displayName="SidebarGroupContent";const pp=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu",className:Fi("flex w-full min-w-0 flex-col gap-1",e),...t}));pp.displayName="SidebarMenu";const hp=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,"data-sidebar":"menu-item",className:Fi("group/menu-item relative",e),...t}));hp.displayName="SidebarMenuItem";const fp=v("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-primary/10 data-[active=true]:font-medium data-[active=true]:text-primary 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"}}),gp=n.forwardRef(({asChild:e=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:o,className:s,...l},d)=>{const c=e?g:"button",{isMobile:u,state:m}=Jm(),p=a(c,{ref:d,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Fi(fp({variant:n,size:i}),s),...l});return o?("string"==typeof o&&(o={children:o}),t(hs,{children:[a(fs,{asChild:!0,children:p}),a(gs,{side:"right",align:"center",hidden:"collapsed"!==m||u,...o})]})):p});gp.displayName="SidebarMenuButton";const vp=n.forwardRef(({className:e,asChild:t=!1,showOnHover:r=!1,...n},i)=>a(t?g:"button",{ref:i,"data-sidebar":"menu-action",className:Fi("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),...n}));vp.displayName="SidebarMenuAction";const bp=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"menu-badge",className:Fi("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}));bp.displayName="SidebarMenuBadge";const xp=n.forwardRef(({className:e,showIcon:r=!1,...i},o)=>{const s=n.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return t("div",{ref:o,"data-sidebar":"menu-skeleton",className:Fi("rounded-md h-8 flex gap-2 px-2 items-center",e),...i,children:[r&&a("div",{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),a("div",{className:"h-4 flex-1 max-w-[--skeleton-width] skeleton-width","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":s}})]})});xp.displayName="SidebarMenuSkeleton";const yp=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu-sub",className:Fi("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}));yp.displayName="SidebarMenuSub";const Np=n.forwardRef(({...e},t)=>a("li",{ref:t,...e}));Np.displayName="SidebarMenuSubItem";const wp=n.forwardRef(({asChild:e=!1,size:t="md",isActive:r,className:n,...i},o)=>a(e?g:"a",{ref:o,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Fi("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"===t&&"text-xs","md"===t&&"text-sm","group-data-[collapsible=icon]:hidden",n),...i}));wp.displayName="SidebarMenuSubButton";const _p=n.forwardRef(({className:e,value:r,defaultValue:n,...i},o)=>{const s=r||n||[0];return t(Ct.Root,{ref:o,value:r,defaultValue:n,className:Fi("relative flex w-full touch-none select-none items-center",e),...i,children:[a(Ct.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:a(Ct.Range,{className:"absolute h-full bg-primary"})}),s.map((e,t)=>a(Ct.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"},t))]})});function Cp({children:e,className:t}){return a("div",{className:Fi("flex flex-col h-full",t),children:a(Dd,{className:"flex-1",children:a("div",{className:"space-y-6 p-6",children:e})})})}function kp({title:e,description:r,actions:n,className:i}){return t("div",{className:Fi("space-y-4",i),children:[t("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[t("div",{className:"space-y-1",children:[a("h2",{className:"text-2xl font-bold tracking-tight",children:e}),r&&a("p",{className:"text-muted-foreground text-sm",children:r})]}),n&&a("div",{className:"flex items-center gap-2 flex-wrap",children:n})]}),a(Zi,{})]})}function Sp({children:e,className:t}){return a("div",{className:Fi("space-y-6",t),children:e})}_p.displayName=Ct.Root.displayName;const Ap=kt.Menu,Ep=kt.Group,Dp=kt.Portal,Pp=kt.Sub,Ip=kt.RadioGroup,Tp=n.forwardRef(({className:e,...t},r)=>a(kt.Root,{ref:r,className:Fi("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",e),...t}));Tp.displayName=kt.Root.displayName;const Rp=n.forwardRef(({className:e,...t},r)=>a(kt.Trigger,{ref:r,className:Fi("flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",e),...t}));Rp.displayName=kt.Trigger.displayName;const Mp=n.forwardRef(({className:e,inset:r,children:n,...i},o)=>t(kt.SubTrigger,{ref:o,className:Fi("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",r&&"pl-8",e),...i,children:[n,a(U,{className:"ml-auto h-4 w-4"})]}));Mp.displayName=kt.SubTrigger.displayName;const Lp=n.forwardRef(({className:e,...t},r)=>a(kt.SubContent,{ref:r,className:Fi("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));Lp.displayName=kt.SubContent.displayName;const zp=n.forwardRef(({className:e,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},o)=>a(kt.Portal,{children:a(kt.Content,{ref:o,align:t,alignOffset:r,sideOffset:n,className:Fi("z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...i})}));zp.displayName=kt.Content.displayName;const Fp=n.forwardRef(({className:e,inset:t,...r},n)=>a(kt.Item,{ref:n,className:Fi("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r}));Fp.displayName=kt.Item.displayName;const Up=n.forwardRef(({className:e,children:r,checked:n,...i},o)=>t(kt.CheckboxItem,{ref:o,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...i,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(kt.ItemIndicator,{children:a(I,{className:"h-4 w-4"})})}),r]}));Up.displayName=kt.CheckboxItem.displayName;const jp=n.forwardRef(({className:e,children:r,...n},i)=>t(kt.RadioItem,{ref:i,className:Fi("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[a("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:a(kt.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));jp.displayName=kt.RadioItem.displayName;const Op=n.forwardRef(({className:e,inset:t,...r},n)=>a(kt.Label,{ref:n,className:Fi("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));Op.displayName=kt.Label.displayName;const Bp=n.forwardRef(({className:e,...t},r)=>a(kt.Separator,{ref:r,className:Fi("-mx-1 my-1 h-px bg-muted",e),...t}));Bp.displayName=kt.Separator.displayName;const $p=({className:e,...t})=>a("span",{className:Fi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});$p.displayname="MenubarShortcut";const Vp={light:"",dark:".dark"},qp=n.createContext(null);function Wp(){const e=n.useContext(qp);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Hp=n.forwardRef(({id:e,className:r,children:i,config:o,...s},l)=>{const d=n.useId(),c=`chart-${e||d.replace(/:/g,"")}`;return a(qp.Provider,{value:{config:o},children:t("div",{"data-chart":c,ref:l,className:Fi("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",r),...s,children:[a(Gp,{id:c,config:o}),a(St.ResponsiveContainer,{children:i})]})})});Hp.displayName="Chart";const Gp=({id:e,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?a("style",{dangerouslySetInnerHTML:{__html:Object.entries(Vp).map(([a,t])=>`\n${t} [data-chart=${e}] {\n${r.map(([e,t])=>{const r=t.theme?.[a]||t.color;return r?` --color-${e}: ${r};`:null}).join("\n")}\n}\n`).join("\n")}}):null},Kp=St.Tooltip,Yp=n.forwardRef(({active:e,payload:i,className:o,indicator:s="dot",hideLabel:l=!1,hideIndicator:d=!1,label:c,labelFormatter:u,labelClassName:m,formatter:p,color:h,nameKey:f,labelKey:g},v)=>{const{config:b}=Wp(),x=n.useMemo(()=>{if(l||!i?.length)return null;const[e]=i,t=Jp(b,e,`${g||e?.dataKey||e?.name||"value"}`),r=g||"string"!=typeof c?t?.label:b[c]?.label||c;return u?a("div",{className:Fi("font-medium",m),children:u(r,i)}):r?a("div",{className:Fi("font-medium",m),children:r}):null},[c,u,i,l,m,b,g]);if(!e||!i?.length)return null;const y=1===i.length&&"dot"!==s;return t("div",{ref:v,className:Fi("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",o),children:[y?null:x,a("div",{className:"grid gap-1.5",children:i.map((e,n)=>{const i=`${f||e.name||e.dataKey||"value"}`,o=Jp(b,e,i),l=h||e.payload?.fill||e.color;return a("div",{className:Fi("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===s&&"items-center"),children:p&&void 0!==e?.value&&e.name?p(e.value,e.name,e,n,e.payload):t(r,{children:[o?.icon?a(o.icon,{}):!d&&a("div",{className:Fi("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===s,"w-1":"line"===s,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===s,"my-0.5":y&&"dashed"===s}),style:{"--color-bg":l,"--color-border":l}}),t("div",{className:Fi("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[t("div",{className:"grid gap-1.5",children:[y?x:null,a("span",{className:"text-muted-foreground",children:o?.label||e.name})]}),void 0!==e.value&&a("span",{className:"font-mono font-medium tabular-nums text-foreground",children:"number"==typeof e.value?e.value.toLocaleString():e.value})]})]})},e.dataKey||n)})})]})});Yp.displayName="ChartTooltip";const Qp=St.Legend,Xp=n.forwardRef(({className:e,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:o},s)=>{const{config:l}=Wp();return n?.length?a("div",{ref:s,className:Fi("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",e),children:n.map(e=>{const n=`${o||e.dataKey||"value"}`,i=Jp(l,e,n);return t("div",{className:Fi("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[i?.icon&&!r?a(i.icon,{}):a("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:e.color}}),i?.label]},e.value)})}):null});function Jp(e,a,t){if("object"!=typeof a||null===a)return;const r="payload"in a&&"object"==typeof a.payload&&null!==a.payload?a.payload:void 0;let n=t;return t in a&&"string"==typeof a[t]?n=a[t]:r&&t in r&&"string"==typeof r[t]&&(n=r[t]),n in e?e[n]:e[t]}Xp.displayName="ChartLegend";const Zp=({onClick:e,isActive:t,disabled:r,children:n,title:i})=>a("button",{type:"button",onClick:e,disabled:r,title:i,className:Fi("p-1.5 rounded hover:bg-muted transition-colors",t?"bg-muted text-primary":"text-muted-foreground",r&&"opacity-50 cursor-not-allowed"),children:n}),eh=()=>a("div",{className:"w-px h-5 bg-border mx-1"}),ah=({value:r,onChange:i,disabled:s,placeholder:d=e.t("write_content_here"),minHeight:c="300px",showModeToggle:u=!0,showVariableHint:m=!0,className:p})=>{const{t:h}=Ga(),[f,g]=o("visual"),v=Vt({extensions:[Wt.configure({heading:{levels:[1,2,3]}}),Ht,Gt.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Kt,Yt,Qt.configure({multicolor:!0})],content:r||"",editable:!s,onUpdate:({editor:e})=>{i(e.getHTML())}});n.useEffect(()=>{v&&r!==v.getHTML()&&v.commands.setContent(r||"")},[r,v]);const b=l(()=>{if(!v)return;const e=v.getAttributes("link").href,a=window.prompt("URL",e);null!==a&&(""!==a?v.chain().focus().extendMarkRange("link").setLink({href:a}).run():v.chain().focus().extendMarkRange("link").unsetLink().run())},[v]);return v?t("div",{className:Fi("space-y-2",p),children:[u&&t("div",{className:"flex justify-between items-center",children:[t("div",{className:"flex gap-1",children:[t($i,{type:"button",size:"sm",variant:"visual"===f?"default":"outline",onClick:()=>g("visual"),disabled:s,children:[a(we,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),t($i,{type:"button",size:"sm",variant:"code"===f?"default":"outline",onClick:()=>g("code"),disabled:s,children:[a(_e,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),t($i,{type:"button",size:"sm",variant:"preview"===f?"default":"outline",onClick:()=>g("preview"),disabled:s,children:[a(Ce,{className:"h-3.5 w-3.5 mr-1"}),"Preview"]})]}),m&&t("p",{className:"text-xs text-muted-foreground",children:["Use ",a("code",{className:"bg-muted px-1 py-0.5 rounded",children:"{{variavel}}"})]})]}),"visual"===f&&t("div",{className:"border rounded-md overflow-hidden bg-background cursor-text",onClick:e=>{e.target.closest(".editor-toolbar")||v?.commands.focus()},children:[t("div",{className:"editor-toolbar flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[a(Zp,{onClick:()=>v.chain().focus().toggleHeading({level:1}).run(),isActive:v.isActive("heading",{level:1}),disabled:s,title:e.t("heading_1"),children:a(ke,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleHeading({level:2}).run(),isActive:v.isActive("heading",{level:2}),disabled:s,title:e.t("heading_2"),children:a(Se,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleHeading({level:3}).run(),isActive:v.isActive("heading",{level:3}),disabled:s,title:e.t("heading_3"),children:a(Ae,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().toggleBold().run(),isActive:v.isActive("bold"),disabled:s,title:e.t("bold"),children:a(Ee,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleItalic().run(),isActive:v.isActive("italic"),disabled:s,title:e.t("italic"),children:a(De,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleUnderline().run(),isActive:v.isActive("underline"),disabled:s,title:"Sublinhado",children:a(Pe,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleStrike().run(),isActive:v.isActive("strike"),disabled:s,title:"Riscado",children:a(Ie,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().toggleBulletList().run(),isActive:v.isActive("bulletList"),disabled:s,title:"Lista",children:a(J,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().toggleOrderedList().run(),isActive:v.isActive("orderedList"),disabled:s,title:h("ordered_list"),children:a(Te,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().toggleHighlight().run(),isActive:v.isActive("highlight"),disabled:s,title:"Destacar",children:a(Re,{className:"h-4 w-4"})}),a(Zp,{onClick:b,isActive:v.isActive("link"),disabled:s,title:"Link",children:a(Me,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().unsetAllMarks().clearNodes().run(),disabled:s,title:h("clear_formatting"),children:a(Le,{className:"h-4 w-4"})}),a(eh,{}),a(Zp,{onClick:()=>v.chain().focus().undo().run(),disabled:s||!v.can().undo(),title:"Desfazer",children:a(ze,{className:"h-4 w-4"})}),a(Zp,{onClick:()=>v.chain().focus().redo().run(),disabled:s||!v.can().redo(),title:"Refazer",children:a(Fe,{className:"h-4 w-4"})})]}),a(qt,{editor:v,className:Fi("prose prose-sm max-w-none focus:outline-none","[&_.ProseMirror]:p-4","[&_.ProseMirror]:min-h-full","[&_.ProseMirror]:cursor-text","[&_.ProseMirror]:outline-none","[&_.ProseMirror_p.is-editor-empty:first-child::before]:text-muted-foreground","[&_.ProseMirror_p.is-editor-empty:first-child::before]:content-[attr(data-placeholder)]","[&_.ProseMirror_p.is-editor-empty:first-child::before]:float-left","[&_.ProseMirror_p.is-editor-empty:first-child::before]:h-0","[&_.ProseMirror_p.is-editor-empty:first-child::before]:pointer-events-none"),style:{minHeight:c}})]}),"code"===f&&a("textarea",{value:r||"",onChange:e=>i(e.target.value),disabled:s,className:"w-full p-3 border rounded-md font-mono text-sm resize-none focus:ring-2 focus:ring-primary bg-background",style:{height:c},placeholder:"Cole ou edite o HTML aqui..."}),"preview"===f&&a("div",{className:"border rounded-lg p-4 bg-muted overflow-auto",style:{height:c},children:a("div",{className:"bg-background shadow-sm rounded border p-4",children:a("div",{dangerouslySetInnerHTML:{__html:r||`<p class="text-muted-foreground">${d}</p>`}})})})]}):null};function th({image:e,title:t,className:r}){return a("div",{className:Fi("relative w-full aspect-video bg-muted rounded-lg overflow-hidden","max-h-[25vh] sm:max-h-[35vh]",r),children:e?a("img",{src:e,alt:t,className:"w-full h-full object-cover"}):a("div",{className:"flex items-center justify-center h-full",children:a(Ue,{className:"w-16 h-16 text-muted-foreground"})})})}function rh({steps:e,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:o}){const{t:s}=Ga(),l=e.length,d=(r+1)/l*100;return t("div",{className:Fi("flex items-center gap-3",o),children:[t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",l,a(D,{className:"h-3 w-3 ml-1"})]})}),a(os,{align:"start",children:e.map((e,a)=>t(ss,{onClick:()=>n(a),className:Fi(a===r&&"bg-accent"),children:[a+1,". ",e.title]},e.id))})]}),a(Tm,{value:d,className:"w-32 h-2"})]})}function nh({currentStepIndex:e,totalSteps:r,onBack:n,onNext:i,onComplete:o,backButtonText:s,continueButtonText:l,finishButtonText:d,className:c}){const{t:u}=Ga(),m=0===e,p=e===r-1;return t("div",{className:Fi("flex items-center gap-2",c),children:[!m&&t($i,{variant:"outline",onClick:n,size:"sm",children:[a(je,{className:"h-4 w-4 mr-2"}),s]}),t($i,{onClick:p?o:i,size:"sm",children:[p?d:l,!p&&a(Oe,{className:"h-4 w-4 ml-2"})]})]})}const ih=n.forwardRef(({open:r,onOpenChange:i,steps:o,onComplete:s,onStepChange:l,continueButtonText:d="Continuar",backButtonText:c="Voltar",finishButtonText:u="Concluir",stepLabel:m=e.t("approval_step_label"),size:p="md",showProgressIndicator:h=!0,currentStepIndex:f,onCurrentStepChange:g,className:v},b)=>{const[x,y]=n.useState(0),N=void 0!==f,w=N?f:x,_=n.useCallback(e=>{N?g?.(e):y(e),l?.(e)},[N,g,l]);n.useEffect(()=>{r||N||y(0)},[r,N]);const C=o[w],k=o.length;return C?a(mo,{open:r,onOpenChange:i,children:t(bo,{ref:b,size:p,variant:"informative",className:Fi("p-0 gap-0 overflow-hidden",v),children:[t(fo,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground z-10",children:[a(E,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Fechar"})]}),a("div",{className:"flex-1 min-h-0 overflow-auto",children:t("div",{className:"p-6 space-y-4",children:[a(th,{image:C.image,title:C.title}),a(wo,{className:"text-xl font-semibold",children:C.title}),a(_o,{className:"text-muted-foreground",children:C.description})]})}),t("div",{className:"flex-shrink-0",children:[a(Zi,{}),t("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?a(rh,{steps:o,currentStepIndex:w,onStepSelect:e=>{_(e)},stepLabel:m}):a("div",{}),a(nh,{currentStepIndex:w,totalSteps:k,onBack:()=>{w>0&&_(w-1)},onNext:()=>{w<k-1&&_(w+1)},onComplete:()=>{s?.(),i(!1)},backButtonText:c,continueButtonText:d,finishButtonText:u})]})]})]})}):null});function oh({label:e,onClick:r,icon:n,actions:i=[],variant:o="default",size:s="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const{t:m}=Ga(),p=l||d;if(!(i.length>0))return t($i,{variant:o,size:s,disabled:p,onClick:r,className:u,children:[d?a(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?a(n,{className:"mr-2 h-4 w-4"}):null,e]});return t("div",{className:Fi("inline-flex rounded-md shadow-sm",u),children:[t($i,{variant:o,size:s,disabled:p,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[d?a(T,{className:"mr-2 h-4 w-4 animate-spin"}):n?a(n,{className:"mr-2 h-4 w-4"}):null,e]}),t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:o,size:s,disabled:p,className:Fi("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[s]),"aria-label":m("more_options"),children:a(D,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[s]})})}),a(os,{align:c,className:"min-w-[160px]",children:i.map(e=>{const r=e.icon;return t(ss,{onClick:e.onClick,disabled:e.disabled,className:Fi("destructive"===e.variant&&"text-destructive focus:text-destructive"),children:[r&&a(r,{className:"mr-2 h-4 w-4"}),e.label]},e.id)})})]})]})}var sh,lh;ih.displayName="OnboardingDialog",(lh=sh||(sh={})).CSV="csv",lh.PDF="pdf",lh.XLSX="xlsx",lh.PNG="png",lh.JPEG="jpeg",lh.SVG="svg";const dh=[{value:sh.CSV,label:"CSV",icon:a(Be,{className:"h-5 w-5"})},{value:sh.PDF,label:"PDF",icon:a(Be,{className:"h-5 w-5"})},{value:sh.XLSX,label:"XLSX",icon:a($e,{className:"h-5 w-5"})}],ch=[{value:sh.PNG,label:"PNG",icon:a(Ve,{className:"h-5 w-5"})},{value:sh.JPEG,label:"JPEG",icon:a(qe,{className:"h-5 w-5"})},{value:sh.SVG,label:"SVG",icon:a(qe,{className:"h-5 w-5"})},{value:sh.PDF,label:"PDF",icon:a(Be,{className:"h-5 w-5"})}];function uh({open:e,onOpenChange:r,onExport:n,mode:i="table",options:s,title:l,description:d,cancelLabel:c="Cancelar",exportLabel:u="Exportar"}){const{t:m}=Ga(),[p,h]=o(""),f=s??("chart"===i?ch:dh),g=l??m("chart"===i?"dashboard_export_chart":"dashboard_export_table"),v=d??m("select_file_format"),b=e=>{e||h(""),r(e)};return a(mo,{open:e,onOpenChange:b,children:t(bo,{className:"sm:max-w-md",variant:"form",isDirty:!!p,children:[a(xo,{children:a(wo,{children:g})}),t("div",{className:"py-4",children:[a("p",{className:"text-sm text-muted-foreground mb-4",children:v}),a(Rm,{value:p,onValueChange:h,className:"gap-3",children:f.map(e=>t("div",{className:"flex items-center space-x-3",children:[a(Mm,{value:e.value,id:`export-${e.value}`}),t(Hi,{htmlFor:`export-${e.value}`,className:Fi("flex items-center gap-2 cursor-pointer font-normal",p===e.value&&"font-medium"),children:[e.icon,e.label]})]},e.value))})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>b(!1),children:c}),a($i,{onClick:()=>{p&&(n(p),r(!1),h(""))},disabled:!p,children:u})]})]})})}const mh=f(({value:e,onChange:r,onTimeChange:i,label:o,error:s,format:d="24h",className:c,id:u,...m},p)=>{const h=u??n.useId(),f=l(e=>{const a=e.target.value;r?.(a),i?.(a)},[r,i]),g=l(e=>{["0","1","2","3","4","5","6","7","8","9","Backspace","Tab",":","ArrowLeft","ArrowRight","Delete"].includes(e.key)||e.preventDefault()},[]);return t("div",{className:Fi("grid gap-1.5",c),children:[o&&a(Hi,{htmlFor:h,children:o}),t("div",{className:"relative",children:[a(qi,{ref:p,id:h,type:"time",value:e??"",onChange:f,onKeyDown:g,min:"00:00",max:"23:59",step:60,className:Fi("pr-9",s&&"border-destructive focus-visible:ring-destructive"),...m}),a(We,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),s&&a("p",{className:"text-sm text-destructive",children:s})]})});function ph({open:r,onOpenChange:n,onConfirm:i,onGenerateCode:s,mode:d="code",email:c,maxLength:u=8,title:m=e.t("electronic_signature"),description:p,confirmLabel:h=e.t("conclude"),cancelLabel:f=e.t("cancel"),resendLabel:g=e.t("resend_code"),errorMessage:v}){const b="password"===d,x=b?e.t("esign_password_description"):e.t("esign_code_description"),y=p??x,[N,w]=o(""),[_,C]=o(!1),[k,S]=o(!1),[A,E]=o(null),D=l(async()=>{if(N.trim()){C(!0),E(null);try{await i(N)?(w(""),n(!1)):E(v??(b?e.t("esign_invalid_password"):e.t("esign_invalid_code")))}catch{E(v??(b?e.t("esign_password_error"):e.t("esign_code_error")))}finally{C(!1)}}},[N,i,n,v,b]),P=l(async()=>{if(s){S(!0),E(null);try{await s()}catch{E(e.t("esign_resend_error"))}finally{S(!1)}}},[s]),I=e=>{e||(w(""),E(null)),n(e)},T=b?He:Ge,R=b?"Senha":e.t("verification_code"),M=b?e.t("enter_password"):e.t("enter_code");return a(mo,{open:r,onOpenChange:I,children:t(bo,{className:"sm:max-w-md",variant:"form",isDirty:!!N,children:[a(xo,{children:t(wo,{className:"flex items-center gap-2",children:[a(T,{className:"h-5 w-5 text-primary"}),m]})}),t("div",{className:"py-4 space-y-4",children:[a("p",{className:"text-sm text-muted-foreground",children:y}),!b&&c&&t("div",{className:"flex items-center gap-2 text-sm bg-muted/50 rounded-md px-3 py-2",children:[a(Ke,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-muted-foreground",children:"Enviado para:"}),a("span",{className:"font-medium",children:c})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"signature-input",children:R}),a(qi,{id:"signature-input",type:b?"password":"text",value:N,onChange:e=>w(e.target.value),onKeyDown:e=>{"Enter"===e.key&&N.trim()&&(e.preventDefault(),D())},maxLength:b?void 0:u,placeholder:M,autoFocus:!0,className:Fi(A&&"border-destructive focus-visible:ring-destructive")}),A&&a("p",{className:"text-sm text-destructive",children:A})]}),!b&&t($i,{variant:"ghost",size:"sm",onClick:P,disabled:k,className:"text-primary",children:[a(ue,{className:Fi("h-4 w-4 mr-1",k&&"animate-spin")}),g]})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>I(!1),disabled:_,children:f}),a($i,{onClick:D,disabled:!N.trim()||_,children:_?"Validando...":h})]})]})})}function hh({currentStep:e,totalSteps:r,onStepChange:i,stepLabels:o,canGoToStep:s,className:l,progressWidth:d="w-32"}){n.useEffect(()=>{process.env.NODE_ENV},[]);const c=Array.from({length:r},(e,a)=>a+1),u=a=>!(a<=e)&&(!!s&&!s(a));return t("div",{className:Fi("flex items-center gap-3",l),children:[t(Jo,{children:[a(Zo,{asChild:!0,children:t($i,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",e,"/",r,a(D,{className:"h-3 w-3 ml-1"})]})}),a(os,{align:"start",children:c.map(r=>t(ss,{onClick:()=>{var a;(a=r)<e?i(a):s&&!s(a)||i(a)},disabled:u(r),className:Fi("cursor-pointer",r===e&&"bg-muted font-medium",u(r)&&"opacity-50 cursor-not-allowed"),children:[t("span",{className:"mr-2 text-muted-foreground",children:[r,"."]}),o?.[r-1]||`Etapa ${r}`,r===e&&a(I,{className:"h-4 w-4 ml-auto"})]},r))})]}),a(Tm,{value:e/r*100,className:Fi("h-2",d)})]})}function fh({open:r,onOpenChange:n,currentStep:i,onStepChange:o,steps:s,canGoToStep:l,children:d,title:c,description:u,onSave:m,saveLabel:p=e.t("save"),nextLabel:h=e.t("next"),backLabel:f=e.t("back"),variant:g="form",isDirty:v,size:b="lg",unsavedChangesTitle:x,unsavedChangesDescription:y,cancelText:N,leaveWithoutSavingText:w,className:_,disableNext:C,hideNavigation:k,footerLeft:S}){const{t:A}=Ga(),E=s.length,D=i>=E,P=i<=1;return a(mo,{open:r,onOpenChange:n,children:t(bo,{size:b,variant:g,isDirty:v,unsavedChangesTitle:x,unsavedChangesDescription:y,cancelText:N,leaveWithoutSavingText:w,className:Fi("!p-0 !border-l-0 flex-row overflow-hidden",_),children:[t("div",{className:"hidden sm:flex w-56 flex-shrink-0 flex-col bg-primary text-primary-foreground p-6 rounded-l-lg",children:[a("h3",{className:"text-sm font-medium opacity-80 mb-6",children:"Etapas"}),a("nav",{className:"flex flex-col gap-1 flex-1",children:s.map((e,r)=>{const n=r+1,s=n===i,d=(e=>e<i)(n),c=(u=n)<=i||!l||l(u);var u;return t("button",{type:"button",onClick:()=>(e=>{e!==i&&(e<i?o(e):l&&!l(e)||o(e))})(n),disabled:!c,className:Fi("flex items-center gap-2 py-3 px-2 rounded-md text-left transition-colors text-xs",s&&"bg-primary-foreground/20 font-semibold",!s&&c&&"hover:bg-primary-foreground/10 cursor-pointer",!c&&"opacity-40 cursor-not-allowed"),children:[a("span",{className:Fi("flex items-center justify-center h-7 w-7 rounded-full text-xs font-bold flex-shrink-0 transition-colors",s&&"bg-primary-foreground text-primary",d&&!s&&"bg-primary-foreground/30 text-primary-foreground",!s&&!d&&"border-2 border-primary-foreground/40 text-primary-foreground/60"),children:d&&!s?a(I,{className:"h-3.5 w-3.5"}):n}),a("span",{className:Fi("line-clamp-2",s&&"text-primary-foreground",!s&&"text-primary-foreground/70"),children:e})]},n)})})]}),t("div",{className:"flex flex-col flex-1 min-w-0",children:[t(xo,{className:"p-6 pb-0",children:[t("p",{className:"text-xs text-muted-foreground sm:hidden mb-1",children:["Etapa ",i," de ",E]}),a(wo,{children:c}),u&&a("p",{className:"text-sm text-muted-foreground mt-1",children:u})]}),a(yo,{className:"px-6",children:d}),!k&&a(No,{className:"px-6 pb-6",children:t("div",{className:"flex items-center justify-between w-full",children:[a("div",{className:"flex items-center gap-2",children:S}),t("div",{className:"flex items-center gap-2",children:[!P&&a($i,{variant:"outline",onClick:()=>o(i-1),children:f}),a($i,D?{onClick:m,disabled:C,children:p}:{onClick:()=>o(i+1),disabled:C,children:h})]})]})})]})]})})}function gh(e){const a=Ys.getAccessToken(),t={"Content-Type":"application/json",...a?{Authorization:`Bearer ${a}`}:{},"un-alias":e};if(a)try{const e=JSON.parse(atob(a.split(".")[1]));e.sub&&(t["x-waf-rate"]=btoa(e.sub))}catch{}return t}async function vh(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await sl.handleApiError({status:401})){const n={...a,headers:gh(t)};r=await fetch(e,n)}}return r}function bh(e){const[a,t]=o([]),[r,n]=o(0),[i,s]=o(!1);m(()=>{if(!e)return;let a=!1;const r=`${xr().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){s(!0);try{const i=gh(e),o=await vh(r,{method:"GET",headers:i},e);if(!o.ok)return;const s=await o.json();!a&&s.data?.[0]&&(t(s.data[0].updates??[]),n(s.data[0].valueBadge??0))}catch(i){}finally{a||s(!1)}}(),()=>{a=!0}},[e]);const d=l(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${xr().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=gh(e),r=JSON.stringify({id:t,idUpdateType:3});await vh(i,{method:"POST",headers:a,body:r},e)}catch(o){}},[e,r,a]);return{updates:a,badgeCount:r,loading:i,markAsVisualized:d}}mh.displayName="Timepicker";const xh=i.forwardRef(({updates:r,badgeCount:n,onOpen:i,onViewAll:o},s)=>{const l=void 0===r,d=kl(),c=d?.alias??null,u=bh(l?c:null),m=l?u.updates??[]:r,p=l?u.badgeCount??0:n??0,h=i??(l?u.markAsVisualized:void 0),f=o??(l&&c?()=>{const e=`https://apps4.qualiex.com/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return t(bs,{children:[a(xs,{asChild:!0,children:t($i,{ref:s,variant:"ghost",size:"sm",className:"relative h-9 w-9 p-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:h,title:e.t("updates"),children:[a(Ye,{className:"h-7 w-7"}),p>0&&a("span",{className:"absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground",children:p>99?"99+":p})]})}),t(ys,{align:"end",className:"w-80 p-0",children:[a("div",{className:"border-b border-border px-4 py-3",children:a("h4",{className:"text-sm font-semibold text-foreground",children:"Atualizações"})}),a("div",{className:"max-h-72 overflow-y-auto",children:m.length>0?a("ul",{className:"divide-y divide-border",children:m.map(e=>t("li",{className:"px-4 py-3 hover:bg-muted/50 transition-colors cursor-pointer",onClick:f,children:[a("p",{className:"text-sm font-medium text-foreground",children:e.title}),a("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2",children:e.text})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-8 px-4 text-center",children:[a(Ye,{className:"h-8 w-8 text-muted-foreground mb-2"}),a("p",{className:"text-sm text-muted-foreground",children:"Nenhum café quentinho, ou melhor, atualização quentinha no momento!"})]})}),a("div",{className:"border-t border-border px-4 py-2",children:t($i,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:f,children:["Ver todas as atualizações",a(Oe,{className:"h-[18px] w-[18px]"})]})})]})]})});var yh,Nh,wh,_h;xh.displayName="UpdatesNotification",(Nh=yh||(yh={}))[Nh.none=0]="none",Nh[Nh.image=1]="image",Nh[Nh.video=2]="video",Nh[Nh.audio=3]="audio",Nh[Nh.wopi=4]="wopi",Nh[Nh.onlineEditor=5]="onlineEditor",Nh[Nh.report=6]="report",(_h=wh||(wh={}))[_h.SimplePrint=0]="SimplePrint",_h[_h.ManagedCopy=1]="ManagedCopy",_h[_h.NonManagedCopy=2]="NonManagedCopy";const Ch={".jpg":yh.image,".jpeg":yh.image,".png":yh.image,".bmp":yh.image,".gif":yh.image,".svg":yh.image,".webp":yh.image,".wav":yh.audio,".mp3":yh.audio,".mp4":yh.video,".webm":yh.video,".ogg":yh.video,".pdf":yh.wopi,".ods":yh.wopi,".xls":yh.wopi,".xlsb":yh.wopi,".xlsm":yh.wopi,".xlsx":yh.wopi,".doc":yh.wopi,".docm":yh.wopi,".docx":yh.wopi,".dot":yh.wopi,".dotm":yh.wopi,".dotx":yh.wopi,".odt":yh.wopi,".odp":yh.wopi,".pot":yh.wopi,".potm":yh.wopi,".potx":yh.wopi,".pps":yh.wopi,".ppsm":yh.wopi,".ppsx":yh.wopi,".ppt":yh.wopi,".pptm":yh.wopi,".pptx":yh.wopi,".gdocs":yh.onlineEditor,".gsheets":yh.onlineEditor};function kh(e){const{t:a}=Ga();return e?Ch[e.toLowerCase()]??yh.none:yh.none}function Sh(e){const{t:a}=Ga();return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"}const Ah={".pdf":"wv/wordviewerframe.aspx?PdfMode=1&",".xls":"x/_layouts/xlviewerinternal.aspx?",".xlsb":"x/_layouts/xlviewerinternal.aspx?",".xlsm":"x/_layouts/xlviewerinternal.aspx?",".xlsx":"x/_layouts/xlviewerinternal.aspx?",".ods":"x/_layouts/xlviewerinternal.aspx?",".doc":"wv/wordviewerframe.aspx?",".docm":"wv/wordviewerframe.aspx?",".docx":"wv/wordviewerframe.aspx?",".dot":"wv/wordviewerframe.aspx?",".dotm":"wv/wordviewerframe.aspx?",".dotx":"wv/wordviewerframe.aspx?",".odt":"wv/wordviewerframe.aspx?",".ppt":"p/PowerPointFrame.aspx?",".pptm":"p/PowerPointFrame.aspx?",".pptx":"p/PowerPointFrame.aspx?",".pot":"p/PowerPointFrame.aspx?",".potm":"p/PowerPointFrame.aspx?",".potx":"p/PowerPointFrame.aspx?",".pps":"p/PowerPointFrame.aspx?",".ppsm":"p/PowerPointFrame.aspx?",".ppsx":"p/PowerPointFrame.aspx?",".odp":"p/PowerPointFrame.aspx?"};function Eh(e){const{t:a}=Ga();return Ah[e?.toLowerCase()]||""}function Dh(e){const{t:a}=Ga(),{viewerUrl:t,wopiUrl:r,fileId:n,token:i,extension:o,language:s="pt-br"}=e,l=Eh(o);if(!l)return null;return`${t}${l}ui=${s}&rs=${s}&access_token=${i}&WOPISrc=${encodeURIComponent(`${r}${n}`)}`}function Ph({open:e,onOpenChange:n,template:i,viewerType:o,isLoading:s=!1,enableDownload:d=!0,onDownload:c,isDownloading:p=!1,enableFavorite:h=!1,isFavorite:f=!1,onFavorite:g,isFavoriting:v=!1,enableConfirmReading:b=!1,readingConfirmationDate:x,onConfirmReading:y,isConfirmingReading:N=!1,readingConfirmationTimeRemaining:w,onIframeLoad:_,className:C}){const{t:k}=Ga(),S=u(null),A=o??kh(i.extension),D=p||N||v,P=i.code?`${i.code} – ${i.name}`:i.name,I=l(()=>{S.current&&_&&_(S.current)},[_]);return m(()=>{if(!e)return;const a=e=>{"Escape"===e.key&&n(!1)};return window.addEventListener("keyup",a),()=>window.removeEventListener("keyup",a)},[e,n]),a(mo,{open:e,onOpenChange:n,children:t(bo,{className:Fi("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(A===yh.wopi||A===yh.report)&&"w-[90vw]",C),children:[t("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[a("h2",s?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-200px)]",children:P}),t("div",{className:"flex items-center gap-1 ml-4 z-20",children:[!s&&t(r,{children:[(b||x)&&a(r,{children:x?t("div",{className:"flex flex-col mr-2.5",children:[t("span",{className:"text-sm font-medium flex items-center gap-1 text-foreground",children:[a(Qe,{className:"h-4 w-4"}),"Leitura confirmada"]}),a("span",{className:"text-xs text-muted-foreground ml-5",children:x.toLocaleDateString()})]}):null!=w&&w>0?t("div",{className:"flex items-center gap-1 mr-2.5 text-sm text-muted-foreground",children:[a("span",{children:k("terms_confirmation_available")}),a("span",{className:"font-medium min-w-[72px]",children:Ih(w)}),a("span",{children:"segundos"})]}):t($i,{variant:"default",size:"sm",disabled:D,onClick:()=>y?.(),className:"mr-2.5",children:[a(Ge,{className:"h-4 w-4 mr-1"}),N?"Confirmando...":k("terms_confirm_reading")]})}),A!==yh.none&&h&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>g?.(f),children:a(Xe,{className:Fi("h-4 w-4",f&&"fill-accent text-accent")})})}),a(gs,{children:f?"Desfavoritar":"Favoritar"})]}),A!==yh.none&&d&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>c?.(),children:a(Je,{className:"h-4 w-4"})})}),a(gs,{children:"Download"})]})]}),t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>n(!1),children:a(E,{className:"h-4 w-4"})})}),a(gs,{children:"Fechar"})]})]})]}),a("div",{className:Fi("flex flex-col items-center justify-center min-h-[160px] w-full",s&&"relative -top-5",A===yh.none&&"min-h-[124px]",A===yh.image&&"max-h-[85vh]",(A===yh.wopi||A===yh.report)&&"min-w-[77vw] min-h-[80vh]"),children:s?a(Yo,{className:"h-14 w-14"}):t(r,{children:[(A===yh.none||!i.url)&&t("div",{className:"text-center",children:[a("p",{className:"text-base text-foreground mb-1",children:"Extensão não suportada para visualização."}),a("b",{className:"text-base text-foreground",children:"Deseja fazer o download do arquivo?"})]}),A===yh.image&&a("img",{loading:"eager",src:i.url,alt:i.name,className:"max-w-full max-h-[85vh] object-contain"}),A===yh.video&&a("video",{controls:!0,autoPlay:!0,src:i.url,className:"w-full h-full"}),A===yh.audio&&a("audio",{controls:!0,autoPlay:!0,src:i.url}),(A===yh.wopi||A===yh.report)&&t("div",{className:"relative w-full h-[79.5vh]",children:[a(Yo,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),a("iframe",{ref:S,src:i.url,onLoad:I,className:"border-none w-full h-full z-[1] relative",title:i.name})]})]})}),!s&&A===yh.none&&t("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[a($i,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),d&&a($i,{variant:"default",onClick:()=>c?.(),children:"Download"})]})]})})}function Ih(e){const{t:a}=Ga(),t=e%60;return`${Math.floor(e/60)}min ${t<10?"0":""}${t}`}function Th({open:e,onOpenChange:r,identifier:n,fileName:i,mode:s="edit",type:d="document",onClose:c,className:u}){const[p,h]=o(!0),f=function(e,a="edit",t="document"){return`https://docs.google.com/${t}/d/${e}/${a}?usp=drivesdk?embedded=true&rm=demo`}(n,s,d);m(()=>{if(e){h(!0);const e=setTimeout(()=>h(!1),300);return()=>clearTimeout(e)}},[e]);const g=l(()=>{c?.(),r(!1)},[c,r]);return m(()=>{if(!e)return;const a=e=>{"Escape"===e.key&&g()};return window.addEventListener("keyup",a),()=>window.removeEventListener("keyup",a)},[e,g]),a(mo,{open:e,onOpenChange:r,children:t(bo,{className:Fi("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",u),children:[t("div",{className:"flex items-center justify-between mb-6 min-h-[30px]",children:[a("h2",p?{className:"text-lg font-medium text-foreground truncate",children:"Carregando..."}:{className:"text-lg font-medium text-foreground truncate max-w-[calc(100%-80px)]",children:i}),a("div",{className:"flex items-center ml-4 z-20",children:t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:g,children:a(E,{className:"h-4 w-4"})})}),a(gs,{children:"Fechar"})]})})]}),a("div",{className:"flex flex-col items-center justify-center min-h-[160px] w-full min-w-[77vw] min-h-[80vh]",children:p?a(Yo,{className:"h-14 w-14"}):t("div",{className:"relative w-full h-[79.5vh]",children:[a(Yo,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-16 w-16"}),a("iframe",{src:f,className:"border-none w-full h-full z-[1] relative",title:i})]})})]})})}function Rh({open:e,onOpenChange:r,url:n,title:i,className:o,minHeight:s="250px"}){const{t:d}=Ga(),c=l(()=>{r(!1)},[r]);return m(()=>{if(!e)return;const a=e=>{"Escape"===e.key&&c()};return window.addEventListener("keyup",a),()=>window.removeEventListener("keyup",a)},[e,c]),a(mo,{open:e,onOpenChange:r,children:t(bo,{className:Fi("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",o),children:[t("div",{className:"flex items-center justify-end mb-2.5",children:[i&&a("h2",{className:"text-lg font-medium text-foreground truncate mr-auto",children:i}),t(hs,{children:[a(fs,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c,children:a(E,{className:"h-4 w-4"})})}),a(gs,{children:"Fechar"})]})]}),a("iframe",{src:n,className:"border-none w-full",style:{minHeight:s},title:i||d("embedded_content")})]})})}function Mh({term:n,open:i,onClose:s,onAgree:d,title:c=e.t("terms_updated"),seeLaterLabel:u=e.t("terms_see_later"),agreeLabel:m=e.t("terms_read_agree"),viewTermLabel:p=e.t("terms_view")}){const[h,f]=o(!1),g=l(()=>{d(n.id)},[d,n.id]);return t(r,{children:[a(mo,{open:i&&!h,onOpenChange:e=>!e&&s(),children:t(bo,{className:"sm:max-w-md",children:[a(xo,{children:t(wo,{className:"flex items-center gap-2",children:[a(Ge,{className:"h-5 w-5 text-primary"}),c]})}),t("div",{className:"space-y-4",children:[n.description&&a(Dd,{className:"max-h-48",children:a("div",{className:"text-sm text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:n.description}})}),n.file&&t($i,{variant:"link",className:"px-0 text-primary",onClick:()=>f(!0),children:[a(pe,{className:"mr-1 h-4 w-4"}),p]})]}),t(No,{className:"gap-2 sm:gap-0",children:[a($i,{variant:"ghost",onClick:s,children:u}),a($i,{onClick:g,children:m})]})]})}),h&&a(Lh,{term:n,open:h,onClose:()=>f(!1),viewOnly:!0})]})}function Lh({term:r,open:n,onClose:i,onSign:o,viewOnly:d=!1,title:c=e.t("terms_of_use"),signLabel:u=e.t("terms_read_agree")}){const m=s(()=>r.file?function(e,a=""){const{t:t}=Ga(),r=atob(e),n=[];for(let o=0;o<r.length;o+=512){const e=r.slice(o,o+512),a=new Array(e.length);for(let t=0;t<e.length;t++)a[t]=e.charCodeAt(t);n.push(new Uint8Array(a))}const i=new Blob(n,{type:a});return URL.createObjectURL(i)}(r.file,r.type):null,[r.file,r.type]),p=l(()=>{m&&URL.revokeObjectURL(m),i()},[m,i]),h=l(()=>{r.hasUserSignature?p():o?.(r.id)},[r,o,p]),f=!d&&!r.hasUserSignature&&o;return a(mo,{open:n,onOpenChange:e=>!e&&p(),children:t(bo,{className:Fi("flex flex-col p-0 sm:max-w-[80vw] h-[95vh]","[&>button.absolute]:hidden"),children:[t("div",{className:"flex items-center justify-between border-b px-4 py-3",children:[t("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[a(Be,{className:"h-5 w-5 text-primary"}),c]}),t("div",{className:"flex items-center gap-2",children:[f&&a($i,{size:"sm",onClick:h,children:u}),a($i,{variant:"ghost",size:"icon",onClick:p,children:a(E,{className:"h-4 w-4"})})]})]}),a("div",{className:"flex-1 min-h-0",children:r.file&&m?a("iframe",{className:"h-full w-full border-0",src:m,title:c}):a("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:a("p",{children:"Nenhum termo de uso ativo encontrado."})})})]})})}function zh(e){return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Fh({users:r,groups:n=[],value:i,onChange:d,disabled:c=!1,maxHeight:u=350,hideGroupFilter:m=!1,searchPlaceholder:p="Buscar usuário...",selectLabel:h="Selecionar",doneLabel:f="Concluir",allLabel:g="Todos",emptyLabel:v=e.t("leadership_no_user_selected"),selectedLabel:b="selecionado",selectedPluralLabel:x="selecionados",className:y}){const[N,w]=o(!1),[_,C]=o(""),[k,S]=o(void 0),A=s(()=>new Set(i),[i]),E=s(()=>{let e=r;if(k&&(e=e.filter(e=>e.groupIds?.includes(k))),_){const a=zh(_);e=e.filter(e=>zh(e.name).includes(a)||zh(e.email??"").includes(a))}return e},[r,k,_]),D=s(()=>N?E:r.filter(e=>A.has(e.id)),[N,E,r,A]),P=i.length,I=s(()=>E.length>0&&E.every(e=>A.has(e.id)),[E,A]),T=l(e=>{if(c)return;const a=A.has(e)?i.filter(a=>a!==e):[...i,e];d(a)},[i,A,d,c]),R=l(e=>{if(c)return;const a=new Set(E.map(e=>e.id));if(e){const e=new Set([...i,...a]);d(Array.from(e))}else d(i.filter(e=>!a.has(e)))},[i,E,d,c]),M=l(()=>{w(e=>!e),C(""),S(void 0)},[]);return t("div",{className:Fi("rounded-md border bg-muted/30",y),children:[(!c||P>0)&&t("div",{className:Fi("flex items-center justify-between px-4 py-2",!c&&"cursor-pointer hover:bg-muted/50"),onClick:c?void 0:M,children:[a("span",{className:"text-sm font-medium text-primary uppercase",children:!c&&(N?f:h)}),a("span",{className:"text-xs text-muted-foreground",children:P>0&&`${P} ${1===P?b:x}`})]}),t("div",{className:"px-4 pb-3",children:[N&&t("div",{className:"flex gap-3 mb-3",children:[!m&&n.length>0&&t(Mo,{value:k??"__all__",onValueChange:e=>S("__all__"===e?void 0:e),children:[a(Fo,{className:"w-[200px] h-9 text-sm",children:a(zo,{placeholder:e.t("approval_user_group")})}),t(Oo,{children:[a($o,{value:"__all__",children:e.t("team_all_groups")}),n.map(e=>a($o,{value:e.id,children:e.name},e.id))]})]}),t("div",{className:"relative flex-1",children:[a(B,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{className:"pl-8 h-9 text-sm",placeholder:p,value:_,onChange:e=>C(e.target.value)})]})]}),!N&&0===P&&t("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:[a(Ze,{className:"h-4 w-4 mr-2"}),v]}),N&&E.length>0&&t("div",{className:"flex items-center gap-2 mb-2",children:[a(qo,{checked:I,onCheckedChange:e=>R(!!e)}),a("span",{className:"text-sm",children:g})]}),D.length>0&&a(Dd,{style:{maxHeight:u},className:"pr-2",children:a("div",{className:"space-y-0.5",children:D.map(e=>{return t("div",{className:Fi("flex items-center gap-3 rounded-md bg-background px-3 py-2 text-sm",N&&!c&&"cursor-pointer hover:bg-accent/50"),onClick:N?()=>T(e.id):void 0,children:[N&&a(qo,{checked:A.has(e.id),onCheckedChange:()=>T(e.id),onClick:e=>e.stopPropagation()}),t(bu,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(xu,{src:e.avatar,alt:e.name}),a(yu,{className:"text-xs",children:(r=e.name,r.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join(""))})]}),t("div",{className:"flex flex-col min-w-0",children:[a("span",{className:"font-normal truncate",children:e.name}),e.email&&a("span",{className:"text-xs text-muted-foreground truncate",children:e.email})]})]},e.id);var r})})}),N&&0===E.length&&a("div",{className:"flex items-center justify-center py-4 text-sm text-muted-foreground",children:"Nenhum usuário encontrado"})]})]})}function Uh(e){const{t:a}=Ga();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function jh(e){const{t:a}=Ga(),t=new Set;if(!e)return t;for(const r of e)r.allowedIds?.forEach(e=>t.add(e)),r.inheritedIds?.forEach(e=>t.add(e));return t}function Oh({items:r,categories:n,value:i,onChange:d,readonly:c=!1,isLoading:u=!1,title:m=e.t("permissions"),addButtonLabel:p=e.t("allow"),chipsTitle:h=e.t("allowed_items"),chipsPlaceholder:f=e.t("no_item_selected"),searchPlaceholder:g=e.t("search_placeholder"),selectPlaceholder:v=e.t("select_items_to_add"),itemInfoTemplate:b=e=>`${e} ${1===e?"item":"itens"}`,disclaimer:x,disclaimerLink:y,onDisclaimerClick:N,className:w}){const[_,C]=o(n[0]?.id??""),[k,S]=o(""),[A,P]=o([]),[T,R]=o(!1),M=s(()=>jh(i[_]),[i,_]),L=s(()=>function(e){const{t:a}=Ga(),t=new Set;if(!e)return t;for(const r of e)r.inheritedIds?.forEach(e=>t.add(e));return t}(i[_]),[i,_]),z=s(()=>r.filter(e=>M.has(e.id)),[r,M]),F=s(()=>{const e=Uh(k);return r.filter(a=>!M.has(a.id)&&!(e&&!Uh(a.name).includes(e)))},[r,M,k]),U=s(()=>{const e={};for(const a of n)e[a.id]=jh(i[a.id]).size;return e},[n,i]),j=l(e=>{C(e),P([]),S("")},[]),O=l(e=>{P(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),$=l(()=>{if(0===A.length)return;const e=[...i[_]??[]];for(const a of A){const t=r.find(e=>e.id===a),n=t?.group??"default",i=e.find(e=>e.context===n);i?i.allowedIds.includes(a)||(i.allowedIds=[...i.allowedIds,a]):e.push({context:n,allowedIds:[a],inheritedIds:[]})}d({...i,[_]:e}),P([]),S(""),R(!1)},[A,i,_,r,d]),V=l(e=>{if(L.has(e))return;const a=(i[_]??[]).map(a=>({...a,allowedIds:a.allowedIds.filter(a=>a!==e)}));d({...i,[_]:a})},[i,_,L,d]);return u?t("div",{className:Fi("rounded-md border bg-muted/30 p-4 animate-pulse space-y-3",w),children:[a("div",{className:"h-4 w-32 bg-muted rounded"}),a("div",{className:"h-9 w-full bg-muted rounded"}),a("div",{className:"h-20 w-full bg-muted rounded"})]}):a("div",{className:Fi("rounded-md border bg-muted/30",w),children:t("div",{className:"p-4 space-y-4",children:[t("div",{className:"space-y-2",children:[a("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:m}),t(Mo,{value:_,onValueChange:j,children:[a(Fo,{className:"h-9 text-sm",children:a(zo,{})}),a(Oo,{children:n.map(e=>a($o,{value:e.id,children:t("span",{className:"flex items-center gap-2",children:[e.icon,e.name,U[e.id]>0&&a(Go,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:U[e.id]})]})},e.id))})]})]}),!c&&t("div",{className:"flex gap-2",children:[t(bs,{open:T,onOpenChange:R,children:[a(xs,{asChild:!0,children:t($i,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[A.length>0?`${A.length} selecionado${A.length>1?"s":""}`:v,a(D,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t(ys,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:[a("div",{className:"p-2 border-b",children:t("div",{className:"relative",children:[a(B,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{className:"pl-8 h-8 text-sm",placeholder:g,value:k,onChange:e=>S(e.target.value)})]})}),a(Dd,{className:"max-h-[220px]",children:0===F.length?a("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Nenhum item encontrado"}):a("div",{className:"p-1",children:F.map(e=>{const r=A.includes(e.id);return t("div",{className:Fi("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",r&&"bg-accent/50"),onClick:()=>O(e.id),children:[a("div",{className:Fi("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",r&&"bg-primary text-primary-foreground"),children:r&&a(I,{className:"h-3 w-3"})}),t("div",{className:"flex flex-col min-w-0",children:[a("span",{className:"truncate",children:e.name}),null!=e.count&&a("span",{className:"text-xs text-muted-foreground",children:b(e.count)})]})]},e.id)})})})]})]}),t($i,{size:"sm",className:"h-9 gap-1",disabled:0===A.length,onClick:$,children:[a(Q,{className:"h-4 w-4"}),p]})]}),t("div",{className:"space-y-2",children:[a("p",{className:"text-sm font-medium",children:h}),a("div",{className:Fi("rounded-md border bg-background p-3 min-h-[60px]",c&&"bg-muted/50"),children:0===z.length?a("span",{className:"text-sm text-muted-foreground",children:f}):a("div",{className:"flex flex-wrap gap-1.5",children:z.map(e=>{const r=L.has(e.id);return t(Go,{variant:r?"secondary":"default",className:"gap-1 pl-2 pr-1 py-1 text-xs",children:[e.name,!c&&!r&&a("button",{type:"button",className:"ml-0.5 rounded-full hover:bg-primary-foreground/20 p-0.5",onClick:()=>V(e.id),children:a(E,{className:"h-3 w-3"})})]},e.id)})})}),c&&x&&t("p",{className:"text-xs text-muted-foreground",children:[a("span",{dangerouslySetInnerHTML:{__html:x}})," ",y&&N&&a("button",{type:"button",className:"text-primary underline hover:no-underline",onClick:N,children:y})]})]})]})})}var Bh,$h;($h=Bh||(Bh={}))[$h.WaitingProcessing=1]="WaitingProcessing",$h[$h.Processing=2]="Processing",$h[$h.Completed=3]="Completed",$h[$h.Error=4]="Error",$h[$h.Expired=5]="Expired";const Vh={report:e.t("report"),status:e.t("status"),requestDate:e.t("request_date"),lastUpdate:e.t("last_update"),expirationDate:e.t("expiration_date"),viewReport:e.t("view_report"),searchPlaceholder:e.t("search_report_placeholder"),noResults:e.t("no_reports_found"),statusWaiting:e.t("status_waiting"),statusProcessing:e.t("status_processing"),statusCompleted:e.t("status_completed"),statusError:e.t("status_error"),statusExpired:e.t("status_expired")};function qh(e){const{t:a}=Ga();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Wh(e){const{t:a}=Ga();return e.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Hh({requests:e,isLoading:n=!1,onGetReportUrl:i,formatDate:d=Wh,labels:c,className:u}){const{t:m}=Ga(),p={...Vh,...c},[h,f]=o(""),[g,v]=o(!1),[b,x]=o(""),[y,N]=o(""),[w,_]=o(null),C=s(()=>{if(!h)return e;const a=qh(h);return e.filter(e=>qh(e.reportName).includes(a))},[e,h]),k=l(async e=>{if(!w){_(e.id);try{const a=await i(e.id);a&&(x(a),N(e.reportName),v(!0))}finally{_(null)}}},[i,w]);return n?a("div",{className:Fi("space-y-3",u),children:Array.from({length:5}).map((e,t)=>a(Ps,{className:"h-12 w-full"},t))}):t(r,{children:[t("div",{className:Fi("space-y-3",u),children:[t("div",{className:"relative max-w-sm",children:[a(B,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{className:"pl-8 h-9 text-sm",placeholder:p.searchPlaceholder,value:h,onChange:e=>f(e.target.value)})]}),a(Dd,{className:"rounded-md border",children:t(Pl,{children:[a(Il,{children:t(Ml,{children:[a(Ll,{className:"min-w-[140px]",children:p.report}),a(Ll,{className:"min-w-[150px]",children:p.status}),a(Ll,{className:"min-w-[160px]",children:p.requestDate}),a(Ll,{className:"min-w-[160px]",children:p.lastUpdate}),a(Ll,{className:"min-w-[160px]",children:p.expirationDate}),a(Ll,{className:"min-w-[140px]"})]})}),a(Tl,{children:0===C.length?a(Ml,{children:a(zl,{colSpan:6,className:"text-center text-muted-foreground py-8",children:p.noResults})}):C.map(e=>{const r=function(e){const{t:a}=Ga();return new Date>new Date(e.expirationDate)&&e.statusId===Bh.Completed?Bh.Expired:e.statusId}(e),n=function(e,t){const{t:r}=Ga();switch(e){case Bh.WaitingProcessing:return{label:t.statusWaiting,icon:a(ta,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case Bh.Processing:return{label:t.statusProcessing,icon:a(ue,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case Bh.Completed:return{label:t.statusCompleted,icon:a(aa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case Bh.Error:return{label:t.statusError,icon:a(O,{className:"h-3.5 w-3.5"}),variant:"danger"};case Bh.Expired:return{label:t.statusExpired,icon:a(ea,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-orange-600 border-orange-300 bg-orange-50"};default:return{label:"—",icon:null,variant:"secondary"}}}(r,p),i=r===Bh.Completed,o=r===Bh.Expired;return t(Ml,{children:[a(zl,{className:"font-medium",children:e.reportName}),a(zl,{children:t(Go,{variant:n.variant,className:Fi("gap-1",n.className),children:[n.icon,n.label]})}),a(zl,{className:"text-sm",children:d(new Date(e.requestDate))}),a(zl,{className:"text-sm",children:d(new Date(e.lastUpdate))}),a(zl,{className:Fi("text-sm",o&&"text-destructive"),children:d(new Date(e.expirationDate))}),a(zl,{children:t($i,{variant:"ghost",size:"sm",className:"gap-1.5",disabled:!i||w===e.id,onClick:()=>k(e),children:[w===e.id?a(T,{className:"h-4 w-4 animate-spin"}):a(Ce,{className:"h-4 w-4"}),p.viewReport]})})]},e.id)})})]})})]}),a(Rh,{open:g,onOpenChange:v,url:b,title:y})]})}function Gh({reportApiUrl:e,parameters:t={},minHeight:r="80vh",...n}){const i=s(()=>{const a=`${e}/api/reports/v1/Viewer/InitViewer`,r=new URLSearchParams(t).toString();return r?`${a}?${r}`:a},[e,t]);return a(Rh,{...n,url:i,minHeight:r})}const Kh={sm:{badge:"px-1.5 py-0.5 text-[11px] gap-1",icon:14},md:{badge:"px-2.5 py-1 text-xs gap-1.5",icon:16},lg:{badge:"px-3 py-1.5 text-sm gap-2",icon:18}};function Yh({label:e,color:r,icon:n,showIcon:i,size:o="md",variant:s="filled",backgroundColor:l,className:d}){const c=Kh[o],u=i??!!n;return t("span",{className:Fi("inline-flex items-center rounded-md font-medium whitespace-nowrap","outline"===s&&"border",c.badge,d),style:(()=>{switch(s){case"outline":return{color:r,borderColor:Ti(r,.3),backgroundColor:"transparent"};case"ghost":return{color:r,backgroundColor:"transparent"};default:return{color:r,backgroundColor:l||Ti(r,.1)}}})(),children:[u&&n&&a(n,{size:c.icon,strokeWidth:2}),e]})}function Qh(e){return a=>e[a]}var Xh,Jh,Zh,ef,af,tf,rf,nf,of,sf,lf,df,cf,uf,mf,pf,hf,ff,gf,vf,bf,xf,yf,Nf,wf,_f,Cf,kf,Sf,Af,Ef,Df,Pf,If,Tf,Rf,Mf,Lf,zf,Ff,Uf,jf,Of,Bf,$f,Vf,qf,Wf,Hf,Gf,Kf;(Jh=Xh||(Xh={})).Count="valuecount",Jh.Sum="sum",Jh.Average="average",Jh.DistinctCount="valuecount_distict",Jh.Max="max",Jh.Min="min",(Zh||(Zh={})).ViewAllAnalysis="nes3j6wn",(af=ef||(ef={})).RegisterDashboards="EeKs7CYA",af.RemoveDashboards="3GKZYOQ9",af.ViewAllDashboards="wYBdQNvZ",af.EditDashboards="bMFcbwv4",(rf=tf||(tf={}))[rf.Default=1]="Default",rf[rf.Compact=2]="Compact",(of=nf||(nf={}))[of.FiveSeconds=1]="FiveSeconds",of[of.TenSeconds=2]="TenSeconds",of[of.FifteenSeconds=3]="FifteenSeconds",of[of.ThirtySeconds=4]="ThirtySeconds",of[of.OneMinute=5]="OneMinute",of[of.ThreeMinutes=6]="ThreeMinutes",of[of.FiveMinutes=7]="FiveMinutes",of[of.TenMinutes=8]="TenMinutes",(lf=sf||(sf={}))[lf.Day=1]="Day",lf[lf.Month=2]="Month",lf[lf.Year=3]="Year",(cf=df||(df={}))[cf.Ascending=1]="Ascending",cf[cf.Descending=2]="Descending",(mf=uf||(uf={}))[mf.Label=1]="Label",mf[mf.Value=2]="Value",(hf=pf||(pf={}))[hf.LastSevenDays=1]="LastSevenDays",hf[hf.LastWeek=2]="LastWeek",hf[hf.LastMonth=3]="LastMonth",hf[hf.PreviousQuarter=4]="PreviousQuarter",hf[hf.PreviousSemester=5]="PreviousSemester",hf[hf.LastYear=6]="LastYear",hf[hf.SpecificPeriod=7]="SpecificPeriod",hf[hf.CurrentMonth=8]="CurrentMonth",hf[hf.CurrentSemester=9]="CurrentSemester",hf[hf.CurrentWeek=10]="CurrentWeek",hf[hf.CurrentYear=11]="CurrentYear",(gf=ff||(ff={}))[gf.Text=1]="Text",gf[gf.Area=2]="Area",gf[gf.Bar=3]="Bar",gf[gf.Column=4]="Column",gf[gf.StackedColumn=5]="StackedColumn",gf[gf.Line=6]="Line",gf[gf.List=7]="List",gf[gf.Numeric=8]="Numeric",gf[gf.Pareto=9]="Pareto",gf[gf.Pie=10]="Pie",gf[gf.RiskMatrix=11]="RiskMatrix",gf[gf.Burndown=12]="Burndown",gf[gf.PerformanceColumns=13]="PerformanceColumns",gf[gf.EvolutionLine=14]="EvolutionLine",(bf=vf||(vf={}))[bf.NotUpdate=1]="NotUpdate",bf[bf.FiveMinutes=2]="FiveMinutes",bf[bf.TenMinutes=3]="TenMinutes",bf[bf.FifteenMinutes=4]="FifteenMinutes",bf[bf.ThirtyMinutes=5]="ThirtyMinutes",bf[bf.OneHour=6]="OneHour",(yf=xf||(xf={}))[yf.NormalPage=1]="NormalPage",yf[yf.Carousel=2]="Carousel",(wf=Nf||(Nf={}))[wf.General=0]="General",wf[wf.Share=1]="Share",(Cf=_f||(_f={}))[Cf.NotShared=1]="NotShared",Cf[Cf.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",Cf[Cf.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(Sf=kf||(kf={})).PtBr="pt-br",Sf.EnUs="en",Sf.EsEs="es",(Ef=Af||(Af={}))[Ef.Quantity=0]="Quantity",Ef[Ef.AllRisksList=1]="AllRisksList",(Pf=Df||(Df={}))[Pf.Five=5]="Five",Pf[Pf.Ten=10]="Ten",Pf[Pf.Fifteen=15]="Fifteen",Pf[Pf.Twenty=20]="Twenty",Pf[Pf.All=0]="All",Pf[Pf.Custom=-1]="Custom",(Tf=If||(If={}))[Tf.AlphabeticalAsc=1]="AlphabeticalAsc",Tf[Tf.AlphabeticalDesc=2]="AlphabeticalDesc",Tf[Tf.CountAsc=3]="CountAsc",Tf[Tf.CountDesc=4]="CountDesc",Tf[Tf.DateAsc=5]="DateAsc",Tf[Tf.DateDesc=6]="DateDesc",(Mf=Rf||(Rf={}))[Mf.Loading=0]="Loading",Mf[Mf.Loaded=1]="Loaded",Mf[Mf.Error=3]="Error",Mf[Mf.NoData=4]="NoData",Mf[Mf.Unavailable=5]="Unavailable",(zf=Lf||(Lf={}))[zf.Quantity=1]="Quantity",zf[zf.Percentage=2]="Percentage",zf[zf.QuantityPercentage=3]="QuantityPercentage",(Uf=Ff||(Ff={}))[Uf.Program=1]="Program",Uf[Uf.Project=2]="Project",Uf[Uf.Action=3]="Action",Uf[Uf.PerformanceProject=4]="PerformanceProject",Uf[Uf.PerformanceAction=5]="PerformanceAction",(Of=jf||(jf={})).OccurrenceActionPlans="xebGnSSq",Of.OccurrenceGeneral="UFws4AvH",Of.PlansActionPlans="Kux6CcVC",Of.PlansProgramProjects="UWjrp6Dw",Of.PlansIdeas="3g7vNm2w",Of.RisksGeneral="PZ4b6FhP",Of.RisksActionPlans="xZErDg57",Of.RisksAnalysis="UxsioMbH",Of.RisksIncidences="gNt5IJ2F",Of.MetrologyGeneral="4MfEPbRY",Of.MetrologyActivities="hdFM9XQW",Of.MetrologyServiceOrders="cIrVPdMv",Of.DecisionsGeneral="CopsnHDB",Of.DecisionsItems="qLFAayjx",Of.DecisionsActionPlans="RiQFpxdb",Of.FlowGeneral="AFV98JoG",Of.AuditGeneral="gON8LJPi",Of.AuditPlans="SsCNVOvr",Of.AuditPlansItems="OpPkCCFm",Of.AuditActionPlans="P1oGePhh",Of.CommonGeneral="VVfEzgMQ",Of.ActionPlans="C6Z4MgGa",Of.SuppliersEvaluations="fSCeS4mH",Of.SuppliersGeneral="8qPThkrD",Of.SuppliersEvaluationsCriteria="RiSIStdY",Of.SuppliersDocuments="Riua4jMa",Of.SuppliersMaterialsServices="UpEkatXH",Of.DocumentsGeneral="FRhhEX2J",Of.DocumentsPhysicalCopies="PZLtJ23h",Of.DocumentsObsolete="XDjbga14",Of.FmeaGeneral="aPwf4uPr",Of.FmeaActionPlans="vQ8PMrVX",($f=Bf||(Bf={}))[$f.NotShared=1]="NotShared",$f[$f.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",$f[$f.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(qf=Vf||(Vf={}))[qf.All=1]="All",qf[qf.OnlyMine=2]="OnlyMine",qf[qf.Favorites=3]="Favorites",(Hf=Wf||(Wf={}))[Hf.Current=1]="Current",Hf[Hf.Inherent=2]="Inherent",(Kf=Gf||(Gf={}))[Kf.Default=1]="Default",Kf[Kf.Pastel=2]="Pastel",Kf[Kf.Vibrant=3]="Vibrant",Kf[Kf.Earth=4]="Earth",Kf[Kf.Ocean=5]="Ocean",Kf[Kf.Floral=6]="Floral",Kf[Kf.Night=7]="Night",Kf[Kf.Winter=8]="Winter",Kf[Kf.Spring=9]="Spring",Kf[Kf.Summer=10]="Summer",Kf[Kf.Fall=11]="Fall",Kf[Kf.Gray=12]="Gray",Kf[Kf.Brown=13]="Brown",Kf[Kf.Blue=14]="Blue",Kf[Kf.Yellow=15]="Yellow",Kf[Kf.Green=16]="Green",Kf[Kf.Purple=17]="Purple",Kf[Kf.Orange=18]="Orange",Kf[Kf.Pink=19]="Pink",Kf[Kf.Red=20]="Red";const Yf={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},Qf={advancedFilter:"analysisDashboardsListFilter"},Xf=["total_calibration_cost","total_verification_cost","total_maintenance_cost","last_calibration_cost","last_verification_cost","last_maintenance_cost","total_cost","total_reported_cost","estimated_cost","last_report_cost_reported_cost","occurrence_reported_cost","task_estimated_cost"],Jf=["link","link_risk","risk_link","link_group","group_link","link_occurrence","occurrence_link","link_audit","link_project","link_program","link_ideia","flow_link","decision_link","link_supplier","auditing_link","fmea_link"];function Zf(e){return e?.sort((e,a)=>{if(!e?.items?.length||!a?.items?.length)return 0;return eg(e.items[0]?.keyDate)-eg(a.items[0]?.keyDate)})}function eg(e){if(!e)return 0;const[a,t]=e.split("/"),r=Yf[a?.toLowerCase()]??0;return 12*(parseInt(t)||0)+r}function ag(e){return null==e?.value||""===e.value.trim()}function tg(e){const a=e.split("/"),t=a[a.length-1];return`${a.slice(0,-1).join("/")}/${encodeURIComponent(t.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function rg(e){for(const a of Jf)if(e[a])return e[a];return null}function ng(e){return e?ig(e).join("&"):null}function ig(e){const a=[];for(const t of Object.keys(e)){const r=e[t];null!=r&&(r instanceof Date?a.push(`${t}=${r.toISOString()}`):Array.isArray(r)?r.forEach(e=>{a.push(...ig({[t]:e}))}):"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||a.push(`${t}=${r}`))}return a}const og=/^-?\d+(,\d{3})*(\.\d+)?$/;function sg(e){return!!og.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))}function lg(e){const a=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(a)}const dg=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});function cg(e){e.forEach(a=>{a.children=e.filter(e=>e.parentId===a.id)});const a=e.filter(e=>!e.parentId);return function e(a,t){a?.forEach(a=>{t(a),a.children&&e(a.children,t)})}(a,a=>{a.children=e.filter(e=>e.parentId===a.id)}),a}const ug=new Set([ff.Text]),mg=new Set([ff.Text,ff.Numeric,ff.RiskMatrix,ff.Burndown,ff.PerformanceColumns]),pg=new Set([ff.Text,ff.RiskMatrix,ff.Burndown,ff.PerformanceColumns]);function hg({config:e,viewOnly:n=!1,complement:i,complementPosition:d="before-options",queryUrlBuilder:c,onRefresh:u,onExport:m,onToggleOnlyMine:p,className:h}){const{t:f}=Ga(),[g,v]=o(e.onlyMine??!1),b=ug.has(e.typeId),x=!mg.has(e.typeId),y=!pg.has(e.typeId),N=s(()=>{if(!e.jsonRules||e.typeId===ff.PerformanceColumns)return!1;try{const a=JSON.parse(e.jsonRules);return a?.rules?.rules?.length>0}catch{return!1}},[e.jsonRules,e.typeId]),w=s(()=>c?.(e)??"#",[c,e]),_=l(()=>{const e=!g;v(e),p?.(e)},[g,p]),C=[];return g&&C.push(f("dashboard_only_mine")),e.onlyLate&&C.push(f("dashboard_only_overdue")),N&&C.push(f("dashboard_advanced_filter")),t("div",{className:Fi("flex items-center justify-between gap-2 border-b bg-muted/30 px-2.5 py-1 text-sm font-medium",h),children:[t("div",{className:"flex min-w-0 flex-wrap items-center gap-1",children:["before-title"===d&&i,t("div",{className:"flex min-w-0 flex-col",children:[t(hs,{children:[a(fs,{asChild:!0,children:a("span",{className:"block truncate",children:e.title})}),a(gs,{children:e.title})]}),C.length>0&&a("span",{className:"text-[9px] font-normal text-muted-foreground truncate",children:C.join(" | ")})]}),"after-title"===d&&i]}),!n&&t("div",{className:"flex shrink-0 items-center gap-0.5",children:["before-options"===d&&i,t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",className:"h-6 w-6",children:a(ra,{className:"h-3.5 w-3.5"})})}),t(os,{align:"end",className:"w-48",children:[e.canUpdate&&t(ss,{onClick:()=>e.onEdit?.(e.id),children:[a(G,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!b&&t(ss,{onClick:u,children:[a(ue,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),x&&t(ss,{disabled:e.noData,onClick:m,children:[a(Je,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!b&&t(ss,{disabled:!e.openQueryEnabled,onClick:()=>window.open(w,"_blank"),children:[a(pe,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),y&&t(r,{children:[a(us,{}),t(ss,{onClick:_,children:[g&&a(I,{className:"mr-2 h-3.5 w-3.5"}),!g&&a("span",{className:"mr-2 w-3.5"}),"Somente meus"]})]}),e.canUpdate&&t(r,{children:[a(us,{}),t(ss,{onClick:()=>e.onDuplicate?.(e.id),children:[a(me,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),t(ss,{className:"text-destructive",onClick:()=>e.onRemove?.(e.id),children:[a(H,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===d&&i]})]})}function fg({config:e,queryUrl:r,className:n}){return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[a(de,{className:"h-12 w-12 text-muted-foreground/50"}),a("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"Erro ao exibir os dados."}),a("p",{className:"text-sm text-muted-foreground",children:"A consulta não pôde ser realizada."}),t("p",{className:"mt-2 text-xs",children:[r&&a("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:text-primary/80",children:"Verificar a consulta"}),r&&e.canUpdate&&a("span",{className:"text-muted-foreground",children:" ou "}),e.canUpdate&&a("button",{type:"button",className:"underline hover:text-foreground",onClick:()=>e.onEdit?.(e.id),children:"revisar o painel"})]})]})}function gg({panelType:e,className:r}){const n=e===ff.Burndown;return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-2 p-4",r),children:[a(Yo,{className:"h-10 w-10 text-muted-foreground/40"}),n&&a("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function vg({hasRemovedColumn:r=!1,className:n}){return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[a("h2",{className:"text-lg font-normal text-foreground/80 lg:text-base",children:e.t("no_data_to_display")}),a("p",{className:"text-sm text-muted-foreground lg:text-xs",children:e.t("dashboard_no_data")})]})}function bg({onRemove:e,className:r}){return t("div",{className:Fi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[a(de,{className:"h-12 w-12 text-muted-foreground/50"}),a("h2",{className:"mt-1 text-lg font-normal text-foreground/80",children:"A consulta não pôde ser realizada."}),a("p",{className:"text-sm text-muted-foreground",children:"Este recurso não está disponível."}),e&&a("p",{className:"mt-2 text-xs",children:a("button",{type:"button",className:"underline hover:text-foreground",onClick:e,children:"Remover painel"})})]})}const xg={[Xh.Count]:e.t("dashboard_distinct_count").replace("distinta","").trim()||"Count",[Xh.Sum]:"Sum",[Xh.Average]:e.t("dashboard_average"),[Xh.DistinctCount]:e.t("dashboard_distinct_count"),[Xh.Max]:e.t("dashboard_max_value"),[Xh.Min]:e.t("dashboard_min_value")};function yg({config:e,state:r,value:n,label:i,viewOnly:o=!1,onClick:s,onRefresh:l,queryUrl:d,queryUrlBuilder:c,className:u}){const{t:m}=Ga(),p=i??xg[e.aggregationType??""]??"",h=function(e,a){if(null==e)return"—";const t=Xf.includes(a.field),r=a.aggregationType===Xh.Count||a.aggregationType===Xh.DistinctCount;return t&&!r?dg.format("string"==typeof e?parseFloat(e):e):"number"==typeof e?r?String(e):e.toLocaleString("pt-BR",{maximumFractionDigits:2}):String(e)}(n,e);return t("div",{className:Fi("flex h-full flex-col",u),children:[a(hg,{config:e,viewOnly:o,onRefresh:l,queryUrlBuilder:c}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&t("div",{className:Fi("flex flex-1 flex-col items-center justify-center",s&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:s,children:[a("span",{className:"text-[clamp(1.5rem,7vh,5rem)] font-bold text-foreground leading-tight",children:h}),p&&a("span",{className:"text-xs text-muted-foreground mt-1",children:p})]}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:d}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Ng({config:e,state:r,htmlContent:n,viewOnly:i=!1,onRefresh:o,queryUrl:s,queryUrlBuilder:l,className:d}){const c=n??e.textTypeString??"";return t("div",{className:Fi("flex h-full flex-col",d),children:[a(hg,{config:e,viewOnly:i,onRefresh:o,queryUrlBuilder:l}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:c}}),r===Rf.Error&&a(fg,{config:e,queryUrl:s})]})}function wg({config:e,state:r,data:n=[],columns:i=[],viewOnly:o=!1,onRowClick:d,onRefresh:c,onExport:u,queryUrl:m,queryUrlBuilder:p,enableRowLinks:h=!0,className:f}){const g=s(()=>i.filter(e=>!1!==e.visible),[i]),v=l(e=>{if(d)d(e);else if(h){const a=rg(e);a&&window.open(tg(a),"_blank")}},[d,h]);return t("div",{className:Fi("flex h-full flex-col",f),children:[a(hg,{config:e,viewOnly:o,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 overflow-auto",children:t("table",{className:"w-full text-sm",children:[a("thead",{className:"sticky top-0 z-10 bg-muted/60 backdrop-blur-sm",children:a("tr",{children:g.map(e=>a("th",{className:"px-2 py-1.5 text-left text-xs font-medium text-muted-foreground whitespace-nowrap border-b",children:e.header||e.columnLabel||e.columnName},e.columnName))})}),a("tbody",{children:n.map((e,t)=>{const r=h&&!!rg(e);return a("tr",{className:Fi("border-b border-border/50 transition-colors hover:bg-muted/30",(r||d)&&"cursor-pointer"),onClick:()=>v(e),children:g.map(t=>a("td",{className:"px-2 py-1.5 text-foreground whitespace-nowrap truncate max-w-[200px]",children:t.render?t.render(e[t.columnName],e):_g(e[t.columnName],t)},t.columnName))},t)})})]})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function _g(e,a){return null==e?"":e instanceof Date?"datetime"===a.columnType?e.toLocaleString("pt-BR"):e.toLocaleDateString("pt-BR"):"number"==typeof e?e.toLocaleString("pt-BR"):String(e)}const Cg=["hsl(var(--primary))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))","#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3"];function kg({config:e,variant:r,state:n,data:i=[],series:o,colors:l,categoryKey:d="key",yAxisFormat:c,viewOnly:u=!1,onPointClick:m,onRefresh:p,onExport:h,queryUrl:f,queryUrlBuilder:g,className:v}){const b=l?.length?l:e.hexColors?.length?e.hexColors:Cg,x=s(()=>o?.length?o:[{dataKey:"value",name:e.title}],[o,e.title]),y="bar"===r,N="stacked-column"===r,w=s(()=>{if(c)return e=>c.replace("{value}",e.toLocaleString("pt-BR"))},[c]);return t("div",{className:Fi("flex h-full flex-col",v),children:[a(hg,{config:e,viewOnly:u,onRefresh:p,onExport:h,queryUrlBuilder:g}),n===Rf.Loading&&a(gg,{}),n===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:Sg({variant:r,data:i,series:x,colors:b,categoryKey:d,isHorizontalBar:y,isStacked:N,yAxisTickFormatter:w,tooltipFormatter:e=>"number"==typeof e?e.toLocaleString("pt-BR"):String(e??""),onPointClick:m})})}),n===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),n===Rf.Error&&a(fg,{config:e,queryUrl:f}),n===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Sg({variant:e,data:r,series:n,colors:i,categoryKey:o,isHorizontalBar:s,isStacked:l,yAxisTickFormatter:d,tooltipFormatter:c,onPointClick:u}){const m={tick:{fontSize:11},tickLine:!1,axisLine:!1},p=a(Et,{dataKey:s?void 0:o,type:s?"number":"category",...m,angle:s?0:-45,textAnchor:s?"middle":"end",height:s?void 0:60,tickFormatter:s?d:void 0}),h=a(Dt,{dataKey:s?o:void 0,type:s?"category":"number",...m,width:s?100:60,tickFormatter:s?void 0:d}),f=a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),g=a(It,{formatter:c,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),v=n.length>1?a(Tt,{wrapperStyle:{fontSize:"11px"}}):null,b=u?(e,a)=>u(r[a],a):void 0;return"bar"===e||"column"===e||"stacked-column"===e?t(Rt,{data:r,layout:s?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(Mt,{dataKey:e.dataKey,name:e.name||e.dataKey,fill:e.color||i[t%i.length],stackId:l?e.stackId||"stack":void 0,radius:l?void 0:[2,2,0,0],onClick:b,cursor:u?"pointer":void 0},e.dataKey))]}):"area"===e?t(Lt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>{const r=e.color||i[t%i.length];return a(zt,{type:"monotone",dataKey:e.dataKey,name:e.name||e.dataKey,stroke:r,fill:r,fillOpacity:.15,strokeWidth:2,dot:!1,activeDot:{r:4,cursor:u?"pointer":void 0}},e.dataKey)})]}):t(Ft,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(Ut,{type:"monotone",dataKey:e.dataKey,name:e.name||e.dataKey,stroke:e.color||i[t%i.length],strokeWidth:2,dot:{r:3},activeDot:{r:5,cursor:u?"pointer":void 0}},e.dataKey))]})}const Ag=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function Eg({config:e,state:r,data:n=[],colors:i,viewOnly:o=!1,onSliceClick:l,onRefresh:d,onExport:c,queryUrl:u,queryUrlBuilder:m,className:p}){const h=i?.length?i:e.hexColors?.length?e.hexColors:Ag,f=s(()=>n.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[n]),g=s(()=>f.reduce((e,a)=>e+(a.value??0),0),[f]);return t("div",{className:Fi("flex h-full flex-col",p),children:[a(hg,{config:e,viewOnly:o,onRefresh:d,onExport:c,queryUrlBuilder:m}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t(jt,{children:[a(Ot,{data:f,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:"80%",label:({name:e,percent:a})=>`${e??""}: ${(100*(a??0)).toFixed(0)}%`,labelLine:!0,onClick:l?(e,a)=>l(n[a],a):void 0,cursor:l?"pointer":void 0,children:f.map((e,t)=>a(Bt,{fill:h[t%h.length]},t))}),a(It,{formatter:e=>{const a="number"==typeof e?e:0,t=g>0?(a/g*100).toFixed(1):"0";return`${a.toLocaleString("pt-BR")} (${t}%)`}}),a(Tt,{wrapperStyle:{fontSize:"11px"}})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:u}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Dg({config:e,state:r,data:n=[],barColor:i,lineColor:o="#e31a1c",viewOnly:l=!1,onPointClick:d,onRefresh:c,onExport:u,queryUrl:m,queryUrlBuilder:p,className:h}){const f=e.hexColors?.length?e.hexColors:["#1f78b4"],g=i??f[0],v=s(()=>{const e=[...n].sort((e,a)=>(a.value??0)-(e.value??0)),a=e.reduce((e,a)=>e+(a.value??0),0);let t=0;return e.map(e=>(t+=e.value??0,{key:String(e.key??""),value:e.value??0,cumulativePercent:a>0?Math.round(t/a*100):0}))},[n]);return t("div",{className:Fi("flex h-full flex-col",h),children:[a(hg,{config:e,viewOnly:l,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t($t,{data:v,margin:{top:5,right:30,left:0,bottom:5},children:[a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Et,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),a(Dt,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),a(Dt,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),a(It,{formatter:(e,a)=>"% Acumulado"===a?`${e}%`:"number"==typeof e?e.toLocaleString("pt-BR"):e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(Tt,{wrapperStyle:{fontSize:"11px"}}),a(Mt,{yAxisId:"left",dataKey:"value",name:"Quantidade",fill:g,radius:[2,2,0,0],onClick:d?(e,a)=>d(n[a],a):void 0,cursor:d?"pointer":void 0}),a(Ut,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:o,strokeWidth:2,dot:{r:3,fill:o}})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Pg({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:o,executedColor:s="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:d=!1,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){const{t:h}=Ga(),f=i??h("dashboard_work_done"),g=o??h("dashboard_work_planned");return t("div",{className:Fi("flex h-full flex-col",p),children:[a(hg,{config:e,viewOnly:d,onRefresh:c,queryUrlBuilder:m}),r===Rf.Loading&&a(gg,{panelType:ff.Burndown}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t(Lt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Et,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),a(Dt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),a(It,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(Tt,{wrapperStyle:{fontSize:"11px"}}),a(zt,{type:"monotone",dataKey:"executedPercentage",name:f,stroke:s,fill:s,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),a(zt,{type:"monotone",dataKey:"plannedPercentage",name:g,stroke:l,fill:l,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:u}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Ig({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:o,executedColor:s="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:d=!1,onPointClick:c,onRefresh:u,queryUrl:m,queryUrlBuilder:p,className:h}){const{t:f}=Ga(),g=i??f("dashboard_work_done"),v=o??f("dashboard_work_planned");return t("div",{className:Fi("flex h-full flex-col",h),children:[a(hg,{config:e,viewOnly:d,onRefresh:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(At,{width:"100%",height:"100%",children:t(Rt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(Pt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Et,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),a(Dt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),a(It,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(Tt,{wrapperStyle:{fontSize:"11px"}}),a(Mt,{dataKey:"executedWork",name:g,fill:s,radius:[2,2,0,0],onClick:c?(e,a)=>c(n[a],a):void 0,cursor:c?"pointer":void 0}),a(Mt,{dataKey:"plannedWork",name:v,fill:l,radius:[2,2,0,0]})]})})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}function Tg({config:e,state:r,rule:n,risks:i=[],matrixViewType:o=Af.Quantity,viewOnly:l=!1,onCellClick:d,onRiskClick:c,onRefresh:u,queryUrl:m,queryUrlBuilder:p,className:h}){const f=s(()=>[...n?.parametersY??[]].sort((e,a)=>a.position-e.position),[n?.parametersY]),g=n?.parametersX??[],v=s(()=>{const e={};return i.forEach(a=>{const t=`${a.parameterYPosition}-${a.parameterXPosition}`;e[t]||(e[t]=[]),e[t].push(a)}),e},[i]);return t("div",{className:Fi("flex h-full flex-col",h),children:[a(hg,{config:e,viewOnly:l,onRefresh:u,queryUrlBuilder:p}),r===Rf.Loading&&a(gg,{}),r===Rf.Loaded&&n&&a("div",{className:"flex-1 overflow-auto p-4",children:t("div",{className:"flex gap-4 items-stretch min-w-fit",children:[a("div",{className:"flex items-center justify-center",children:a("span",{className:"text-xs font-medium text-muted-foreground [writing-mode:vertical-lr] rotate-180",children:n.name_y})}),t("div",{className:"flex-1",children:[t("div",{className:"flex mb-1",children:[a("div",{className:"w-16 shrink-0"}),a("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.threat_strategy_type_name}),!n.disable_opportunities&&a("div",{className:"flex-1 text-center text-xs font-medium text-muted-foreground truncate",children:n.opportunity_strategy_type_name})]}),f.map((e,r)=>t("div",{className:"flex",children:[a("div",{className:"w-16 shrink-0 flex items-center justify-center border border-border/50 text-xs font-medium p-1 text-center",children:e.name}),g.map((i,s)=>{const l=((e,a)=>v[`${a.position}-${e.position}`]??[])(i,e),u=((e,a)=>n?.colorMatrix?.[a]?.[e]??"hsl(var(--muted))")(s,r);return t("div",{className:Fi("flex-1 min-w-[60px] min-h-[40px] border border-border/50 flex flex-col items-center justify-center gap-0.5 p-1",(d||c)&&l.length>0&&"cursor-pointer hover:opacity-80"),style:{backgroundColor:u},onClick:()=>l.length>0&&d?.(i,e,l),children:[o===Af.Quantity&&l.length>0&&t("span",{className:"text-xs font-semibold",children:[l.length," risco",1!==l.length?"s":""]}),o===Af.AllRisksList&&l.map(e=>t(hs,{children:[a(fs,{asChild:!0,children:a("button",{type:"button",className:"text-[10px] text-primary underline hover:text-primary/80",onClick:a=>{a.stopPropagation(),c?.(e)},children:e.code})}),t(gs,{className:"max-w-[250px]",children:[t("p",{className:"font-medium",children:[e.code," - ",e.name]}),e.analysisDate&&t("p",{className:"text-xs mt-1",children:["Última análise: ",a("strong",{children:e.analysisDate})]}),e.strategy&&t("p",{className:"text-xs",children:["Estratégia: ",a("strong",{children:e.strategy})]}),e.resultName&&t("p",{className:"text-xs",children:["Criticidade: ",a("strong",{style:{backgroundColor:u},className:"px-1 rounded",children:e.resultName})]})]})]},e.code))]},i.position)})]},e.position)),t("div",{className:"flex",children:[a("div",{className:"w-16 shrink-0"}),g.map(e=>a("div",{className:"flex-1 min-w-[60px] border border-border/50 text-xs font-medium p-1 text-center",children:e.name},e.position))]}),a("div",{className:"text-center text-xs font-medium text-muted-foreground mt-2",children:n.name_x})]})]})}),r===Rf.NoData&&a(vg,{hasRemovedColumn:e.hasRemovedColumn}),r===Rf.Error&&a(fg,{config:e,queryUrl:m}),r===Rf.Unavailable&&a(bg,{onRemove:()=>e.onRemove?.(e.id)})]})}const Rg=Object.freeze({Translate:{toString(e){if(!e)return;const{x:a,y:t}=e;return"translate3d("+(a?Math.round(a):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:a,scaleY:t}=e;return"scaleX("+a+") scaleY("+t+")"}},Transform:{toString(e){if(e)return[Rg.Translate.toString(e),Rg.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:a,duration:t,easing:r}=e;return a+" "+t+"ms "+r}}});function Mg(e){switch(e){case ff.Bar:case ff.Column:case ff.Pie:case ff.List:case ff.Line:case ff.Area:case ff.Text:case ff.StackedColumn:return{x:4,y:2};case ff.Pareto:case ff.RiskMatrix:case ff.Burndown:case ff.PerformanceColumns:return{x:8,y:2};case ff.Numeric:return{x:1,y:1};default:return{x:2,y:2}}}function Lg(e){switch(Number(e)){case ff.Area:case ff.Bar:case ff.Column:case ff.Line:case ff.Numeric:case ff.Pie:case ff.Text:return{x:1,y:1};default:return{x:2,y:2}}}function zg({panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:o,children:l}){const{attributes:d,listeners:c,setNodeRef:u,transform:m,transition:p,isDragging:h}=nr({id:e.id,disabled:!o}),f=s(()=>({gridColumn:`${e.col+1} / span ${e.sizeX}`,gridRow:`${e.row+1} / span ${e.sizeY}`,minHeight:e.sizeY*n+(e.sizeY-1)*i+"px",transform:Rg.Transform.toString(m),transition:p,zIndex:h?50:void 0,opacity:h?.85:1}),[e,r,n,i,m,p,h]);return t("div",{ref:u,style:f,className:Fi("rounded-lg border border-border bg-card shadow-sm overflow-hidden","transition-shadow duration-200",h&&"shadow-lg ring-2 ring-primary/20"),...d,children:[a("div",{className:Fi("dashboard-panel-drag-handle",o&&"cursor-grab active:cursor-grabbing"),...o?c:{}}),a("div",{className:"h-full",children:l})]})}function Fg({panels:e,columns:r=8,cellHeight:n=160,cellGap:i=10,allowDragging:d=!1,showGridLines:c=!1,renderPanel:u,onLayoutChange:m,className:p}){const[h,f]=o(e);s(()=>{f(e)},[e]);const g=Xt(Jt(Zt,{activationConstraint:{distance:8}})),v=s(()=>0===h.length?1:Math.max(...h.map(e=>e.row+e.sizeY)),[h]),b=s(()=>h.map(e=>e.id),[h]),x=l(e=>{const{active:a,over:t}=e;if(!t||a.id===t.id)return;const r=h.findIndex(e=>e.id===a.id),n=h.findIndex(e=>e.id===t.id);if(-1===r||-1===n)return;const i=[...h],o={...i[r]},s={...i[n]},l=o.col,d=o.row;o.col=s.col,o.row=s.row,s.col=l,s.row=d,i[r]=o,i[n]=s,f(i),m?.(i)},[h,m]),y=s(()=>({display:"grid",gridTemplateColumns:`repeat(${r}, 1fr)`,gridTemplateRows:`repeat(${v}, ${n}px)`,gap:`${i}px`}),[r,v,n,i]);return 0===h.length?t("div",{className:Fi("flex flex-col items-center justify-center py-16 text-center",p),children:[a("h2",{className:"text-lg font-semibold text-foreground mb-2",children:"Nenhum painel adicionado"}),a("p",{className:"text-sm text-muted-foreground",children:"Adicione painéis para visualizar seus dados aqui."})]}):a(er,{sensors:g,collisionDetection:ar,onDragEnd:x,children:a(tr,{items:b,strategy:rr,children:a("div",{style:y,className:Fi("relative w-full",c&&"bg-muted/30",p),children:h.map(e=>a(zg,{panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:d,children:u(e.id)},e.id))})})})}const Ug={[ff.Bar]:"bar",[ff.Column]:"column",[ff.StackedColumn]:"stacked-column",[ff.Area]:"area",[ff.Line]:"line",[ff.EvolutionLine]:"evolution-line"};function jg({config:e,state:r,data:n,numericValue:i,listColumns:o,cartesianData:s,cartesianSeries:l,burndownData:d,performanceData:c,matrixRule:u,matrixRisks:m,onPanelClick:p}){const h=Ug[e.typeId];if(h)return a(kg,{config:e,variant:h,state:r,data:s,series:l});switch(e.typeId){case ff.Numeric:return a(yg,{config:e,state:r,value:i});case ff.Text:return a(Ng,{config:e,state:r});case ff.List:return a(wg,{config:e,state:r,data:n,columns:o??[]});case ff.Pie:return a(Eg,{config:e,state:r,data:n});case ff.Pareto:return a(Dg,{config:e,state:r,data:n});case ff.Burndown:return a(Pg,{config:e,state:r,data:d});case ff.PerformanceColumns:return a(Ig,{config:e,state:r,data:c});case ff.RiskMatrix:return a(Tg,{config:e,state:r,rule:u,risks:m??[]});default:return t("div",{className:"flex items-center justify-center h-full text-muted-foreground text-sm",children:["Tipo de painel não suportado (",e.typeId,")"]})}}function Og({dashboard:e,panels:r,pages:n,activePageId:i,canEdit:d=!1,isFullscreen:c=!1,isLoading:u=!1,getPanelData:m,onRefresh:p,onToggleFullscreen:h,onToggleFavorite:f,onEdit:g,onShare:v,onAddPanel:b,onEditPanel:x,onRemovePanel:y,onDuplicatePanel:N,onLayoutChange:w,onPageChange:_,toolbarActions:C,className:k}){const{t:S}=Ga(),[A,E]=o(!1),D=e.idViewType===xf.Carousel,P=s(()=>r,[r,D,i]),I=s(()=>P.map(e=>{const a=Lg(e.typeId);return{id:e.id,col:e.col,row:e.row,sizeX:e.sizeX,sizeY:e.sizeY,minSizeX:a.x,minSizeY:a.y}}),[P]),T=l(e=>({id:e.id,title:e.titlePtBr||e.titleEnUs||e.titleEsEs,typeId:e.typeId,queryId:e.queryId,queryContextId:e.queryContextId,queryTitle:e.queryTitle,querySelectedColumns:e.querySelectedColumns,field:e.field??"",fieldType:e.fieldType??"",fieldAuxAxis:e.fieldAuxAxis,fieldAuxAxisType:e.fieldAuxAxisType,aggregationType:e.aggregationType,textTypeString:e.textTypeString,referenceDate:e.referenceDate,period:e.period,initialDate:e.initialDate,finalDate:e.finalDate,dimension:e.dimension,yAxis:e.yAxis,yAxisType:e.yAxisType,orderBy:e.orderBy,orderByType:e.orderByType,secondaryGrouping:e.secondaryGrouping,secondaryGroupingType:e.secondaryGroupingType,onlyLate:e.onlyLate,jsonRules:e.jsonRules,ignoreRules:e.ignoreRules,visualizationType:e.visualizationType,sortType:e.sortType,itemsPerPanel:e.itemsPerPanel,secondaryItemsPerPanel:e.secondaryItemsPerPanel,matrixViewRule:e.matrixViewRule,listPanelColumns:e.listPanelColumns,listPanelListType:e.listPanelListType,paletteId:e.paletteId,hexColors:e.hexColors,showNotInformedData:e.showNotInformedData,fieldAnalysisRule:e.fieldAnalysisRule,fieldCriticality:e.fieldCriticality,fieldPlansType:e.fieldPlansType,fieldPlansSelected:e.fieldPlansSelected,fieldPlansBurndown:e.fieldPlansBurndown,fieldPlansBurndownGroup:e.fieldPlansBurndownGroup,analysisCriteriaId:e.analysisCriteriaId,analysisCriteriaParameter:e.analysisCriteriaParameter,evolutionSecondaryGrouping:e.evolutionSecondaryGrouping,canUpdate:d,hasRemovedColumn:e.hasRemovedColumn,panelSize:{x:e.sizeX,y:e.sizeY},onEdit:x,onRemove:y,onDuplicate:N}),[d,x,y,N]),R=l(()=>{A||u||(E(!0),p?.(),setTimeout(()=>E(!1),3e4))},[A,u,p]),M=l(e=>{const r=P.find(a=>a.id===e);if(!r)return null;const n=T(r),i=m?.(e)??{state:Rf.Loaded};return t("div",{className:"flex flex-col h-full",children:[a(hg,{config:n,onRefresh:()=>{}}),a("div",{className:"flex-1 min-h-0 p-2",children:a(jg,{config:n,...i})})]})},[P,T,m,d,x,y,N]);return t("div",{className:Fi("flex flex-col h-full",c&&"fixed inset-0 z-50 bg-background",k),children:[t("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border bg-card",children:[t("div",{className:"flex items-center gap-3 min-w-0",children:[a("h1",{className:"text-lg font-semibold text-foreground truncate",children:e.title}),e.responsibleName&&!c&&a("span",{className:"text-xs text-muted-foreground truncate hidden sm:inline",children:e.responsibleName})]}),t("div",{className:"flex items-center gap-1",children:[C,p&&a("button",{onClick:R,disabled:A||u,className:Fi("inline-flex items-center justify-center rounded-md p-2 text-sm","hover:bg-accent hover:text-accent-foreground transition-colors","disabled:opacity-50 disabled:pointer-events-none"),title:A?S("dashboard_wait_refresh"):"Atualizar",children:a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M21 12a9 9 0 0 1-9 9m9-9a9 9 0 0 0-9-9m9 9H3m0 0a9 9 0 0 1 9-9m-9 9a9 9 0 0 0 9 9"})})}),h&&a("button",{onClick:h,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:c?S("dashboard_exit_fullscreen"):"Fullscreen",children:a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",c?{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"}:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})}),d&&!c&&v&&a("button",{onClick:v,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:"Compartilhar",children:t("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),a("circle",{cx:"9",cy:"7",r:"4"}),a("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),a("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),f&&!c&&a("button",{onClick:f,className:"inline-flex items-center justify-center rounded-md p-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors",title:e.isFavorite?S("dashboard_remove_favorite"):"Favoritar",children:a("svg",{className:Fi("h-4 w-4",e.isFavorite&&"fill-yellow-400 text-yellow-400"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})]})]}),D&&n&&n.length>1&&a("div",{className:"flex items-center gap-1 px-4 py-1 border-b border-border bg-card overflow-x-auto",children:n.map(e=>a("button",{onClick:()=>_?.(e.id),className:Fi("px-3 py-1.5 text-sm rounded-md whitespace-nowrap transition-colors",i===e.id?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground"),children:e.name||`Dashboard ${e.position}`},e.id))}),d&&!c&&b&&a("div",{className:"flex justify-center py-3",children:t("button",{onClick:b,className:Fi("inline-flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M12 5v14M5 12h14"})}),"Adicionar painel"]})}),u&&a("div",{className:"flex-1 flex items-center justify-center",children:a("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!u&&a("div",{className:"flex-1 overflow-auto p-4 bg-muted/30",children:a(Fg,{panels:I,allowDragging:d,showGridLines:d,renderPanel:M,onLayoutChange:w})})]})}function Bg(e,a=kf.PtBr){const{t:t}=Ga();switch(a){case kf.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case kf.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function $g(e){const{t:a}=Ga();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const Vg=[{value:Vf.All,label:"Todos"},{value:Vf.OnlyMine,label:e.t("dashboard_my")},{value:Vf.Favorites,label:"Favoritos"}];function qg({dashboards:e,limit:n,isLoading:i=!1,language:d=kf.PtBr,canAdd:c=!1,canEdit:u=!1,canRemove:m=!1,onOpen:p,onEdit:h,onShare:f,onDuplicate:g,onRemove:v,onAdd:b,onToggleFavorite:x,onRefresh:y,onSearch:N,onQuickFilterChange:w,toolbarExtra:_,className:C}){const{t:k}=Ga(),[S,A]=o(""),[E,D]=o(Vf.All),[P,I]=o(null),T=l(e=>{A(e),N?.(e)},[N]),R=l(e=>{D(e),w?.(e)},[w]),M=s(()=>{let a=e;if(S){const e=S.toLowerCase();a=a.filter(a=>a.code?.toLowerCase().includes(e)||Bg(a,d).toLowerCase().includes(e)||a.responsibleName?.toLowerCase().includes(e))}switch(E){case Vf.OnlyMine:break;case Vf.Favorites:a=a.filter(e=>e.isFavorite)}return a},[e,S,E,d]);return t("div",{className:Fi("flex flex-col h-full",C),children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[t("div",{className:"flex items-center gap-3",children:[a("h1",{className:"text-lg font-semibold text-foreground",children:"Dashboards"}),n&&t("span",{className:"text-xs text-muted-foreground",children:["(",n.countDashboards,"/",n.maxDashboards,")"]})]}),t("div",{className:"flex items-center gap-2",children:[t("div",{className:"relative",children:[t("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("circle",{cx:"11",cy:"11",r:"8"}),a("path",{d:"m21 21-4.3-4.3"})]}),a("input",{type:"text",placeholder:"Buscar...",value:S,onChange:e=>T(e.target.value),className:Fi("h-9 w-48 rounded-md border border-input bg-background pl-9 pr-3 text-sm","placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")})]}),_,c&&b&&t("button",{onClick:b,className:Fi("inline-flex items-center gap-1.5 px-3 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"M12 5v14M5 12h14"})}),"Novo"]})]})]}),a("div",{className:"flex items-center gap-1 px-4 py-2 border-b border-border bg-card",children:Vg.map(e=>a("button",{onClick:()=>R(e.value),disabled:i,className:Fi("px-3 py-1.5 text-sm rounded-md transition-colors",E===e.value?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-accent hover:text-accent-foreground","disabled:opacity-50"),children:e.label},e.value))}),i&&a("div",{className:"flex-1 flex items-center justify-center",children:a("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),!i&&a("div",{className:"flex-1 overflow-auto",children:t("table",{className:"w-full text-sm",children:[a("thead",{className:"sticky top-0 bg-muted/80 backdrop-blur-sm border-b border-border",children:t("tr",{children:[a("th",{className:"w-12 px-3 py-2 text-left font-medium text-muted-foreground",children:a("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Código"}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Título"}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Responsável"}),a("th",{className:"w-12 px-3 py-2 text-center font-medium text-muted-foreground",children:t("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),a("circle",{cx:"9",cy:"7",r:"4"}),a("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),a("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Última modificação"}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Situação"}),a("th",{className:"w-12 px-3 py-2"})]})}),t("tbody",{children:[0===M.length&&a("tr",{children:a("td",{colSpan:8,className:"px-3 py-12 text-center text-muted-foreground",children:"Nenhum dashboard encontrado."})}),M.map(e=>t("tr",{onClick:()=>p?.(e),className:Fi("border-b border-border cursor-pointer transition-colors","hover:bg-accent/50"),children:[a("td",{className:"px-3 py-2",children:a("button",{onClick:a=>{a.stopPropagation(),x?.(e)},className:"p-1 hover:bg-accent rounded transition-colors",children:a("svg",{className:Fi("h-4 w-4",e.isFavorite?"fill-yellow-400 text-yellow-400":"text-muted-foreground"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})})}),a("td",{className:"px-3 py-2 font-mono text-xs text-foreground",children:e.code}),a("td",{className:"px-3 py-2 text-foreground font-medium",children:Bg(e,d)}),a("td",{className:"px-3 py-2 text-muted-foreground",children:e.responsibleName}),a("td",{className:"px-3 py-2 text-center",children:e.hasSharedIcon&&t("svg",{className:"h-4 w-4 mx-auto text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),a("circle",{cx:"9",cy:"7",r:"4"}),a("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),a("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),a("td",{className:"px-3 py-2 text-muted-foreground text-xs",children:$g(e.lastModified)}),a("td",{className:"px-3 py-2",children:a("span",{className:Fi("inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium",e.isActive?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400"),children:e.isActive?"Ativo":"Inativo"})}),a("td",{className:"px-3 py-2",children:t("div",{className:"relative",children:[a("button",{onClick:a=>{a.stopPropagation(),I(P===e.id?null:e.id)},className:"p-1 hover:bg-accent rounded transition-colors",children:t("svg",{className:"h-4 w-4 text-muted-foreground",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("circle",{cx:"12",cy:"5",r:"1"}),a("circle",{cx:"12",cy:"12",r:"1"}),a("circle",{cx:"12",cy:"19",r:"1"})]})}),P===e.id&&t(r,{children:[a("div",{className:"fixed inset-0 z-40",onClick:()=>I(null)}),t("div",{className:"absolute right-0 top-8 z-50 min-w-[160px] rounded-md border border-border bg-popover shadow-md py-1",children:[a("button",{onClick:a=>{a.stopPropagation(),I(null),p?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Abrir"}),u&&a("button",{onClick:a=>{a.stopPropagation(),I(null),h?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Editar"}),u&&a("button",{onClick:a=>{a.stopPropagation(),I(null),f?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Compartilhar"}),a("button",{onClick:a=>{a.stopPropagation(),I(null),g?.(e)},className:"w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors",children:"Duplicar"}),m&&t(r,{children:[a("div",{className:"my-1 border-t border-border"}),a("button",{onClick:a=>{a.stopPropagation(),I(null),v?.(e)},className:"w-full px-3 py-1.5 text-left text-sm text-destructive hover:bg-destructive/10 transition-colors",children:"Remover"})]})]})]})]})})]},e.id))]})]})})]})}const Wg=[{value:vf.NotUpdate,label:e.t("dashboard_no_refresh")},{value:vf.FiveMinutes,label:"5 minutos"},{value:vf.TenMinutes,label:"10 minutos"},{value:vf.FifteenMinutes,label:"15 minutos"},{value:vf.ThirtyMinutes,label:"30 minutos"},{value:vf.OneHour,label:"1 hora"}],Hg=[{value:xf.NormalPage,label:e.t("dashboard_normal_page")},{value:xf.Carousel,label:"Carrossel"}],Gg=[{value:nf.FiveSeconds,label:"5 segundos"},{value:nf.TenSeconds,label:"10 segundos"},{value:nf.FifteenSeconds,label:"15 segundos"},{value:nf.ThirtySeconds,label:"30 segundos"},{value:nf.OneMinute,label:"1 minuto"},{value:nf.ThreeMinutes,label:"3 minutos"},{value:nf.FiveMinutes,label:"5 minutos"},{value:nf.TenMinutes,label:"10 minutos"}],Kg=[{value:_f.NotShared,label:e.t("dashboard_not_shared"),description:e.t("dashboard_only_responsible")},{value:_f.SharedWithAllCollaborators,label:e.t("dashboard_shared_unit"),description:e.t("dashboard_all_access")},{value:_f.SharedWithUsersGroupsPlacesCollaborators,label:e.t("dashboard_select_groups"),description:e.t("dashboard_select_groups")}],Yg=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function Qg({dashboard:e,initialTab:r=Nf.General,isSaving:n=!1,isQualitfy:i=!1,users:d=[],groups:c=[],places:u=[],collaborators:m=[],onSave:p,onCancel:h,className:f}){const{t:g}=Ga(),v=!!e,[b,x]=o(r),[y,N]=o({"pt-br":!!e?.titlePtBr||!v,en:!!e?.titleEnUs,es:!!e?.titleEsEs}),[w,_]=o(e?.titlePtBr??""),[C,k]=o(e?.titleEnUs??""),[S,A]=o(e?.titleEsEs??""),[E,D]=o(e?.responsibleId??""),[P,I]=o(e?.isActive??!0),[T,R]=o(e?.idUpdateTime??vf.NotUpdate),[M,L]=o(e?.idViewType??xf.NormalPage),[z,F]=o(e?.idPageTime??nf.FifteenSeconds),[U,j]=o(e?.idShare??_f.NotShared),[O,B]=o(e?.groups??[]),[$,V]=o(e?.places??[]),[q,W]=o(e?.collaborators??[]),H=M===xf.Carousel,G=y["pt-br"]||y.en||y.es,K=s(()=>!!G&&(!(y["pt-br"]&&!w.trim())&&(!(y.en&&!C.trim())&&!(y.es&&!S.trim()))),[G,y,w,C,S]),Y=l(e=>{N(a=>({...a,[e]:!a[e]}))},[]),Q=l(()=>{K&&!n&&p?.({titlePtBr:y["pt-br"]?w:"",titleEnUs:y.en?C:"",titleEsEs:y.es?S:"",responsibleId:E||void 0,isActive:P,idUpdateTime:T,idViewType:M,idPageTime:H?z:null,idShare:U,groups:U===_f.SharedWithUsersGroupsPlacesCollaborators?O:[],places:U===_f.SharedWithUsersGroupsPlacesCollaborators?$:[],collaborators:U===_f.SharedWithUsersGroupsPlacesCollaborators?q:[]})},[K,n,p,y,w,C,S,E,P,T,M,z,H,U,O,$,q]);return t("div",{className:Fi("flex flex-col h-full bg-background",f),children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-card",children:[t("div",{className:"flex items-center gap-3",children:[a("h2",{className:"text-lg font-semibold text-foreground",children:g(v?"dashboard_edit":"dashboard_new")}),v&&e&&a("span",{className:"text-sm text-muted-foreground",children:e.code})]}),t("div",{className:"flex items-center gap-2",children:[a("button",{onClick:h,className:"px-3 py-2 text-sm rounded-md border border-input hover:bg-accent transition-colors",children:"Cancelar"}),t("button",{onClick:Q,disabled:!K||n,className:Fi("inline-flex items-center gap-1.5 px-4 py-2 rounded-md text-sm font-medium","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","disabled:opacity-50 disabled:pointer-events-none"),children:[n?a("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent"}):a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("polyline",{points:"20 6 9 17 4 12"})}),"Salvar"]})]})]}),t("div",{className:"flex border-b border-border bg-card",children:[a("button",{onClick:()=>x(Nf.General),className:Fi("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===Nf.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),a("button",{onClick:()=>x(Nf.Share),className:Fi("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===Nf.Share?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Compartilhamento"})]}),t("div",{className:"flex-1 overflow-auto p-6",children:[b===Nf.General&&t("div",{className:"max-w-2xl space-y-6",children:[t("div",{className:"space-y-2",children:[a("label",{className:"text-sm font-medium text-foreground",children:"Título *"}),a("div",{className:"flex gap-2",children:Yg.map(e=>a("button",{onClick:()=>Y(e.key),className:Fi("px-3 py-1 text-xs rounded-md border transition-colors",y[e.key]?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:bg-accent"),children:e.label},e.key))}),!G&&a("p",{className:"text-xs text-destructive",children:"Selecione pelo menos um idioma"})]}),y["pt-br"]&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Título em Português (BR)"}),a("input",{value:w,onChange:e=>_(e.target.value),maxLength:200,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),t("p",{className:"text-xs text-muted-foreground text-right",children:[w.length,"/200"]})]}),y.en&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Título em Inglês (US)"}),a("input",{value:C,onChange:e=>k(e.target.value),maxLength:200,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),t("p",{className:"text-xs text-muted-foreground text-right",children:[C.length,"/200"]})]}),y.es&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Título em Espanhol (ES)"}),a("input",{value:S,onChange:e=>A(e.target.value),maxLength:200,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring")}),t("p",{className:"text-xs text-muted-foreground text-right",children:[S.length,"/200"]})]}),!e?.isStandard&&d.length>0&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Responsável"}),t("select",{value:E,onChange:e=>D(e.target.value),disabled:!v,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:[a("option",{value:"",children:"Selecione..."}),d.map(e=>a("option",{value:e.id,children:e.name},e.id))]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Intervalo de atualização"}),a("select",{value:T,onChange:e=>R(Number(e.target.value)),disabled:i,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Wg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]}),t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Situação"}),t("div",{className:"flex items-center gap-3 h-10",children:[a("button",{onClick:()=>I(!P),disabled:e?.isGeneralViewUse,className:Fi("relative inline-flex h-6 w-11 items-center rounded-full transition-colors",P?"bg-primary":"bg-muted","disabled:opacity-50"),children:a("span",{className:Fi("inline-block h-4 w-4 rounded-full bg-white transition-transform",P?"translate-x-6":"translate-x-1")})}),a("span",{className:"text-sm text-foreground",children:P?"Ativo":"Inativo"})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Tipo de visualização"}),a("select",{value:M,onChange:e=>L(Number(e.target.value)),disabled:i||H,className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50"),children:Hg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]}),H&&t("div",{className:"space-y-1",children:[a("label",{className:"text-sm text-muted-foreground",children:"Trocar página a cada"}),a("select",{value:z??"",onChange:e=>F(Number(e.target.value)),className:Fi("w-full h-10 rounded-md border border-input bg-background px-3 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:Gg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]})]})]}),b===Nf.Share&&t("div",{className:"max-w-2xl space-y-6",children:[t("div",{className:"flex items-start gap-2 p-3 rounded-md bg-muted/50 border border-border",children:[t("svg",{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("circle",{cx:"12",cy:"12",r:"10"}),a("path",{d:"M12 16v-4"}),a("path",{d:"M12 8h.01"})]}),a("p",{className:"text-sm text-muted-foreground",children:"Configure quem pode visualizar este dashboard. O responsável sempre terá acesso."})]}),a("div",{className:"space-y-3",children:Kg.map(r=>t("label",{className:Fi("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",U===r.value?"border-primary bg-primary/5":"border-border hover:bg-accent/50",e?.isGeneralViewUse&&"opacity-50 pointer-events-none"),children:[a("input",{type:"radio",name:"shareType",value:r.value,checked:U===r.value,onChange:()=>j(r.value),disabled:e?.isGeneralViewUse,className:"mt-1 accent-primary"}),t("div",{children:[a("p",{className:"text-sm font-medium text-foreground",children:r.label}),a("p",{className:"text-xs text-muted-foreground",children:r.description})]})]},r.value))}),U===_f.SharedWithUsersGroupsPlacesCollaborators&&t("div",{className:"space-y-4 pl-4 border-l-2 border-primary/20",children:[t("div",{className:"space-y-1",children:[t("label",{className:"text-sm font-medium text-foreground",children:["Grupos de usuários (",O.length,")"]}),a("select",{multiple:!0,value:O,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);B(a)},className:Fi("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:c.map(e=>a("option",{value:e.id,children:e.name},e.id))})]}),t("div",{className:"space-y-1",children:[t("label",{className:"text-sm font-medium text-foreground",children:["Locais (",$.length,")"]}),a("select",{multiple:!0,value:$,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);V(a)},className:Fi("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:u.map(e=>a("option",{value:e.id,children:e.name},e.id))})]}),t("div",{className:"space-y-1",children:[t("label",{className:"text-sm font-medium text-foreground",children:["Colaboradores (",q.length,")"]}),a("select",{multiple:!0,value:q,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);W(a)},className:Fi("w-full h-24 rounded-md border border-input bg-background px-3 py-2 text-sm","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:m.map(e=>a("option",{value:e.id,children:e.name},e.id))})]})]})]})]})]})}function Xg({dashboards:e,limit:r,generalView:n,language:i=kf.PtBr,isLoading:d=!1,canAdd:c=!1,canEdit:u=!1,canRemove:p=!1,canEditStandard:h=!1,activePanels:f=[],activePages:g=[],getPanelData:v,users:b=[],groups:x=[],places:y=[],collaborators:N=[],isSaving:w=!1,onOpen:_,onBackToList:C,onRefresh:k,onRefreshList:S,onToggleFavorite:A,onSave:E,onUpdate:D,onRemove:P,onDuplicate:I,onShare:T,onAddPanel:R,onEditPanel:M,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onSearch:U,onQuickFilterChange:j,onSetGeneralView:O,viewState:B,onViewStateChange:$,listToolbarExtra:V,viewToolbarActions:q,className:W}){const[H,G]=o({mode:"list"}),K=B??H,Y=l(e=>{$?$(e):G(e)},[$]),Q=s(()=>"view"===K.mode||"edit"===K.mode||"share"===K.mode?e.find(e=>e.id===K.dashboardId)??null:null,[e,K]),[X,J]=o(!1),[Z,ee]=o(g[0]?.id);m(()=>{g.length>0&&!Z&&ee(g[0]?.id)},[g,Z]),m(()=>{if("view"!==K.mode||!Q||Q.idViewType!==xf.Carousel||g.length<=1)return;const e=function(e){switch(e){case nf.FiveSeconds:return 5e3;case nf.TenSeconds:return 1e4;case nf.FifteenSeconds:return 15e3;case nf.ThirtySeconds:return 3e4;case nf.OneMinute:return 6e4;case nf.ThreeMinutes:return 18e4;case nf.FiveMinutes:return 3e5;case nf.TenMinutes:return 6e5;default:return 15e3}}(Q.idPageTime),a=setInterval(()=>{ee(e=>{const a=(g.findIndex(a=>a.id===e)+1)%g.length;return g[a]?.id})},e);return()=>clearInterval(a)},[K,Q,g]);const ae=l(e=>{Y({mode:"view",dashboardId:e.id}),ee(void 0),_?.(e)},[Y,_]),te=l(()=>{Y({mode:"list"}),J(!1),C?.()},[Y,C]),re=l(()=>{Y({mode:"create"})},[Y]),ne=l(e=>{Y({mode:"edit",dashboardId:e.id})},[Y]),ie=l(e=>{Y({mode:"share",dashboardId:e.id})},[Y]),oe=l(e=>{"edit"===K.mode||"share"===K.mode?D?.(K.dashboardId,e):E?.(e)},[K,E,D]),se=l(()=>{"edit"===K.mode||"share"===K.mode?Y({mode:"view",dashboardId:K.dashboardId}):Y({mode:"list"})},[K,Y]),le=l(()=>{Q&&A?.(Q)},[Q,A]),de=l(()=>{Q&&ne(Q)},[Q,ne]),ce=l(()=>{Q&&ie(Q)},[Q,ie]);return t("div",{className:Fi("flex flex-col h-full",W),children:["list"===K.mode&&a(qg,{dashboards:e,limit:r,isLoading:d,language:i,canAdd:c,canEdit:u,canRemove:p,onOpen:ae,onEdit:ne,onShare:ie,onDuplicate:I,onRemove:P,onAdd:re,onToggleFavorite:A,onRefresh:S,onSearch:U,onQuickFilterChange:j,toolbarExtra:V,className:"flex-1"}),"view"===K.mode&&Q&&t("div",{className:"flex flex-col h-full",children:[!X&&t("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:[t("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]}),n?.dashboardId===Q.id&&t("span",{className:"ml-auto inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary",children:[t("svg",{className:"h-3 w-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[a("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),a("polyline",{points:"9 22 9 12 15 12 15 22"})]}),"Visão geral"]}),u&&O&&n?.dashboardId!==Q.id&&a("button",{onClick:()=>O(Q.id),className:"ml-auto text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Definir como visão geral"})]}),a(Og,{dashboard:Q,panels:f,pages:g,activePageId:Z,canEdit:u||h&&!!Q.isStandard,isFullscreen:X,isLoading:d,getPanelData:v,onRefresh:k,onToggleFullscreen:()=>J(e=>!e),onToggleFavorite:le,onEdit:de,onShare:ce,onAddPanel:R,onEditPanel:M,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onPageChange:ee,toolbarActions:q,className:"flex-1"})]}),"create"===K.mode&&t("div",{className:"flex flex-col h-full",children:[a("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:t("button",{onClick:te,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"m15 18-6-6 6-6"})}),"Voltar para lista"]})}),a(Qg,{users:b,groups:x,places:y,collaborators:N,isSaving:w,onSave:oe,onCancel:se,className:"flex-1"})]}),("edit"===K.mode||"share"===K.mode)&&Q&&t("div",{className:"flex flex-col h-full",children:[a("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border bg-card",children:t("button",{onClick:se,className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[a("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:a("path",{d:"m15 18-6-6 6-6"})}),"Voltar"]})}),a(Qg,{dashboard:Q,initialTab:"share"===K.mode?Nf.Share:Nf.General,users:b,groups:x,places:y,collaborators:N,isSaving:w,isQualitfy:!!Q.isStandard&&!h,onSave:oe,onCancel:se,className:"flex-1"})]})]})}function Jg(){return`n_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Zg(e,a){return{id:a?.id??Jg(),text:e,children:a?.children,collapsed:a?.collapsed,color:a?.color,icon:a?.icon,note:a?.note,side:a?.side}}function ev(e,a){if(e.id===a)return{node:e,parent:null};const t=[];for(const r of e.children??[])t.push({node:r,parent:e});for(;t.length;){const e=t.pop();if(e.node.id===a)return{node:e.node,parent:e.parent};for(const a of e.node.children??[])t.push({node:a,parent:e.node})}return null}function av(e,a){const t=a(e);return t.children?.length?{...t,children:t.children.map(e=>av(e,a))}:t}function tv(e,a,t){return av(e,e=>e.id===a?t(e):e)}function rv(e){return{left:(e.children??[]).filter(e=>"left"===e.side).length,right:(e.children??[]).filter(e=>"left"!==e.side).length}}function nv(e,a,t){const r=Zg(t||"");let n=r.id;const i=av(e,t=>{if(t.id!==a)return t;let i=r;if(t.id===e.id){const a=rv(e);i={...i,side:a.left<=a.right?"left":"right"}}else i={...i,side:t.side};return n=i.id,{...t,collapsed:!1,children:[...t.children??[],i]}});return{root:i,newId:n}}function iv(e,a,t){if(e.id===a)return nv(e,a,t);const r=ev(e,a);if(!r||!r.parent)return{root:e,newId:a};const n=r.parent,i=Zg(t||"",{side:r.node.side}),o=i.id,s=av(e,e=>{if(e.id!==n.id)return e;const t=(e.children??[]).findIndex(e=>e.id===a),r=[...e.children??[]];return r.splice(t+1,0,i),{...e,children:r}});return{root:s,newId:o}}function ov(e,a){if(e.id===a)return{root:e,nextSelectedId:a};const t=ev(e,a);if(!t||!t.parent)return{root:e,nextSelectedId:null};const r=t.parent,n=r.children??[],i=n.findIndex(e=>e.id===a),o=n[i+1]?.id??n[i-1]?.id??r.id,s=av(e,e=>e.id!==r.id?e:{...e,children:(e.children??[]).filter(e=>e.id!==a)});return{root:s,nextSelectedId:o}}function sv(e,a,t){if(a===t)return e;if(a===e.id)return e;if(function(e,a,t){const r=ev(e,a);return!!r&&!!ev(r.node,t)}(e,a,t))return e;const r=ev(e,a);if(!r)return e;const n=(()=>{if(t===e.id){const a=rv(e);return{...r.node,side:a.left<=a.right?"left":"right"}}const a=ev(e,t)?.node;return{...r.node,side:a?.side}})(),i=av(e,e=>e.children?.length&&e.children.some(e=>e.id===a)?{...e,children:e.children.filter(e=>e.id!==a)}:e);return av(i,e=>e.id!==t?e:{...e,collapsed:!1,children:[...e.children??[],n]})}function lv(e,a){return tv(e,a,e=>({...e,collapsed:!e.collapsed}))}function dv(e,a){return av(e,t=>t.children?.length?t.id===e.id&&a?t:{...t,collapsed:a}:t)}function cv(e){const{value:a,defaultValue:t,onChange:r,readOnly:n}=e,i=void 0!==a,[d,c]=o(()=>t??a??Zg("Mapa Mental",{id:"root"})),m=i?a:d,[p,h]=o(m.id),f=u([]),g=u([]),v=l((e,a)=>{n||(f.current.push(a),f.current.length>50&&f.current.shift(),g.current=[],i||c(e),r?.(e))},[i,r,n]),b=l((e,a)=>{const t=tv(m,e,e=>({...e,text:a}));v(t,m)},[m,v]),x=l((e,a)=>{const t=tv(m,e,e=>({...e,...a}));v(t,m)},[m,v]),y=l((e,a="")=>{const{root:t,newId:r}=nv(m,e,a);return v(t,m),h(r),r},[m,v]),N=l((e,a="")=>{const{root:t,newId:r}=iv(m,e,a);return v(t,m),h(r),r},[m,v]),w=l(e=>{const{root:a,nextSelectedId:t}=ov(m,e);a!==m&&(v(a,m),h(t))},[m,v]),_=l((e,a)=>{const t=sv(m,e,a);t!==m&&v(t,m)},[m,v]),C=l(e=>{const a=ev(m,e);if(!a||!a.node.children?.length)return;const t=lv(m,e);v(t,m)},[m,v]),k=l(()=>{v(dv(m,!1),m)},[m,v]),S=l(()=>{v(dv(m,!0),m)},[m,v]),A=l(()=>{const e=f.current.pop();e&&(g.current.push(m),i||c(e),r?.(e))},[m,i,r]),E=l(()=>{const e=g.current.pop();e&&(f.current.push(m),i||c(e),r?.(e))},[m,i,r]),D=f.current.length>0,P=g.current.length>0,I=s(()=>p?ev(m,p)?.node??null:null,[m,p]),T=l(e=>{v(e,m)},[m,v]);return{root:m,setRoot:T,selectedId:p,selectedNode:I,setSelectedId:h,renameNode:b,updateNodeProps:x,addChild:y,addSibling:N,removeNode:w,moveNode:_,toggleNode:C,expandAll:k,collapseAll:S,undo:A,redo:E,canUndo:D,canRedo:P}}const uv=180,mv=80,pv=16,hv=60;function fv(e){const a=(e.collapsed?[]:e.children??[]).map(fv);if(!a.length)return{node:e,visibleChildren:a,height:44};const t=a.reduce((e,a)=>e+a.height,0)+pv*(a.length-1);return{node:e,visibleChildren:a,height:Math.max(44,t)}}function gv(e,a,t,r,n,i,o){const s=[],l={node:e.node,parent:a,x:t,y:r,width:180,height:44,side:n,depth:i,visibleChildren:s};if(o.push(l),!e.visibleChildren.length)return l;let d=r+22-(e.visibleChildren.reduce((e,a)=>e+a.height,0)+pv*(e.visibleChildren.length-1))/2;for(const c of e.visibleChildren){const a="right"===n?t+180+mv:t-mv-uv,r=d+c.height/2-22,l=gv(c,e.node,a,r,n,i+1,o);s.push(l),d+=c.height+pv}return l}function vv(e){return s(()=>function(e){const a=e.collapsed?[]:e.children??[],t=a.filter(e=>"left"!==e.side).map(fv),r=a.filter(e=>"left"===e.side).map(fv),n=t.reduce((e,a)=>e+a.height,0)+pv*Math.max(0,t.length-1),i=r.reduce((e,a)=>e+a.height,0)+pv*Math.max(0,r.length-1),o=Math.max(n,i,56),s=e=>e.visibleChildren.length?1+Math.max(...e.visibleChildren.map(s)):0,l=t.length?Math.max(...t.map(s))+1:0,d=260*(r.length?Math.max(...r.map(s))+1:0),c=220+260*l+d+120,u=o+120,m=hv+d,p=[],h={node:e,parent:null,x:m,y:hv+o/2-28,width:220,height:56,side:"root",depth:0,visibleChildren:[]};p.push(h);let f=hv+o/2-n/2;for(const b of t){const a=f+b.height/2-22,t=gv(b,e,m+220+mv,a,"right",1,p);h.visibleChildren.push(t),f+=b.height+pv}let g=hv+o/2-i/2;for(const b of r){const a=g+b.height/2-22,t=gv(b,e,m-mv-uv,a,"left",1,p);h.visibleChildren.push(t),g+=b.height+pv}const v=new Map(p.map(e=>[e.node.id,e]));return{nodes:p,byId:v,width:c,height:u}}(e),[e])}function bv(e,a){const{layout:t,selectedId:r,setSelectedId:n}=a;if(!r)return void n(t.nodes[0]?.node.id??null);const i=t.byId.get(r);if(!i)return;if("left"===e||"right"===e){if("root"===i.side){const a=i.visibleChildren.find(a=>a.side===e);return void(a&&n(a.node.id))}if(e===i.side){const e=i.visibleChildren[Math.floor(i.visibleChildren.length/2)];e&&n(e.node.id)}else i.parent&&n(i.parent.id);return}if(!i.parent)return;const o=t.byId.get(i.parent.id);if(!o)return;const s=o.visibleChildren.filter(e=>e.side===i.side),l=s.findIndex(e=>e.node.id===r),d="up"===e?s[l-1]:s[l+1];d&&n(d.node.id)}const xv=({layout:e,selected:r,editing:i,readOnly:o,onSelect:s,onStartEditing:l,onFinishEditing:d,onToggle:c,onDragStart:u,onDragOver:m,onDragLeave:p,onDrop:h,isDropTarget:f,renderNodeContent:g})=>{const v=e.node,b="root"===e.side,x=(y=v.icon)?S[y]??null:null;var y;const N=!!v.children?.length,w=n.useRef(null),[_,C]=n.useState(v.text);n.useEffect(()=>{if(i){C(v.text);const e=window.setTimeout(()=>{w.current?.focus(),w.current?.select()},0);return()=>window.clearTimeout(e)}},[i,v.text]);const k=()=>{d(_.trim()||v.text)},A=v.color;return t("div",{role:"treeitem","aria-selected":r,"aria-expanded":N?!v.collapsed:void 0,tabIndex:r?0:-1,"data-node-id":v.id,draggable:!o&&!b&&!i,onDragStart:u,onDragOver:m,onDragLeave:p,onDrop:h,onClick:e=>{e.stopPropagation(),s()},onDoubleClick:e=>{e.stopPropagation(),o||l()},className:Fi("absolute flex items-center gap-2 rounded-lg border bg-card text-card-foreground px-3 select-none transition-shadow","shadow-sm hover:shadow-md cursor-pointer",b&&"font-semibold border-primary/40 bg-primary text-primary-foreground",r&&!b&&"ring-2 ring-primary ring-offset-1",r&&b&&"ring-2 ring-primary-foreground/60 ring-offset-1",f&&"ring-2 ring-accent border-accent"),style:{left:e.x,top:e.y,width:e.width,height:e.height,backgroundColor:A},children:[x&&a(x,{className:Fi("h-4 w-4 shrink-0",b&&"text-primary-foreground")}),a("div",{className:"flex-1 min-w-0",children:i?a("input",{ref:w,value:_,onChange:e=>C(e.target.value),onBlur:k,onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),k()):"Escape"===e.key?(e.preventDefault(),d(null)):e.stopPropagation()},className:Fi("w-full bg-transparent outline-none text-sm",b&&"text-primary-foreground placeholder:text-primary-foreground/60")}):a("div",g?{className:"text-sm truncate",children:g(v)}:{className:"text-sm truncate",children:v.text||a("span",{className:"opacity-50",children:"—"})})}),v.note&&!i&&t(hs,{children:[a(fs,{asChild:!0,children:a("button",{type:"button",onClick:e=>e.stopPropagation(),className:Fi("shrink-0 rounded p-0.5 hover:bg-muted/40",b&&"hover:bg-primary-foreground/10"),"aria-label":v.note,children:a(Be,{className:"h-3.5 w-3.5 opacity-70"})})}),a(gs,{className:"max-w-xs whitespace-pre-line",children:v.note})]}),N&&a("button",{type:"button",onClick:e=>{e.stopPropagation(),c()},className:Fi("shrink-0 rounded-full border bg-background text-foreground h-5 w-5 flex items-center justify-center -mr-1","shadow-sm hover:bg-muted transition-colors",b&&"border-primary-foreground/30"),"aria-label":v.collapsed?"Expandir":"Colapsar",children:v.collapsed?a(Q,{className:"h-3 w-3"}):"left"===e.side?a(U,{className:"h-3 w-3 rotate-180"}):"right"===e.side?a(U,{className:"h-3 w-3"}):a(na,{className:"h-3 w-3"})})]})},yv=({parent:e,child:t})=>{const r=t.x+t.width/2<e.x+e.width/2,n=r?e.x:e.x+e.width,i=e.y+e.height/2,o=r?t.x+t.width:t.x,s=t.y+t.height/2,l=(n+o)/2;return a("path",{d:`M ${n} ${i} C ${l} ${i}, ${l} ${s}, ${o} ${s}`,fill:"none",stroke:"hsl(var(--border))",strokeWidth:2,strokeLinecap:"round"})},Nv=({label:e,icon:r,onClick:n,disabled:i})=>t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",onClick:n,disabled:i,"aria-label":e,className:"h-8 w-8",children:r})}),a(gs,{children:e})]}),wv=e=>{const{t:r}=Ga();return t("div",{className:"flex items-center gap-1 border-b bg-card px-2 py-1.5",children:[a(Nv,{label:r("mind_map_add_child"),icon:a(ia,{className:"h-4 w-4"}),onClick:e.onAddChild,disabled:!e.canAddChild}),a(Nv,{label:r("mind_map_add_sibling"),icon:a(Q,{className:"h-4 w-4"}),onClick:e.onAddSibling,disabled:!e.canAddSibling}),a(Nv,{label:r("mind_map_delete_node"),icon:a(H,{className:"h-4 w-4"}),onClick:e.onDelete,disabled:!e.canDelete}),a(Zi,{orientation:"vertical",className:"mx-1 h-5"}),a(Nv,{label:r("mind_map_expand_all"),icon:a(oa,{className:"h-4 w-4"}),onClick:e.onExpandAll}),a(Nv,{label:r("mind_map_collapse_all"),icon:a(sa,{className:"h-4 w-4"}),onClick:e.onCollapseAll}),a(Zi,{orientation:"vertical",className:"mx-1 h-5"}),a(Nv,{label:r("mind_map_zoom_out"),icon:a(la,{className:"h-4 w-4"}),onClick:e.onZoomOut}),a(Nv,{label:r("mind_map_zoom_in"),icon:a(da,{className:"h-4 w-4"}),onClick:e.onZoomIn}),a(Nv,{label:r("mind_map_fit_to_screen"),icon:a(ca,{className:"h-4 w-4"}),onClick:e.onFit}),a(Zi,{orientation:"vertical",className:"mx-1 h-5"}),a(Nv,{label:r("mind_map_undo"),icon:a(ua,{className:"h-4 w-4"}),onClick:e.onUndo,disabled:!e.canUndo}),a(Nv,{label:r("mind_map_redo"),icon:a(ma,{className:"h-4 w-4"}),onClick:e.onRedo,disabled:!e.canRedo}),a("div",{className:"flex-1"}),a(Nv,{label:r("mind_map_export_json"),icon:a(Je,{className:"h-4 w-4"}),onClick:e.onExportJson}),a(Nv,{label:r("mind_map_export_image"),icon:a(Ve,{className:"h-4 w-4"}),onClick:e.onExportImage})]})};function _v(e){return JSON.stringify(e,null,2)}function Cv(e){if(!e||"object"!=typeof e)throw new Error("Invalid mind map node: not an object");const a=e;if("string"!=typeof a.text)throw new Error('Invalid mind map node: missing "text"');const t=Array.isArray(a.children)?a.children.map(e=>Cv(e)):void 0;return Zg(a.text,{id:"string"==typeof a.id?a.id:void 0,collapsed:"boolean"==typeof a.collapsed?a.collapsed:void 0,color:"string"==typeof a.color?a.color:void 0,icon:"string"==typeof a.icon?a.icon:void 0,note:"string"==typeof a.note?a.note:void 0,side:"left"===a.side||"right"===a.side?a.side:void 0,children:t})}function kv(e){return Cv(JSON.parse(e))}const Sv=({value:e,defaultValue:r,onChange:i,onNodeSelect:s,readOnly:d=!1,hideToolbar:c=!1,extraShortcuts:p,renderNodeContent:h,className:f,height:g=600})=>{const{t:v}=Ga(),b=cv({value:e,defaultValue:r,onChange:i,readOnly:d}),x=vv(b.root),y=function(){const[e,a]=o({x:0,y:0,scale:1}),t=u(!1),r=u({x:0,y:0,tx:0,ty:0}),n=l(a=>{0!==a.button&&1!==a.button||(t.current=!0,r.current={x:a.clientX,y:a.clientY,tx:e.x,ty:e.y},a.currentTarget.setPointerCapture(a.pointerId))},[e.x,e.y]),i=l(e=>{t.current&&a(a=>({...a,x:r.current.tx+(e.clientX-r.current.x),y:r.current.ty+(e.clientY-r.current.y)}))},[]),s=l(e=>{if(t.current){t.current=!1;try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}}},[]),d=l((e,t,r)=>{a(a=>{const n=Math.min(2.5,Math.max(.3,a.scale+e));if(n===a.scale)return a;if(void 0===t||void 0===r)return{...a,scale:n};const i=n/a.scale;return{scale:n,x:t-(t-a.x)*i,y:r-(r-a.y)*i}})},[]),c=l(()=>d(.15),[d]),p=l(()=>d(-.15),[d]),h=l(()=>a({x:0,y:0,scale:1}),[]),f=l((e,t,r,n)=>{const i=Math.min((r-64)/e,(n-64)/t,1.5),o=Math.max(.3,i);a({scale:o,x:(r-e*o)/2,y:(n-t*o)/2})},[]),g=l(e=>{if(!e.ctrlKey&&!e.metaKey)return;e.preventDefault();const a=e.currentTarget.getBoundingClientRect(),t=e.clientX-a.left,r=e.clientY-a.top;d(e.deltaY>0?-.1:.1,t,r)},[d]);return m(()=>{const e=()=>t.current=!1;return window.addEventListener("pointerup",e),()=>window.removeEventListener("pointerup",e)},[]),{transform:e,setTransform:a,zoomIn:c,zoomOut:p,reset:h,fitTo:f,onBackgroundPointerDown:n,onPointerMove:i,onPointerUp:s,onWheel:g}}(),N=n.useRef(null),w=n.useRef(null),_=n.useRef(null),[C,k]=n.useState(null),[S,A]=n.useState(null);n.useEffect(()=>{s?.(b.selectedNode)},[b.selectedNode,s]),function({api:e,layout:a,containerRef:t,onStartEditing:r,readOnly:n,extraShortcuts:i}){m(()=>{const o=o=>{const s=t.current;if(!s)return;if(!s.contains(document.activeElement))return;const l=o.target;if(l?.isContentEditable)return;if(l&&("INPUT"===l.tagName||"TEXTAREA"===l.tagName))return;const d={layout:a,selectedId:e.selectedId,setSelectedId:e.setSelectedId},c=e.selectedId;for(const a of i??[])if(a.key.toLowerCase()===o.key.toLowerCase()&&!!a.ctrl===(o.ctrlKey||o.metaKey)&&!!a.shift===o.shiftKey&&!!a.alt===o.altKey)return o.preventDefault(),void a.handler({selectedId:e.selectedId,root:e.root,setRoot:e.setRoot,select:e.setSelectedId});if((o.ctrlKey||o.metaKey)&&"z"===o.key.toLowerCase())return o.preventDefault(),void(o.shiftKey?e.redo():e.undo());if("ArrowUp"===o.key)return o.preventDefault(),void bv("up",d);if("ArrowDown"===o.key)return o.preventDefault(),void bv("down",d);if("ArrowLeft"===o.key)return o.preventDefault(),void bv("left",d);if("ArrowRight"===o.key)return o.preventDefault(),void bv("right",d);if(c){if(" "===o.key)return o.preventDefault(),void e.toggleNode(c);if("F2"===o.key){if(n)return;return o.preventDefault(),void r(c)}if(!n){if("Enter"===o.key&&!o.shiftKey)return o.preventDefault(),c===e.root.id?e.addChild(c,""):e.addSibling(c,""),void setTimeout(()=>{e.selectedId&&r(e.selectedId)},0);if("Insert"===o.key||"Tab"===o.key)return o.preventDefault(),e.addChild(c,""),void setTimeout(()=>{e.selectedId&&r(e.selectedId)},0);if("Delete"===o.key||"Backspace"===o.key){if(c===e.root.id)return;return o.preventDefault(),void e.removeNode(c)}}}};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[e,a,t,r,n,i])}({api:b,layout:x,containerRef:N,onStartEditing:e=>{d||k(e)},readOnly:d,extraShortcuts:p});const E=n.useRef(!1);n.useEffect(()=>{if(E.current)return;const e=w.current;if(!e)return;const{clientWidth:a,clientHeight:t}=e;a>0&&t>0&&x.width>0&&(y.fitTo(x.width,x.height,a,t),E.current=!0)},[x.width,x.height,y]);const D=b.selectedId,P=b.selectedNode,I=D===b.root.id,T=n.useRef(null),R=e=>a=>{if(d)return;const t=T.current;if(!t||t===e)return;const r=ev(b.root,t);r&&ev(r.node,e)||(a.preventDefault(),a.dataTransfer.dropEffect="move",A(e))},M=()=>A(null),L=e=>a=>{a.preventDefault();const t=T.current;A(null),T.current=null,t&&t!==e&&b.moveNode(t,e)};return a(ps,{children:t("div",{ref:N,tabIndex:0,role:"tree","aria-label":v("mind_map_aria_label"),className:Fi("relative flex flex-col rounded-lg border bg-muted/20 overflow-hidden focus:outline-none",f),style:{height:g},onClick:()=>N.current?.focus(),children:[!c&&a(wv,{canAddChild:!!P&&!d,canAddSibling:!!P&&!d,canDelete:!!P&&!I&&!d,canUndo:b.canUndo&&!d,canRedo:b.canRedo&&!d,onAddChild:()=>{if(!D)return;const e=b.addChild(D,"");k(e)},onAddSibling:()=>{if(!D)return;if(I){const e=b.addChild(D,"");return void k(e)}const e=b.addSibling(D,"");k(e)},onDelete:()=>{D&&!I&&b.removeNode(D)},onExpandAll:b.expandAll,onCollapseAll:b.collapseAll,onFit:()=>{const e=w.current;e&&y.fitTo(x.width,x.height,e.clientWidth,e.clientHeight)},onZoomIn:y.zoomIn,onZoomOut:y.zoomOut,onUndo:b.undo,onRedo:b.redo,onExportJson:()=>{!function(e,a,t="application/json"){const r=new Blob([e],{type:t}),n=URL.createObjectURL(r),i=document.createElement("a");i.href=n,i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(n)}(_v(b.root),"mind-map.json")},onExportImage:async()=>{if(_.current)try{await async function(e,a="mind-map.png"){const t=e.cloneNode(!0),r=(new XMLSerializer).serializeToString(t),n=`data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(r)))}`,i=new Image;await new Promise((e,a)=>{i.onload=()=>e(),i.onerror=()=>a(new Error("Failed to load SVG snapshot")),i.src=n});const o=e.clientWidth||Number(e.getAttribute("width"))||1200,s=e.clientHeight||Number(e.getAttribute("height"))||800,l=document.createElement("canvas");l.width=2*o,l.height=2*s;const d=l.getContext("2d");if(!d)throw new Error("Canvas 2D context unavailable");d.fillStyle="#ffffff",d.fillRect(0,0,l.width,l.height),d.drawImage(i,0,0,l.width,l.height);const c=await new Promise(e=>l.toBlob(e,"image/png"));if(!c)throw new Error("Failed to create PNG blob");const u=URL.createObjectURL(c),m=document.createElement("a");m.href=u,m.download=a,document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(u)}(_.current,"mind-map.png")}catch(e){}}}),a("div",{ref:w,className:"relative flex-1 overflow-hidden cursor-grab active:cursor-grabbing",onPointerDown:e=>{e.target===e.currentTarget&&(y.onBackgroundPointerDown(e),b.setSelectedId(null))},onPointerMove:y.onPointerMove,onPointerUp:y.onPointerUp,onWheel:y.onWheel,children:t("div",{className:"absolute origin-top-left",style:{transform:`translate(${y.transform.x}px, ${y.transform.y}px) scale(${y.transform.scale})`,width:x.width,height:x.height},children:[a("svg",{ref:_,width:x.width,height:x.height,className:"absolute inset-0 pointer-events-none",xmlns:"http://www.w3.org/2000/svg",children:x.nodes.map(e=>e.visibleChildren.map(t=>a(yv,{parent:e,child:t},`${e.node.id}-${t.node.id}`)))}),x.nodes.map(e=>{return a(xv,{layout:e,selected:D===e.node.id,editing:C===e.node.id,readOnly:d,onSelect:()=>b.setSelectedId(e.node.id),onStartEditing:()=>k(e.node.id),onFinishEditing:a=>{null!==a&&b.renameNode(e.node.id,a),k(null)},onToggle:()=>b.toggleNode(e.node.id),onDragStart:(t=e.node.id,e=>{d||t===b.root.id||(T.current=t,e.dataTransfer.setData("text/plain",t),e.dataTransfer.effectAllowed="move")}),onDragOver:R(e.node.id),onDragLeave:M,onDrop:L(e.node.id),isDropTarget:S===e.node.id,renderNodeContent:h},e.node.id);var t})]})})]})})},Av=({manager:n,columns:i,onEdit:o,onView:s,onToggleStatus:l,onDelete:d,renderActions:c,customRowActions:u,enableBulkActions:p=!1,onNew:h,newButtonLabel:f,showNewButton:g=!0,customActions:v=[],hideActionBar:b,showActionBar:x=!0,showSearch:y=!1,searchValue:N,onSearchChange:w,searchPlaceholder:_,bulkActions:C=[],onBulkDelete:k,filters:S,gridColumns:A=3,renderCard:E,viewMode:D,onViewModeChange:P,listCardRenderer:I,gridCardRenderer:T,showViewToggle:R=!1})=>{const{setSearchVisible:M}=kl(),L=void 0!==b?!b:x;m(()=>{if(!y)return M(!0),()=>M(!1)},[M,y]);const z=h||v.length>0||y||p||S||R,F=k||(()=>{n.bulkDelete?.(n.selectedIds)}),U=D||"grid",j="list"===U,O={1:"grid-cols-1",2:"grid-cols-1 md:grid-cols-2",3:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3",4:"grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"}[j?1:A],B=L&&z?a(bd,{onNew:h,newButtonLabel:f,showNewButton:g,showSearch:y,searchValue:N,onSearchChange:w,searchPlaceholder:_,showBulkActions:p,selectedCount:n.selectedIds.length,bulkActions:C,onBulkDelete:F,onClearSelection:n.clearSelection,customActions:v,filters:S,viewMode:U,onViewModeChange:P,showViewToggle:R,availableViewModes:["list","grid"]}):null;return n.isLoading?t("div",{className:"flex flex-col h-full",children:[B,a("div",{className:"flex-1 overflow-auto p-4",children:a(jl,{count:6})})]}):0===n.entities.length?t("div",{className:"flex flex-col h-full",children:[B,a("div",{className:"flex-1 flex items-center justify-center",children:a(ql,{title:e.t("no_items_found_empty"),description:e.t("no_data_to_display"),variant:"search"})})]}):t("div",{className:"flex flex-col h-full",children:[B,a("div",{className:"flex-1 overflow-auto p-4",children:a("div",{className:Fi("grid gap-4",O),children:n.entities.map(e=>{const m=(e=>{const{t:a}=Ga();return j&&I?I(e):!j&&T?T(e):E?E(e):null})(e);return t(Gl,{children:[a(Kl,{asChild:!0,children:m?a("div",{className:"cursor-pointer",onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):o?.(e)},children:m}):a(Gi,{className:Fi("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",p&&n.selectedIds.includes(e.id)&&"bg-muted ring-2 ring-primary",j&&"flex-row"),onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):o?.(e)},children:t(Xi,{className:Fi("p-4",j&&"flex items-center gap-4 w-full"),children:[p&&a("div",{className:Fi(j?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:a(xd,{checked:n.selectedIds.includes(e.id),onCheckedChange:()=>n.selectItem(e.id)})}),j?t(r,{children:[a("div",{className:"flex-1 flex items-center gap-6 min-w-0",children:i.map(r=>t("div",{className:"flex items-center gap-2 min-w-0",children:[t("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[r.header,":"]}),a("div",{className:"text-sm text-foreground truncate",children:r.render?r.render(e):String(e[r.key]??"")})]},String(r.key)))}),(o||s||c)&&a("div",{onClick:e=>e.stopPropagation(),children:c?c(e):a(dd,{onEdit:o?()=>o(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,customActions:u?u(e):[]})})]}):t("div",{className:"flex items-start gap-3",children:[p&&a("div",{className:"pt-0.5",onClick:e=>e.stopPropagation(),children:a(xd,{checked:n.selectedIds.includes(e.id),onCheckedChange:()=>n.selectItem(e.id)})}),t("div",{className:"flex-1 min-w-0",children:[i.map((r,n)=>t("div",{className:Fi("flex justify-between items-start gap-2",n!==i.length-1&&"mb-2"),children:[t("span",{className:"text-sm font-medium text-muted-foreground shrink-0",children:[r.header,":"]}),a("div",{className:"text-sm text-foreground text-right truncate",children:r.render?r.render(e):String(e[r.key]??"")})]},String(r.key))),(o||s||c)&&a("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(e):a(dd,{onEdit:o?()=>o(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,customActions:u?u(e):[]})})]})]})]})})}),a(ad,{className:"w-[160px]",children:a(ld,{onEdit:o?()=>o(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,canDelete:!!d,customActions:u?u(e):[],renderAs:"context"})})]},e.id)})})})]})};function Ev({data:e,columns:r,sortField:n,sortDirection:d,onSort:c,onRowClick:u,renderActions:m,isLoading:p=!1,emptyMessage:h,className:f,enableSelection:g=!1,selectedIds:v=[],onSelectItem:b,onSelectAll:x,isAllSelected:y=!1,enableColumnResize:N=!0,onColumnResize:w,enableColumnReorder:_=!1,onReorderColumns:C,storageKey:k,enableExpandableRows:S=!1,renderExpandedContent:A,expandedRowIds:E,onToggleExpand:P,defaultExpandAll:I=!1,rowActionsVariant:T="default",hideActionsColumn:R=!1,actionsHeaderContent:M}){const{t:L}=Ga(),z=h||L("no_items_found",L("no_items_found_empty")),[F,j]=o(()=>I?new Set(e.map(e=>e.id)):new Set),O=void 0!==E,B=O?new Set(E):F,$=l(e=>{O&&P?P(e):j(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[O,P]),{columnWidths:V,isDragging:q,activeColumn:W,handleMouseDown:H}=md({columns:r.map(e=>({key:String(e.key),minWidth:e.minWidth??60,maxWidth:e.maxWidth??500,defaultWidth:e.width??e.minWidth??150})),storageKey:k?`${k}-columns`:void 0,onResize:w,enabled:N}),G=wd({enabled:_&&!!C,onReorder:C??(()=>{})}),K=s(()=>{if(N){const e=r.map(e=>V[String(e.key)]??e.width??e.minWidth??150),a=e.reduce((e,a)=>e+a,0);return e.map(e=>e/a*100+"%")}const e=r.reduce((e,a)=>a.width?e:e+(a.weight??1),0);return r.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}%`})},[r,N,V]);if(p)return a("div",{className:"flex-1 overflow-auto",children:a("div",{className:"p-4 space-y-3",children:[...Array(5)].map((e,t)=>a(Ps,{className:"h-12 w-full"},t))})});if(0===e.length)return a("div",{className:"flex-1 flex items-center justify-center",children:a("div",{className:"text-center text-muted-foreground",children:a("p",{children:z})})});const Y=m&&!R,Q=(g?1:0)+(S?1:0)+r.length+(Y?1:0);return a("div",{className:"flex-1 overflow-auto "+(q?"select-none":""),children:t(Pl,{className:Fi("table-fixed w-full",f),children:[a(Il,{className:"sticky top-0 bg-background z-10",children:t(Ml,{children:[S&&a(Ll,{className:"w-[40px]"}),g&&a(Ll,{className:"w-[40px]",children:a(qo,{checked:y,onCheckedChange:x,"aria-label":L("select_all","Selecionar todos")})}),r.map((e,r)=>{const i=N&&!1!==e.resizable,o=W===String(e.key),s=_&&!!C,l=s?G.getDragProps(r):{},u=G.dragFromIndex===r,m=G.dragOverIndex===r&&G.dragFromIndex!==r;return t(Ll,{className:Fi(e.className,"relative transition-opacity",e.sortable&&"cursor-pointer",s&&G.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:K[r]},...l,children:[!1!==e.sortable&&c?t("button",{onClick:()=>c(String(e.key)),className:"flex items-center hover:text-foreground transition-colors font-medium",children:[e.header,(p=String(e.key),n!==p?null:a("asc"===d?re:ne,{size:14,className:"ml-1"}))]}):a("span",{className:"font-medium",children:e.header}),i&&a(Hl,{direction:"horizontal",onMouseDown:a=>H(String(e.key),a),isDragging:o})]},String(e.key));var p}),Y&&a(Ll,{className:"w-[80px] text-right",children:M??L("actions","Ações")})]})}),a(Tl,{children:e.map(e=>{const n=S&&B.has(e.id);return t(i.Fragment,{children:[t(Ml,{onClick:()=>u?.(e),className:Fi(u?"cursor-pointer":"","relative","inline"===T&&"group"),children:[S&&a(zl,{className:"w-[40px] px-2",children:a("button",{onClick:a=>{a.stopPropagation(),$(e.id)},className:"p-1 rounded-sm hover:bg-muted transition-colors","aria-label":n?L("collapse_row","Recolher linha"):L("expand_row","Expandir linha"),children:a(n?D:U,{size:16,className:"text-muted-foreground"})})}),g&&a(zl,{children:a(qo,{checked:v.includes(e.id),onCheckedChange:()=>b?.(e.id),onClick:e=>e.stopPropagation(),"aria-label":`${L("select_all","Selecionar todos")} ${e.id}`})}),r.map(t=>a(zl,{className:t.className,children:a(Wl,{children:t.render?t.render(e):String(e[t.key]??"-")})},String(t.key))),Y&&a(zl,{className:"text-right",onClick:e=>e.stopPropagation(),children:"inline"===T?a("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:m(e)}):m(e)})]}),n&&A&&a(Ml,{className:"bg-muted/30 hover:bg-muted/30",children:a(zl,{colSpan:Q,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:A(e)})})})]},e.id)})})]})})}function Dv({onEdit:e,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:o=!0,canDelete:l=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=Ga(),p=s(()=>{const a=[];return e&&o&&a.push({key:"edit",icon:V,label:m("edit","Editar"),onClick:e,variant:"default"}),n&&a.push({key:"toggle-status",icon:i?q:W,label:i?m("deactivate","Inativar"):m("activate","Ativar"),onClick:n,variant:"default"}),d.forEach(e=>{!1!==e.show&&a.push({key:`custom-${e.label}`,icon:e.icon,label:e.label,onClick:e.onClick,variant:e.variant||"default",disabled:e.disabled,disabledReason:e.disabledReason})}),r&&l&&a.push({key:"delete",icon:H,label:m("remove","Remover"),onClick:r,variant:"destructive"}),a},[e,r,n,i,o,l,d,m]);return 0===p.length?null:"dropdown"===c?a(ps,{delayDuration:200,children:t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:a(A,{size:"compact"===u?14:16})})}),a(os,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(e=>e.disabled?t(vs,{disabledReason:e.disabledReason,className:"destructive"===e.variant?"text-destructive":"",children:[e.icon&&a(e.icon,{className:"mr-2 h-4 w-4"}),e.label]},e.key):t(ss,{onClick:e.onClick,className:"destructive"===e.variant?"text-destructive":"",children:[e.icon&&a(e.icon,{className:"mr-2 h-4 w-4"}),e.label]},e.key))})]})}):a("div",{className:"flex items-center gap-1",children:p.map(e=>t($i,{variant:"destructive"===e.variant?"destructive":"ghost",size:"compact"===u?"sm":"default",onClick:e.onClick,className:"compact"===u?"h-7 px-2":"",children:[e.icon&&a(e.icon,{size:"compact"===u?14:16}),"compact"!==u&&a("span",{className:"ml-1",children:e.label})]},e.key))})}function Pv({searchValue:e="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:o=!0,layout:s="horizontal"}){const{t:l}=Ga(),d=e||n.length>0;return t("div",{className:`flex ${"vertical"===s?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&t("div",{className:"relative flex-1 min-w-[200px]",children:[a(B,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{type:"text",placeholder:l("search","Pesquisar"),value:e,onChange:e=>r(e.target.value),className:"pl-9 h-9"})]}),n.map((e,t)=>a("div",{className:"vertical"===s?"w-full":"",children:e},t)),o&&d&&i&&t($i,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[a(E,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function Iv(e,a){const t=new Set;function r(e){if(e)for(const a of e)t.add(a.id),r(a.children)}return function e(t){for(const n of t){if(n.id===a)return r(n.children),!0;if(n.children&&e(n.children))return!0}return!1}(e),t}function Tv({children:e,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:o,onDropCell:s,className:l}){return a(zl,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},className:l,children:e})}function Rv({item:e,level:n,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:d,onRowClick:c,renderActions:u,rowActionsVariant:m="default",enableSelection:p,selectedIds:h,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:x,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:_}){const C=l.has(e.id),k=(e.children?.length??0)>0,S=24*n,A="inline"===m,E=v===e.id||h?.has(e.id)&&v&&h?.has(v),P=b===e.id&&v!==e.id,I=h?.has(e.id)??!1,T={itemId:e.id,enableDrag:g,onDragStartCell:x,onDragEndCell:y,onDragOverCell:N,onDropCell:w};return t(r,{children:[t(Ml,{className:Fi(c&&"cursor-pointer",A&&"group",E&&"opacity-40",P&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:c?()=>c(e):void 0,children:[a(Tv,{...T,children:t("div",{className:"flex items-center gap-2",style:{paddingLeft:`${S}px`},children:[p&&a(qo,{checked:I,onCheckedChange:()=>f?.(e.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),g&&a("span",{className:"cursor-grab text-muted-foreground shrink-0 select-none",title:"Arrastar",children:"⠿"}),k?a("button",{onClick:a=>{a.stopPropagation(),d(e.id)},className:"p-1 hover:bg-accent rounded shrink-0",children:a(C?D:U,{className:"h-4 w-4"})}):a("div",{className:"w-6 shrink-0"}),s??a(ge,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"truncate",children:String(e[o]??e.id)}),v===e.id&&_&&_>1&&a("span",{className:"ml-1 inline-flex items-center rounded-full bg-primary px-1.5 py-0 text-xs font-semibold text-primary-foreground",children:_})]})}),i.map(r=>{const i=e[r.key],o=r.render?r.render(e,n):null!=i?String(i):"—";return a(Tv,{...T,className:Fi("text-center",r.className),children:r.hoverContent?t(Hu,{openDelay:200,children:[a(Gu,{asChild:!0,children:a("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:o})}),a(Ku,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:r.hoverContent(e)})]}):o},String(r.key))}),u&&a(Tv,{...T,className:"text-right",children:a("div",{onClick:e=>e.stopPropagation(),className:Fi("flex items-center justify-end gap-1",A&&"opacity-0 group-hover:opacity-100 transition-opacity"),children:u(e)})})]}),k&&C&&e.children.map(e=>a(Rv,{item:e,level:n+1,columns:i,nameKey:o,iconComponent:s,expandedIds:l,onToggleExpand:d,onRowClick:c,renderActions:u,rowActionsVariant:m,enableSelection:p,selectedIds:h,onSelectItem:f,enableRowDrag:g,draggedId:v,dragOverId:b,onDragStartCell:x,onDragEndCell:y,onDragOverCell:N,onDropCell:w,dragCount:_},e.id))]})}function Mv({onDrop:r,isDragOver:n,onDragOver:i,onDragLeave:o,label:s}){return t("div",{className:Fi("absolute top-0 left-0 right-0 z-10 flex items-center justify-center gap-2 py-2 px-4 border-2 border-dashed rounded-md text-sm transition-colors mx-2 mt-2",n?"border-primary bg-primary/10 text-primary":"border-muted-foreground/30 text-muted-foreground bg-background/95"),onDragOver:i,onDragEnter:i,onDragLeave:o,onDrop:r,children:[a(pa,{className:"h-4 w-4"}),s??e.t("leadership_make_root_short")]})}function Lv({data:r,columns:n,nameKey:s,nameHeader:d=e.t("ap_name"),iconComponent:c,expandedIds:m,onToggleExpand:p,onRowClick:h,renderActions:f,actionsHeader:g="",rowActionsVariant:v="default",isLoading:b,emptyMessage:x="Nenhum registro encontrado.",className:y,enableSelection:N,selectedIds:w,onSelectItem:_,onSelectAll:C,isAllSelected:k,enableRowDrag:S,onMoveNode:A,onMoveNodes:E,rootDropLabel:D,actionsWidth:P=20,nameMinWidth:I=200}){const[T,R]=o(null),[M,L]=o(null),[z,F]=o(!1),[U,j]=o(1),O=u(null),B=u([]),$=u(null),V=i.useMemo(()=>new Set(w??[]),[w]),q=i.useMemo(()=>{if(!T||!r)return new Set;const e=B.current.length>0?B.current:[T],a=function(e,a){const t=new Set;for(const r of a)Iv(e,r).forEach(e=>t.add(e));return t}(r,e);return e.forEach(e=>a.add(e)),a},[T,r]),W=u(q);W.current=q;const H=l(()=>{O.current=null,B.current=[],$.current=null,R(null),L(null),F(!1),j(1)},[]),G=l((e,a)=>{e.length>1&&E?E(e,a):1===e.length&&A?.(e[0],a)},[A,E]),K=l((e,a)=>{const t=V.has(e)&&V.size>1?Array.from(V):[e];O.current=e,B.current=t,$.current=null,R(e),j(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[V]),Y=l((e,a)=>{a.preventDefault(),a.dataTransfer.dropEffect="move",W.current.has(e)?L(null):($.current=e,L(e))},[]),Q=l((e,a)=>{a.preventDefault(),a.stopPropagation();const t=W.current.has(e)?$.current:e;if(!t)return void H();let r=B.current;if(0===r.length){try{const e=a.dataTransfer.getData("application/x-tree-ids");if(e){const a=JSON.parse(e);Array.isArray(a)&&a.length>0&&(r=a)}}catch{}if(0===r.length){const e=a.dataTransfer.getData("text/plain");e&&(r=[e])}}0===r.length||r.includes(t)||G(r,t),H()},[G,H]),X=l(e=>{e.preventDefault(),e.stopPropagation();let a=B.current;if(0===a.length){try{const t=e.dataTransfer.getData("application/x-tree-ids");if(t){const e=JSON.parse(t);Array.isArray(e)&&e.length>0&&(a=e)}}catch{}if(0===a.length){const t=e.dataTransfer.getData("text/plain");t&&(a=[t])}}0!==a.length?(G(a,null),H()):H()},[G,H]),J=l(e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",F(!0)},[]),Z=l(e=>{S&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},[S]),ee=l(e=>{if(!S)return;const a=document.elementFromPoint(e.clientX,e.clientY)?.closest?.("[data-tree-row-id]"),t=a?.dataset?.treeRowId??$.current;t&&Q(t,e)},[S,Q]);if(b)return a("div",{className:"flex items-center justify-center py-12",children:t("div",{className:"text-center space-y-2",children:[a("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),a("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(!r||0===r.length)return t("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-2",children:[a(ge,{className:"h-10 w-10 text-muted-foreground/50"}),a("p",{className:"text-sm text-muted-foreground",children:x})]});const ae=null!==T;return t("div",{className:Fi("border rounded-lg overflow-hidden relative",y),onDragOver:Z,onDrop:ee,onDragLeave:S?e=>{const a=e.relatedTarget;a&&e.currentTarget.contains(a)||(L(null),F(!1))}:void 0,children:[S&&ae&&a(Mv,{onDrop:X,isDragOver:z,onDragOver:J,onDragLeave:()=>F(!1),label:D}),t(Pl,{children:[a(Il,{children:t(Ml,{children:[a(Ll,{className:"text-left",style:{minWidth:I},children:t("div",{className:"flex items-center gap-2",children:[N&&a(qo,{checked:k??!1,onCheckedChange:()=>C?.()}),d]})}),n.map(e=>a(Ll,{className:Fi("text-center",e.className),style:e.width?{width:e.width}:void 0,children:e.header},String(e.key))),f&&a(Ll,{className:"text-right",style:{width:P},children:g})]})}),a(Tl,{children:r.map(e=>a(Rv,{item:e,level:0,columns:n,nameKey:s,iconComponent:c,expandedIds:m,onToggleExpand:p,onRowClick:h,renderActions:f,rowActionsVariant:v,enableSelection:N,selectedIds:V,onSelectItem:_,enableRowDrag:S,draggedId:T,dragOverId:M,onDragStartCell:K,onDragEndCell:H,onDragOverCell:Y,onDropCell:Q,dragCount:U},e.id))})]})]})}function zv(e){const a=nt();return{onNew:()=>{const t=e.newPath||`${e.basePath}/new`;a(t)},onEdit:t=>{const r=e.editPath?e.editPath.replace(":id",t.id):`${e.basePath}/${t.id}/edit`;a(r)}}}function Fv(e,a){const t=zv({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Uv=[{value:"pt-BR",label:"Português (Brasil)"},{value:"en-US",label:"English (US)"},{value:"es-ES",label:"Español"}],jv=({open:e,onOpenChange:r,user:n,userPhotoUrl:i,userInitials:s})=>{const{t:l,i18n:d}=Ga(),c=u(null),[m,p]=o(null),[h,f]=o(d.language||"pt-BR"),g=m||i,v=e=>{e||(p(null),f(d.language||"pt-BR")),r(e)};return a(mo,{open:e,onOpenChange:v,children:t(bo,{className:"sm:max-w-md",children:[a(xo,{children:a(wo,{children:l("edit_profile","Editar Perfil")})}),t("div",{className:"space-y-6 py-4",children:[t("div",{className:"flex items-center gap-4",children:[a("div",{className:"relative flex-shrink-0",children:t(bu,{className:"w-24 h-24",children:[g&&a(xu,{src:g,alt:n.name||""}),a(yu,{className:"bg-primary text-primary-foreground font-semibold text-2xl",children:s})]})}),t("div",{className:"space-y-1",children:[n.name&&a("p",{className:"text-base font-semibold",children:n.name}),n.email&&a("p",{className:"text-sm text-muted-foreground",children:n.email}),t($i,{variant:"outline",size:"sm",onClick:()=>c.current?.click(),children:[a(ha,{className:"mr-2 h-4 w-4"}),l("change_photo","Trocar foto")]}),a("input",{ref:c,type:"file",accept:"image/*",className:"hidden",onChange:e=>{const a=e.target.files?.[0];if(!a)return;const t=URL.createObjectURL(a);p(t)}})]})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:l("language","Idioma")}),t(Mo,{value:h,onValueChange:f,children:[a(Fo,{children:a(zo,{})}),a(Oo,{children:Uv.map(e=>a($o,{value:e.value,children:e.label},e.value))})]})]})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>v(!1),children:l("cancel","Cancelar")}),a($i,{onClick:()=>{h!==d.language&&d.changeLanguage(h),r(!1)},children:l("save","Salvar")})]})]})})},Ov="true"===import.meta.env.VITE_SHOW_EDIT_PROFILE,Bv=i.memo(({variant:e="card",className:n="",selectedUnit:l,onUnitChange:d})=>{const{t:c}=Ga(),{user:u,companies:m,alias:p,isAuthenticated:h,logout:f,switchUnit:g}=kl(),{role:v}=au(),b=v?.name||null,x=m?.[0]||null,y=p?m?.find(e=>e.alias===p):x,N=m||[],w=l||y||x||x,_=s(()=>{if(!u?.id)return null;const e=(new Date).toISOString().slice(0,10);return`https://login-api.qualiex.com/api/Users/Photo/${u.id}/${e}/1?size=48`},[u?.id]),C=s(()=>{if(!u?.name)return"";const e=u.name.trim().split(/\s+/);return 1===e.length?e[0].charAt(0).toUpperCase():(e[0].charAt(0)+e[e.length-1].charAt(0)).toUpperCase()},[u?.name]),k=i.useCallback(e=>{d?d(e):g(e)},[d,g]),S=i.useMemo(()=>{if(!N?.length)return[];const e=new Map;N.forEach(a=>{e.set(a.alias,a)});const a=Array.from(e.values()),t=a.find(e=>e.alias===w?.alias),r=a.filter(e=>e.alias!==w?.alias);return r.sort((e,a)=>(e.name||"").localeCompare(a.name||"","pt-BR",{sensitivity:"base"})),t?[t,...r]:r},[N,w?.alias]),[A,E]=o(!1);if(!h||!u)return null;return"dropdown"===e?t(r,{children:[t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",className:`h-auto p-2 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10 ${n}`,children:t("div",{className:"flex items-center space-x-2",children:[t("div",{className:"hidden md:block text-right",children:[t("p",{className:"text-sm font-medium",children:[u.name?.split(" ")[0],b?` [${b}]`:""]}),a("p",{className:"text-xs text-primary-foreground/70",children:w?.name||"N/A"})]}),t(bu,{className:"w-8 h-8 border border-primary-foreground/30",children:[_&&a(xu,{src:_,alt:u.name||c("user_photo")}),a(yu,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:C||a(ge,{className:"h-4 w-4"})})]}),a(D,{className:"h-4 w-4"})]})})}),t(os,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[t(ts,{children:[t(ns,{children:[a(ue,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),a(is,{children:S.map(e=>t(ss,{onClick:()=>k(e),className:e.alias===w?.alias?"bg-muted":"",children:[a(fe,{className:"mr-2 h-4 w-4"}),e.name,e.alias===w?.alias&&a(Go,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},e.alias))})]}),Ov&&t(r,{children:[a(us,{}),t(ss,{onClick:()=>E(!0),children:[a(fa,{className:"mr-2 h-4 w-4"}),c("edit_profile","Editar Perfil")]})]}),a(us,{}),t(ss,{onClick:f,children:[a(ve,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}),Ov&&a(jv,{open:A,onOpenChange:E,user:u,userPhotoUrl:_,userInitials:C})]}):t(Gi,{className:n,children:[a(Ki,{children:a(Yi,{className:"text-lg",children:c("user_info")})}),t(Xi,{className:"space-y-4",children:[a(()=>t(r,{children:[t("div",{className:"flex items-center space-x-3",children:[a("div",{className:"flex-shrink-0",children:t(bu,{className:"w-10 h-10",children:[_&&a(xu,{src:_,alt:u.name||c("user_photo")}),a(yu,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:C||a(ge,{className:"h-5 w-5"})})]})}),t("div",{className:"flex-1 min-w-0",children:[a("p",{className:"text-sm font-medium truncate",children:u.name}),t("p",{className:"text-xs text-muted-foreground",children:["Unidade: ",w?.name||"N/A"]})]})]}),w&&a("div",{className:"mt-3",children:t("div",{className:"flex items-center space-x-2",children:[a(fe,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:w.name})]})}),S.length>1&&t("div",{className:"mt-2",children:[t("p",{className:"text-xs text-muted-foreground mb-1",children:["Unidades disponíveis: ",S.length]}),t("div",{className:"flex flex-wrap gap-1",children:[S.slice(0,3).map(e=>a(Go,{variant:e.alias===w?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>k(e),children:e.name},e.alias)),S.length>3&&t(Go,{variant:"outline",className:"text-xs",children:["+",S.length-3]})]})]})]}),{}),a(Zi,{}),t($i,{variant:"outline",onClick:f,size:"sm",className:"w-full",children:[a(ve,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),$v=d({});function Vv({children:e,config:t}){const r=s(()=>{const e=mr(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return a($v.Provider,{value:r,children:e})}function qv(){return c($v)}function Wv(){const e=it(),{navigation:a}=qv();return Hv(a,e.pathname)}function Hv(e,a){if(!e)return"";const t=e.find(e=>e.path===a);if(t)return t.label;const r=e.find(e=>a.startsWith(e.path+"/"));return r?.label||""}function Gv(e,a){const[t,r]=o(e),n=u(),i=l(()=>{n.current&&(clearTimeout(n.current),n.current=void 0)},[]);return m(()=>(i(),n.current=setTimeout(()=>{r(e)},a),i),[e,a,i]),[t,i]}function Kv({appName:e}){const[n,i]=o(!1);return t(r,{children:[t("div",{className:"flex items-center justify-between w-[258px]",children:[a("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>i(!0),children:a("img",{src:Sr.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),e&&a("button",{className:"min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground/80 hover:text-primary-foreground/60 transition-colors leading-tight py-1",onClick:()=>i(!0),children:a("span",{className:"line-clamp-2",children:(e=>{const n=e.split(" ");if(n.length<=1)return t("span",{className:"whitespace-nowrap",children:[e," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return t(r,{children:[o," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(e)})})]}),a(ru,{open:n,onOpenChange:i})]})}const Yv=p(function({actions:r}){const n=it(),i=nt(),{navigation:s,appName:d}=qv(),c=Hv(s,n.pathname),{metadata:u,headerActions:p}=cc(),{setOpenMobile:h}=Jm(),{companies:f,alias:g,isSearchVisible:v,clearSearch:b,refreshData:x,switchUnit:y}=kl(),N=g?f?.find(e=>e.alias===g)||f?.[0]||null:f?.[0]||null,[w,_]=tt(),C=l(e=>{const{pathname:a,search:t,hash:r}=n;if(g){const n=a.split("/"),o=n.indexOf(g);if(o>=0)return n[o]=e.alias,void i(n.join("/")+t+r)}y(e)},[g,n,i,y]),[k,S]=o(()=>w.get("search")||""),[A,D]=Gv(k,fr.debounceDelay);m(()=>{if(!v)return;const e=new URLSearchParams(w);A?(e.set("search",A),e.set("page","1")):e.delete("search"),_(e)},[A,_,v]);const P=s?.find(e=>e.path===n.pathname)||s?.find(e=>n.pathname.startsWith(e.path+"/")),I=u.title||c,T=u.subtitle||P?.complementaryText||"";return a("header",{className:"bg-primary border-b border-primary px-2 md:px-4 py-2",children:t("div",{className:"flex items-center gap-4",children:[a($i,{variant:"ghost",size:"sm",className:"md:hidden h-8 w-8 p-0 flex-shrink-0 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:()=>h(!0),children:a(ga,{size:20})}),a("div",{className:"hidden md:flex items-center flex-shrink-0",children:a(Kv,{appName:d})}),a("div",{className:"hidden md:block w-px h-8 bg-primary-foreground/20 flex-shrink-0"}),t("div",{className:"flex-shrink-0",children:[u.breadcrumbs&&u.breadcrumbs.length>0&&a("nav",{className:"flex items-center gap-1 text-xs text-primary-foreground/70 mb-0.5",children:u.breadcrumbs.map((e,r)=>t("span",{className:"flex items-center gap-1",children:[r>0&&a(U,{className:"h-3 w-3"}),e.href?a(st,{to:e.href,className:"hover:text-primary-foreground transition-colors",children:e.label}):a("span",{children:e.label})]},r))}),a("div",{className:"flex items-center gap-2 mb-1",children:a("h1",{className:"text-lg font-semibold text-primary-foreground truncate",children:I})}),T&&a("div",{className:"text-sm text-primary-foreground/70 truncate",children:T})]}),v&&t("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[t("div",{className:"relative flex-1",children:[a(B,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(qi,{placeholder:"Pesquisar",value:k,onChange:e=>{return a=e.target.value,void S(a);var a},className:"w-full pl-10 pr-8"}),k&&a($i,{variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 transform -translate-y-1/2 h-6 w-6 p-0 hover:bg-primary-foreground/10 text-primary-foreground/60",onClick:()=>{D(),S("");const e=new URLSearchParams(w);e.delete("search"),e.delete("page"),_(e)},title:e.t("clear_search"),children:a(E,{size:14})})]}),a($i,{variant:"outline",size:"sm",onClick:x,className:"flex-shrink-0 h-10 w-10 p-0 bg-primary-foreground/20 border-primary-foreground/30 text-primary-foreground hover:bg-primary-foreground/30 hover:text-primary-foreground",title:e.t("refresh_data"),children:a(ue,{size:14})})]}),t("div",{className:"flex-shrink-0 ml-auto flex items-center gap-3",children:[(p||r)&&a("div",{className:"flex items-center gap-2",children:p||r}),import.meta.env.VITE_WIKI_URL&&a($i,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>Li(import.meta.env.VITE_WIKI_URL,e),title:e.t("open_wiki"),children:"Wiki"}),a(xh,{}),a("div",{className:"text-sm",children:a(Bv,{variant:"dropdown",selectedUnit:N,onUnitChange:C})})]})]})})}),Qv=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>Ja({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function Xv({config:e,isCollapsed:n=!1,isDisabled:i=!1,className:o}){const{t:s}=Ga(),{actions:l,triggerLabel:d="Criar",triggerIcon:c=Q,variant:u="button"}=e;if(!l||0===l.length)return null;if("split-button"===u){const e=l[0],r=e.icon||c,s=l.slice(1).map(e=>({id:e.id,label:e.label,icon:e.icon,onClick:e.onClick,disabled:e.disabled}));if(n){const n=a($i,{onClick:e.onClick,disabled:i||e.disabled,className:Fi("justify-center px-2 w-full",o),variant:"outline",size:"default",children:a(r,{className:"h-4 w-4 shrink-0"})});return t(hs,{children:[a(fs,{asChild:!0,children:n}),a(gs,{side:"right",children:a("p",{children:e.label})})]})}return a(oh,{label:e.label,onClick:e.onClick,icon:r,actions:s,variant:"outline",disabled:i||e.disabled,className:Fi("w-full",o),menuAlign:"start"})}const m=(e,i,o=!1)=>t(r,{children:[e,!n&&i&&a("span",{className:"truncate",children:i}),!n&&o&&a(D,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(l.length>1)){const e=l[0],r=e.icon||c,s=i||e.disabled,d=a($i,{onClick:e.onClick,disabled:s,className:Fi("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:m(a(r,{className:"h-4 w-4 shrink-0"}),e.label)});return n?t(hs,{children:[a(fs,{asChild:!0,children:d}),a(gs,{side:"right",children:a("p",{children:e.label})})]}):d}const p=a($i,{disabled:i,className:Fi("w-full gap-2 justify-start",n&&"justify-center px-2",o),variant:"outline",size:"default",children:m(a(c,{className:"h-4 w-4 shrink-0"}),d,!0)});return t(Jo,{children:[a(Zo,{asChild:!0,children:n?t(hs,{children:[a(fs,{asChild:!0,children:p}),a(gs,{side:"right",children:a("p",{children:d})})]}):p}),a(os,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:l.map(e=>{const r=e.icon;return t(ss,{onClick:e.onClick,disabled:e.disabled,className:"cursor-pointer",children:[r&&a(r,{className:"mr-2 h-4 w-4"}),e.label]},e.id)})})]})}const Jv="forlogic-sidebar-pinned",Zv=()=>{try{const e=localStorage.getItem(Jv);return!!e&&JSON.parse(e)}catch{return!1}};function eb({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:i,isOpen:s=!0}={}){const[d,c]=o(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[p,h]=o(!1),f=u(null);m(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(s?e.style.setProperty("--sidebar-width",`${d}px`):e.style.setProperty("--sidebar-width","290px"))},[d,s]);const g=l(e=>{e.preventDefault(),h(!0)},[]);return m(()=>{if(!p)return;const r=r=>{let n;n="left"===e?window.innerWidth-r.clientX:r.clientX,n=Math.max(a,Math.min(t,n)),c(n),i?.(n)},o=()=>{h(!1),c(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",o),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",o)}},[p,e,a,t,d,n,i]),m(()=>(p?(document.body.style.cursor="ew-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[p,e]),{width:d,isDragging:p,dragRef:f,handleMouseDown:g}}const ab=d(void 0);function tb({children:e}){const[t,r]=o(new Set),[n,i]=o(!1),d=l(e=>{r(a=>{const t=new Set(a);return t.add(e),t})},[]),c=l(e=>{r(a=>{const t=new Set(a);return t.delete(e),t})},[]),u=l(e=>{i(e)},[]),m=s(()=>t.size>0||n,[t,n]),p=s(()=>({openModals:t,hasOpenModal:m,registerModal:d,unregisterModal:c,setHasOpenModal:u}),[t,m,d,c,u]);return a(ab.Provider,{value:p,children:e})}function rb(){const e=c(ab);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function nb(){const{hasOpenModal:e}=rb();return e}function ib({config:e,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:s=384}={}){const{t:d}=Ga(),{open:c,setOpen:u,setOpenMobile:p}=Jm(),h=it(),{alias:f,user:g}=kl(),{appName:v}=qv(),{hasOpenModal:b}=rb(),[x,y]=o(Zv),N=Dl(),w=!!N||c,_=l(()=>{N&&p(!1)},[N,p]),C=n?eb({minWidth:i,maxWidth:s,storageKey:"app-sidebar-width",isOpen:c}):null;m(()=>{u(!!x)},[x,u]);const k=e=>h.pathname===e||h.pathname.startsWith(e+"/");return t(ep,{collapsible:"icon",className:Fi("app-sidebar bg-background border-r border-border flex flex-col",w?"px-3":"px-1.5"),style:C&&w?{width:`${C.width}px`,transition:"none"}:{transition:"width 300ms ease-in-out"},children:[e?.moduleActions&&e.moduleActions.actions.length>0&&a("div",{className:"py-3",children:a(ps,{children:a(Xv,{config:e.moduleActions,isCollapsed:!w,isDisabled:b})})}),a(lp,{className:Fi(e?.moduleActions&&e.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||a(dp,{className:"p-0",children:a(mp,{children:a(pp,{className:"gap-1",children:a(ps,{children:e?.navigation?.map((e,r)=>{if("separator"===e.type)return a(sp,{className:"my-2"},`sep-${r}`);const n=({item:e,index:r})=>{const i=`${e.path}-${r}-${f??"noalias"}-${g?.id??"nouser"}`,{data:o=!0,isLoading:s}=Qv({key:i,enabled:Boolean(e.permissionCheck&&f&&g?.id),checkFn:e.permissionCheck||(()=>Promise.resolve(!0))}),l=e.permissionCheck&&!o,c=s?T:l?He:e.icon;l?d("restricted_access"):e.complementaryText;return e.children&&e.children.length>0?w?a(Sc,{defaultOpen:!0,className:"group/collapsible",children:t(hp,{children:[a(Ac,{asChild:!0,children:a(gp,{size:"default",children:t("div",{className:"flex w-full items-center gap-3",children:[a("span",{className:"flex items-center justify-center h-8 w-8",children:a(c,{className:"h-4 w-4"})}),a("span",{className:"font-medium sidebar-text",children:e.label}),a(U,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),a(Ec,{children:a(yp,{children:e.children.map((e,t)=>a(n,{item:e,index:t},e.path))})})]})},e.path):a(hp,{children:t(hs,{children:[a(fs,{asChild:!0,children:a("div",{className:Fi("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors cursor-pointer","hover:bg-accent hover:text-accent-foreground"),children:a(c,{className:"h-4 w-4"})})}),a(gs,{side:"right",children:a("p",{children:e.label})})]})},e.path):a(hp,{children:l||s?t(hs,{children:[a(fs,{asChild:!0,children:w?a(gp,{size:"default",className:"opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:t("div",{className:"flex w-full items-center gap-3",children:[a("span",{className:"flex items-center justify-center h-8 w-8",children:a(c,{className:"h-4 w-4 "+(s?"animate-spin":"")})}),a("span",{className:"font-medium sidebar-text",children:e.label})]})}):a("div",{className:"flex items-center justify-center h-8 w-8 mx-auto rounded-md opacity-50 cursor-not-allowed",onClick:e=>e.preventDefault(),children:a(c,{className:"h-4 w-4 "+(s?"animate-spin":"")})})}),a(gs,{side:"right",children:a("p",{children:s?"Verificando acesso...":d("restricted_access")})})]}):w?a(gp,{asChild:!0,isActive:k(e.path),size:"default",children:t(st,{to:e.path,className:"flex w-full items-center gap-3",onClick:_,children:[a("span",{className:"flex items-center justify-center h-8 w-8",children:a(c,{className:"h-4 w-4"})}),a("span",{className:"font-medium sidebar-text",children:e.label})]})}):t(hs,{children:[a(fs,{asChild:!0,children:a(st,{to:e.path,onClick:_,className:Fi("flex items-center justify-center h-8 w-8 mx-auto rounded-md transition-colors",k(e.path)?"bg-primary/10 text-primary":"hover:bg-accent hover:text-accent-foreground"),children:a(c,{className:"h-4 w-4"})})}),a(gs,{side:"right",children:a("p",{children:e.label})})]})},e.path)};return a(n,{item:e,index:r},e.path)})})})})})}),!N&&a("div",{className:Fi("mt-auto pb-4 pt-2 flex",c?"justify-end":"justify-center"),children:t(hs,{children:[a(fs,{asChild:!0,children:a("button",{id:"btn-expand-side-nav",onClick:()=>{const e=!x;y(e),(e=>{try{localStorage.setItem(Jv,JSON.stringify(e))}catch{}})(e)},className:"h-6 w-6 flex items-center justify-center rounded-full bg-primary hover:bg-primary/90 shadow-md transition-colors",children:a(c?oe:U,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),a(gs,{side:"right",children:a("p",{children:c?"Recolher":"Expandir"})})]})}),n&&C&&w&&a("div",{ref:C.dragRef,onMouseDown:C.handleMouseDown,className:Fi("absolute inset-y-0 right-0 w-1 cursor-ew-resize","hover:bg-primary/20 transition-colors","after:absolute after:inset-y-0 after:-left-1 after:-right-1 after:content-['']",C.isDragging&&"bg-primary/40")})]})}const ob=p(function({children:e,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const o=s(()=>r||a(ib,{config:n}),[r,n]),d=s(()=>({"--sidebar-width":"290px","--sidebar-width-icon":"58px"}),[]),c=u(null),p=u(null),h=l(()=>{if(c.current&&p.current){const e=c.current.offsetHeight;p.current.style.setProperty("--header-height",`${e}px`)}},[]);return m(()=>{h();const e=new ResizeObserver(h);return c.current&&e.observe(c.current),()=>e.disconnect()},[h]),a(Vv,{config:n,children:a(dc,{children:a(Zm,{defaultOpen:!1,style:d,children:t("div",{ref:p,className:"flex flex-col h-screen w-full overflow-hidden",children:[i&&a("div",{ref:c,className:"flex-shrink-0 sticky top-0 z-40 bg-primary",children:a(Yv,{})}),t("div",{className:"sidebar-container flex flex-1 overflow-hidden",children:[o,a("main",{className:"relative z-0 flex-1 flex flex-col overflow-hidden",children:a("div",{className:"flex-1 min-h-0 overflow-y-auto bg-muted/30",children:e})})]})]})})})})});function sb({open:e,appName:n}){const[i,s]=o(!1);return t(r,{children:[a(ip,{className:"p-0 gap-0",children:e?t("div",{className:"flex items-center gap-2 pl-2 min-h-10",children:[a("button",{className:"flex-shrink-0 cursor-pointer",onClick:()=>s(!0),children:a("img",{src:Sr.logo,alt:"Logo",className:"h-8 max-w-[140px] object-contain"})}),n&&a("button",{className:"flex-1 min-w-0 text-sm font-medium text-right cursor-pointer text-primary-foreground hover:text-primary-foreground/80 transition-colors leading-tight py-1",onClick:()=>s(!0),children:a("span",{className:"line-clamp-2",children:(e=>{const n=e.split(" ");if(n.length<=1)return t("span",{className:"whitespace-nowrap",children:[e," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],o=n.slice(0,-1).join(" ");return t(r,{children:[o," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(D,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(n)})})]}):a("div",{className:"flex flex-col items-center justify-center w-full",children:a("button",{className:"flex items-center justify-center h-10 w-8 cursor-pointer",onClick:()=>s(!0),children:a("img",{src:Sr.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),a(ru,{open:i,onOpenChange:s})]})}function lb({title:e,subtitle:r,children:n,className:i,hasHeader:o=!0}){const s=e||r;return t("div",{className:Fi("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",i),children:[o&&s&&t("div",{className:"px-6 py-4 border-b border-border/50",children:[e&&a("h2",{className:"text-xl font-semibold text-foreground",children:e}),r&&a("p",{className:"text-sm text-muted-foreground mt-0.5",children:r})]}),n&&a("div",{className:Fi("p-6",!o&&s&&"pt-4"),children:n})]})}function db({breadcrumbs:e,children:r,className:i}){return t("div",{className:Fi("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[e&&e.length>0&&a(Nu,{className:"mb-4",children:a(wu,{children:e.map((r,i)=>{const o=i===e.length-1;return t(n.Fragment,{children:[i>0&&a(Su,{}),a(_u,{children:o||!r.href?a(ku,{children:r.label}):r.asChild&&r.children?a(Cu,{asChild:!0,children:r.children}):a(Cu,{asChild:!0,children:a(st,{to:r.href||"/",children:r.label})})})]},`${r.label}-${i}`)})})}),a("div",{className:"space-y-6",children:r})]})}const cb=(e={})=>{const{enabled:a=!0}=e,{alias:t}=kl();return Ja({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=rl(),{data:a,error:r}=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(r){if(!ol.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function ub({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:s=!0}){const[d,c]=o(()=>{if(!s||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[p,h]=o(!1),[f,g]=o(null),v=u(0),b=u(0),x=l(e=>d[e]??a,[d,a]),y=l((e,t)=>{s&&(t.preventDefault(),t.stopPropagation(),h(!0),g(e),v.current=t.clientY,b.current=d[e]??a)},[s,d,a]);m(()=>{if(!p||!f)return;const e=e=>{const a=e.clientY-v.current,n=Math.max(t,Math.min(r,b.current+a));c(e=>{const a={...e,[f]:n};return i?.(a),a})},a=()=>{h(!1),g(null),n&&c(e=>(localStorage.setItem(n,JSON.stringify(e)),e))};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",a),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",a)}},[p,f,t,r,n,i]),m(()=>(p?(document.body.style.cursor="row-resize",document.body.style.userSelect="none"):(document.body.style.cursor="",document.body.style.userSelect=""),()=>{document.body.style.cursor="",document.body.style.userSelect=""}),[p]);const N=l(()=>{c({}),n&&localStorage.removeItem(n),i?.({})},[n,i]);return{rowHeights:d,isDragging:p,activeRow:f,handleMouseDown:y,resetHeights:N,getRowHeight:x}}function mb(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:i}=e,[d,c]=o(t),[u,m]=o(r),[p,h]=o(!1),[f,g]=o(!1),v=a.length,b=0===d,x=d===v-1,y=a[d],N=v>1?(d+1)/v*100:100,w=l(()=>!y?.canProceed||y.canProceed(),[y]),_=s(()=>w(),[w,u]),C=s(()=>!b&&!y?.disableBack,[b,y]),k=l(e=>{m(a=>({...a,...e}))},[]),S=l((e,a)=>{m(t=>({...t,[e]:a}))},[]),A=l(()=>{c(t),m(r),h(!1),g(!1),i?.()},[t,r,i]),E=l(async()=>{if(w()&&!f){g(!0);try{await(n?.(u))}finally{g(!1)}}},[w,f,u,n]),D=l(async()=>{w()&&!p&&(x?await E():c(e=>Math.min(e+1,v-1)))},[w,p,x,v,E]),P=l(()=>{C&&!p&&c(e=>Math.max(e-1,0))},[C,p]),I=l(e=>{e<0||e>=v||p||(e<=d||e===d+1)&&c(e)},[d,v,p]),T=l(e=>{h(e)},[]);return{currentStep:d,currentStepConfig:y,data:u,isFirstStep:b,isLastStep:x,isLoading:p,isCompleting:f,next:D,back:P,goTo:I,canProceed:_,canGoBack:C,setData:k,updateField:S,reset:A,complete:E,setLoading:T,progress:N,stepIndex:d,totalSteps:v}}function pb(...e){return Object.assign({},...e)}const hb=()=>{const{locale:e,timezone:a}=wc(),t=fi;return{formatDatetime:r=>Ei(r,t,a,e),formatDate:t=>Di(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class fb{static async sendEmail(e){const a=rl(),{data:t,error:r}=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(r)throw r;return t}}const gb=fb;function vb({open:e,onOpenChange:r,placeId:n,placeName:i,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const{t:m}=Ga(),[p,h]=o([]),[f,g]=o(!1),[v,b]=o(""),{data:x=[],isLoading:y}=Ld({enabled:e}),N=s(()=>{let e=[...x];if(e.sort((e,a)=>{const t=e.userName?.toLowerCase()||"",r=a.userName?.toLowerCase()||"";return t.localeCompare(r)}),v){const a=v.toLowerCase();e=e.filter(e=>e.userName?.toLowerCase().includes(a)||e.userEmail?.toLowerCase().includes(a))}return e},[x,v]),w=e=>{h(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},_=1===p.length,C=p.length>0;return a(mo,{open:e,onOpenChange:r,children:t(bo,{className:"max-w-2xl",variant:"form",children:[a(xo,{showSeparator:!0,children:t(wo,{className:"flex items-center gap-2",children:[a(Ze,{className:"h-5 w-5"}),"Gerenciar Acessos - ",i]})}),t(yo,{children:[t("div",{className:"relative mb-4",children:[a(B,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(qi,{placeholder:"Pesquisar...",value:v,onChange:e=>b(e.target.value),className:"pl-9"})]}),a(Dd,{className:"h-[400px] pr-4",children:y?a("div",{className:"space-y-2",children:[...Array(5)].map((e,t)=>a(Ps,{className:"h-16 w-full"},t))}):0===N.length?t("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[a(Ze,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),a("p",{className:"text-sm text-muted-foreground",children:m(v?"leadership_no_users_found":"leadership_no_users_available")})]}):a("div",{className:"space-y-2",children:N.map(e=>{const r=e.userId===c,n=u.includes(e.userId||""),i=p.includes(e.userId||"");return t("div",{className:Fi("flex items-center gap-3 p-3 rounded-lg border transition-colors",i&&"bg-accent border-primary","hover:bg-accent/50 cursor-pointer"),onClick:()=>w(e.userId||""),children:[a(qo,{checked:i,onCheckedChange:()=>w(e.userId||""),onClick:e=>e.stopPropagation()}),t("div",{className:"flex-1",children:[t("div",{className:"flex items-center gap-2",children:[a("p",{className:"font-medium",children:e.userName}),r&&a(va,{className:"h-4 w-4 text-yellow-500"})]}),a("p",{className:"text-sm text-muted-foreground",children:e.userEmail})]}),(r||n)&&a("div",{className:"text-xs text-muted-foreground",children:r?"Gestor":"Membro"})]},e.userId)})})})]}),t(No,{className:"flex gap-2 sm:gap-2",children:[a("div",{className:"flex-1 text-sm text-muted-foreground",children:p.length>0&&t("span",{children:[p.length," selecionado(s)"]})}),_&&l&&t($i,{onClick:async()=>{if(l&&1===p.length){g(!0);try{await l(p[0],n),h([])}finally{g(!1)}}},disabled:f,variant:"outline",children:[a(va,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&t($i,{onClick:async()=>{if(d&&0!==p.length){g(!0);try{await d(p,n),h([])}finally{g(!1)}}},disabled:f,children:[a(ba,{className:"h-4 w-4 mr-2"}),"Tornar ",p.length>1?"Membros":"Membro"]})]})]})})}function bb({place:e,level:r=0,manageAccessConfig:n}){const{t:i}=Ga(),[s,l]=o(!1),[d,c]=o(!1),u=e.subPlaces&&e.subPlaces.length>0,m=e.isActive??!0,p=e.usersCount??0;return t("div",{children:[t(Sc,{open:s,onOpenChange:l,children:[t("div",{className:"flex items-center gap-2 py-3 px-4 hover:bg-accent/50 transition-colors",style:{paddingLeft:2*r+1+"rem"},children:[u?t(Ac,{className:"flex items-center gap-2 flex-1",children:[a(U,{className:Fi("h-4 w-4 transition-transform shrink-0",s&&"rotate-90")}),a(fe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"font-medium",children:e.name}),t("span",{className:"text-sm text-muted-foreground",children:["(",e.subPlaces.length,")"]})]}):t("div",{className:"flex items-center gap-2 flex-1",children:[a("div",{className:"w-4 shrink-0"}),a(fe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"font-medium",children:e.name})]}),t("div",{className:"flex items-center gap-3 ml-auto",children:[t("div",{className:"flex items-center gap-1.5",children:[a(Ze,{className:"h-3.5 w-3.5 text-muted-foreground"}),a("span",{className:"text-sm text-muted-foreground",children:p})]}),a(Go,{variant:m?"default":"secondary",className:"text-xs",children:m?"Ativo":"Inativo"}),n&&a(Dv,{customActions:[{label:i("manage_access"),icon:xa,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),u&&a(Ec,{children:e.subPlaces.map(e=>a(bb,{place:e,level:r+1,manageAccessConfig:n},e.id))})]}),0===r&&a(Zi,{}),n&&a(vb,{open:d,onOpenChange:c,placeId:e.id,placeName:e.name,onMakeManager:n.onMakeManager,onMakeMembers:n.onMakeMembers,currentManagerId:n.getCurrentManagerId?.(e.id),currentMemberIds:n.getCurrentMemberIds?.(e.id)})]})}function xb({places:e,isLoading:r,manageAccessConfig:n}){return r?a("div",{className:"flex items-center justify-center py-12",children:t("div",{className:"text-center space-y-2",children:[a("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),a("p",{className:"text-sm text-muted-foreground",children:"Carregando dados..."})]})}):e&&0!==e.length?t("div",{className:"space-y-1",children:[a("h2",{className:"text-xl font-bold mb-4",children:"Estrutura de Locais"}),e.map(e=>a(bb,{place:e,manageAccessConfig:n},e.id))]}):t("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-3",children:[a(fe,{className:"h-12 w-12 text-muted-foreground/50"}),t("div",{children:[a("h3",{className:"font-semibold text-lg",children:"Nenhum local encontrado"}),a("p",{className:"text-sm text-muted-foreground",children:"Não há locais cadastrados para esta unidade."})]})]})}const yb=new class{get baseUrl(){return xr()}async makeApiCall(e,a,t){const r=sl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Ys.getAccessToken();if(!n)throw new Error("Token Qualiex não encontrado");if(!t||""===t.trim())throw new Error("Alias da unidade é obrigatório");const i=new URL(e,this.baseUrl);Object.entries(a).forEach(([e,a])=>{i.searchParams.append(e,a)});const o=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!o.ok){const e=new Error(`API call failed: ${o.status}`);throw e.status=o.status,e}return o.json()}buildHierarchy(e){const a=new Map,t=[];return e.forEach(e=>{a.set(e.id,{...e,subPlaces:[]})}),e.forEach(e=>{const r=a.get(e.id);if(e.parentId){const n=a.get(e.parentId);n?(n.subPlaces=n.subPlaces||[],n.subPlaces.push(r)):t.push(r)}else t.push(r)}),t}async getPlaces(e,a){try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(t){if(await sl.handleApiError(t))try{const t=await this.makeApiCall("/api/common/v1/places",{companyId:a},e),r=t.data||t||[];return this.buildHierarchy(r)}catch(r){return Qs.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return Qs.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Nb(e,a){const t=e.map(e=>({...e})),r=new Set(t.filter(e=>!a.has(e.id_user)).map(e=>e.id_user));return t.forEach(e=>{if(e.id_leader&&r.has(e.id_leader)){let a=e.id_leader;for(;a&&r.has(a);){const e=t.find(e=>e.id_user===a);a=e?.id_leader||null}e.id_leader=a}}),t.filter(e=>a.has(e.id_user))}function wb(e){const a=new Map,t=new Map,r=[];e.forEach(e=>{const r={...e,children:[],level:0};a.set(e.id,r),t.set(e.id_user,r)}),e.forEach(e=>{const n=a.get(e.id);if(e.id_leader){const a=t.get(e.id_leader);if(a)return void a.children.push(n)}r.push(n)});const n=(e,a)=>{e.level=a,e.children.forEach(e=>n(e,a+1))};r.forEach(e=>n(e,0));const i=e=>{e.sort((e,a)=>{const t=e.name||e.id_user||e.email||"",r=a.name||a.id_user||a.email||"";return t.localeCompare(r)}),e.forEach(e=>e.children.length>0&&i(e.children))};return i(r),r}function _b(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function Cb(){const{alias:a,isAuthenticated:t}=kl(),r=Ys.getAccessToken(),{data:n=[]}=Ld(),i=Ja({queryKey:["leadership-raw",a],queryFn:async()=>{if(!r||!a)throw new Error("Usuário não autenticado ou unidade não selecionada");const e=rl(),{data:t,error:n}=await e.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",a);if(n)throw new Error("Erro ao buscar hierarquia de liderança");return t??[]},enabled:!!r&&!!a&&t}),o=s(()=>{const a=i.data;if(!a)return;if(0===a.length)return[];const t={};n.forEach(e=>{t[e.userId]={name:e.userName||e.userEmail,email:e.userEmail||""}});const r=a.map(r=>{const n=a.filter(e=>e.id_leader===r.id_user);return{...r,name:t[r.id_user]?.name||e.t("inactive_user"),email:t[r.id_user]?.email||"",subordinatesCount:n.length,subordinateNames:n.map(e=>t[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))}}),o=new Set(a.map(e=>e.id_user));return new Set(a.filter(e=>e.id_leader&&!o.has(e.id_leader)).map(e=>e.id_leader)).forEach(n=>{const i=t[n],o=a.filter(e=>e.id_leader===n);r.push({id:`virtual-${n}`,alias:a[0]?.alias||"",id_user:n,id_leader:null,is_removed:!1,is_active:!0,created_at:(new Date).toISOString(),updated_at:(new Date).toISOString(),name:i?.name||e.t("inactive_user"),email:i?.email||"",subordinatesCount:o.length,subordinateNames:o.map(e=>t[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),wb(r)},[i.data,n]);return{...i,data:o}}import.meta.env.VITE_SUPABASE_URL,Js();const kb="common";function Sb(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(a.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Ib(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(kb).from("leaders").insert({alias:e,id_user:a.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1}).select().single();if(i)throw i;return n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_promoted_success","Líder virtual promovido com sucesso"))},onError:e=>{C.error(e.message||r("leader_create_error","Erro ao criar líder"))}})}function Ab(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));if(!a.users.length)throw new Error(r("select_at_least_one",r("leadership_select_subordinates")));const n=a.users.map(e=>e.id_user),{data:i}=await t.schema(kb).from("leaders").select("id_user").eq("alias",e).in("id_user",n).eq("is_removed",!1);if(i&&i.length>0){const e=i.map(e=>e.id_user);throw new Error(r("users_already_leaders",`Alguns usuários já estão cadastrados como líderes: ${e.join(", ")}`))}for(const d of a.users){if(a.id_leader&&d.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Ib(t,e,d.id_user,a.id_leader)}const o=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:s,error:l}=await t.schema(kb).from("leaders").insert(o).select();if(l)throw l;return s},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_added_success",`${t?.length||0} liderado(s) adicionado(s) com sucesso`))},onError:e=>{C.error(e.message||r("subordinates_add_error","Erro ao adicionar liderados"))}})}function Eb(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(kb).from("leaders").select("id_user").eq("id",a.id).eq("alias",e).single();if(!n)throw new Error(r("leader_not_found","Líder não encontrado"));if(n.id_user===a.id_leader)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));a.id_leader&&await Ib(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:o}=await t.schema(kb).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(o)throw o;return i},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_updated_success","Líder atualizado com sucesso"))},onError:e=>{C.error(e.message||r("leader_update_error","Erro ao atualizar líder"))}})}function Db(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(kb).from("leaders").update({is_removed:!0}).eq("id",a).eq("alias",e);if(n)throw n},onSuccess:()=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("leader_removed_success","Líder removido com sucesso"))},onError:e=>{C.error(e.message||r("leader_remove_error","Erro ao remover líder"))}})}function Pb(){const{alias:e}=kl(),a=Xa(),t=rl(),{t:r}=Ga();return Za({mutationFn:async({leaderUserId:a,selectedUsers:n})=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const i=n.map(e=>e.id_user),o=await Promise.all([t.schema(kb).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(kb).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:s,error:l},{data:d,error:c}]=o;if(l)throw l;if(c)throw c;const u=s||[],m=d||[],p=new Set(i),h=u.filter(e=>!p.has(e.id_user)),f=m.filter(e=>e.id_leader!==a),g=new Set(m.map(e=>e.id_user)),v=n.filter(e=>!g.has(e.id_user));for(const r of f)await Ib(t,e,r.id_user,a,r.id);for(const y of v){if(y.id_user===a)throw new Error(r("cannot_be_own_leader","Usuário não pode ser seu próprio líder"));await Ib(t,e,y.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(t.schema(kb).from("leaders").update({is_removed:!0}).in("id",a).eq("alias",e))}if(f.length){const r=f.map(e=>e.id);b.push(t.schema(kb).from("leaders").update({id_leader:a}).in("id",r).eq("alias",e))}if(v.length){const r=v.map(t=>({alias:e,id_user:t.id_user,id_leader:a,is_active:!0,is_removed:!1}));b.push(t.schema(kb).from("leaders").insert(r))}const x=(await Promise.all(b)).find(e=>e?.error);if(x?.error)throw x.error;return{unlinked:h.length,updated:f.length,created:v.length}},onSuccess:t=>{a.invalidateQueries({queryKey:["leadership",e]}),C.success(r("subordinates_synced_success",`Subordinados sincronizados (${t.created} adicionados, ${t.updated} atualizados, ${t.unlinked} removidos)`))},onError:e=>{C.error(e.message||r("subordinates_sync_error","Erro ao sincronizar subordinados"))}})}async function Ib(a,t,r,n,i){const{data:o,error:s}=await a.schema(kb).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(s)throw s;const l=i?o.filter(e=>e.id!==i):o,d=new Set;let c=n;for(;c;){if(d.has(c))throw new Error(e.t("leadership_cycle_error"));if(c===r)throw new Error("Esta associação criaria um ciclo na hierarquia");d.add(c);const a=l.find(e=>e.id_user===c);c=a?.id_leader||null}}var Tb=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,o=r.path.join(".");if(!t[o])if("unionErrors"in r){var s=r.unionErrors[0].errors[0];t[o]={message:s.message,type:s.code}}else t[o]={message:i,type:n};if("unionErrors"in r&&r.unionErrors.forEach(function(a){return a.errors.forEach(function(a){return e.push(a)})}),a){var l=t[o].types,d=l&&l[r.code];t[o]=Oa(o,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},Rb=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,o){try{var s=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&or({},i),{errors:{},values:t.raw?r:e}})}catch(l){return o(l)}return s&&s.then?s.then(void 0,o):s}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:sr(Tb(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(o){return Promise.reject(o)}}};const Mb=ir.object({id_leader:ir.string().nullable(),id_users:ir.array(ir.string()).min(1,e.t("leadership_select_subordinates"))}),Lb=ir.object({id_leader:ir.string().nullable(),id_users:ir.array(ir.string())});function zb({value:r,onChange:n,excludeUserIds:i=[],error:s}){const{data:l=[],isLoading:d}=Ld(),[c,p]=o(""),h=u(null),f=u(0),g=l.filter(e=>!i.includes(e.userId||"")).filter(e=>{const a=c.toLowerCase(),t=e.userName?.toLowerCase().includes(a);return t}).sort((e,a)=>{const t=r.includes(e.userId),n=r.includes(a.userId);if(t&&!n)return-1;if(!t&&n)return 1;const i=e.userName||e.userEmail||"",o=a.userName||a.userEmail||"";return i.localeCompare(o)});return m(()=>{h.current&&f.current>0&&(h.current.scrollTop=f.current)},[g]),t("div",d?{className:"flex items-center justify-center p-4",children:[a(T,{className:"h-6 w-6 animate-spin"}),a("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[a(qi,{placeholder:e.t("search_user_placeholder"),value:c,onChange:e=>p(e.target.value)}),a("div",{ref:h,className:"border rounded-md p-4 max-h-[300px] overflow-y-auto",children:0===g.length?a("p",{className:"text-sm text-muted-foreground",children:e.t("search_user_placeholder")}):a("div",{className:"space-y-2",children:g.map(e=>t("div",{className:"flex items-center space-x-2",children:[a(qo,{id:e.userId,checked:r.includes(e.userId),onCheckedChange:()=>{return a=e.userId,h.current&&(f.current=h.current.scrollTop),void(r.includes(a)?n(r.filter(e=>e!==a)):n([...r,a]));var a}}),a(Hi,{htmlFor:e.userId,className:"flex-1 cursor-pointer",children:e.userName||e.userEmail})]},e.userId))})}),r.length>0&&t("p",{className:"text-sm text-muted-foreground",children:[r.length," selecionado(s)"]}),s&&a("p",{className:"text-sm text-destructive",children:s})]})}function Fb({leader:n,prefilledLeaderId:i,onSuccess:s}){const{t:l}=Ga(),{alias:d}=kl(),c=!!n,u=n?.id.startsWith("virtual-"),p=Ab(),h=Sb(),f=Eb(),g=Pb(),v=Db(),{data:b=[]}=Cb(),{data:x=[]}=Ld(),[y,N]=o(""),w=_b(b).map(e=>e.id_user),_=c?_b(b).filter(e=>e.id_leader===n.id_user).map(e=>e.id_user):[],C=Ba({resolver:Rb(c?Lb:Mb),defaultValues:{id_leader:i||(c?n?.id_leader:null)||null,id_users:c?_:[]}});m(()=>{if(n){const e=_b(b).filter(e=>e.id_leader===n.id_user).map(e=>e.id_user);C.reset({id_leader:n.id_leader||null,id_users:e})}else i?C.reset({id_leader:i,id_users:[]}):C.reset({id_leader:null,id_users:[]})},[d,n?.id,n?.id_user,n?.id_leader,i,b]);const k=p.isPending||h.isPending||f.isPending||g.isPending||v.isPending,S=C.watch("id_leader"),A=C.watch("id_users"),E=c?[n.id_user,...w.filter(e=>e!==n.id_user&&!A.includes(e)&&!_.includes(e))]:[S,...w.filter(e=>!A.includes(e))].filter(Boolean);return t("form",{onSubmit:C.handleSubmit(async e=>{try{if(c)if(u){await h.mutateAsync({id_user:n.id_user,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await g.mutateAsync({leaderUserId:n.id_user,selectedUsers:a})}else{await f.mutateAsync({id:n.id,id_leader:e.id_leader});const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await g.mutateAsync({leaderUserId:n.id_user,selectedUsers:a})}else{const a=x.filter(a=>e.id_users.includes(a.userId)).map(e=>({id_user:e.userId}));await p.mutateAsync({id_leader:e.id_leader,users:a})}s?.()}catch(a){}}),className:"space-y-4",children:[c&&t("div",{children:[a(Hi,{children:e.t("leader")}),a(qi,{value:x.find(e=>e.userId===n.id_user)?.userName||n.name||e.t("inactive_user"),disabled:!0,className:"bg-muted"})]}),t("div",{children:[a(Hi,{children:l("leadership_immediate_superior")}),t(Mo,{value:S||"none",onValueChange:e=>C.setValue("id_leader","none"===e?null:e),children:[a(Fo,{children:a(zo,{placeholder:"Selecione..."})}),t(Oo,{children:[a("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:a(qi,{placeholder:"Buscar superior...",value:y,onChange:e=>N(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),t(Dd,{className:"h-[200px]",children:[a($o,{value:"none",children:"[Nenhum]"}),x.filter(e=>{const a=c?e.userId!==n.id_user:!A.includes(e.userId),t=!y||e.userName?.toLowerCase().includes(y.toLowerCase());return a&&t}).sort((e,a)=>{const t=e.userName||e.userEmail||"",r=a.userName||a.userEmail||"";return t.localeCompare(r)}).map(e=>a($o,{value:e.userId,children:e.userName},e.userId))]})]})]},`superior-select-${d}`),C.formState.errors.id_leader&&a("p",{className:"text-sm text-destructive mt-1",children:C.formState.errors.id_leader.message})]}),t("div",{children:[a(Hi,{children:"Subordinados *"}),a(zb,{value:A,onChange:e=>C.setValue("id_users",e),excludeUserIds:E,error:C.formState.errors.id_users?.message},`users-multiselect-${d}`)]}),t("div",{className:"flex items-center justify-between gap-2",children:[a($i,{type:"submit",disabled:k||!c&&0===A.length,children:k&&!v.isPending?t(r,{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),c?"Atualizando...":"Salvando..."]}):c?"Atualizar":"Criar"}),c&&!S&&0===A.length&&t(eo,{children:[a(ao,{asChild:!0,children:a($i,{type:"button",variant:"destructive",disabled:k,className:"ml-auto",children:v.isPending?t(r,{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):t(r,{children:[a(H,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),t(no,{children:[t(io,{children:[a(so,{children:l("confirm_removal")}),a(lo,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),t(oo,{children:[a(uo,{children:l("cancel")}),a(co,{onClick:async()=>{if(n)try{await v.mutateAsync(n.id),s?.()}catch(e){}},children:l("remove")})]})]})]})]})]})}function Ub({open:e,onOpenChange:r,leader:n,prefilledLeaderId:i,title:o}){return a(mo,{open:e,onOpenChange:r,children:t(bo,{variant:"form",className:"sm:max-w-[500px]",children:[a(xo,{showSeparator:!0,children:a(wo,{children:o})}),a(yo,{children:a(Fb,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const jb="leadership-expanded-nodes",Ob=(e,a)=>{try{localStorage.setItem(`${jb}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Bb({unassociatedUsers:n=[],onAssociateUser:i,onMoveNode:d,onMoveNodes:c,columns:u,nameHeader:p=e.t("leader"),rootDropLabel:h=e.t("leadership_make_root")}={}){const{alias:f}=kl(),{data:g,isLoading:v,error:b,refetch:x}=Cb(),y=Eb(),N=Sb(),[w,_]=o(()=>f?(e=>{try{const a=localStorage.getItem(`${jb}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(f):new Set),[C,k]=o([]),[S,A]=o(new Set),[E,P]=o(!0),[I,T]=o(!1),[R,M]=o(),[L,z]=o(null),F=s(()=>g?_b(g):[],[g]),j=s(()=>F.map(e=>e.id),[F]),O=j.length>0&&C.length===j.length,B=F.filter(e=>e.children.length>0).every(e=>w.has(e.id));m(()=>{if(g&&g.length>0&&f){if(!localStorage.getItem(`${jb}-${f}`)){const e=g.map(e=>e.id),a=new Set(e);_(a),Ob(f,a)}}},[g,f]);const $=l(e=>{_(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),f&&Ob(f,t),t})},[f]),V=l(()=>{if(B){const e=new Set;_(e),f&&Ob(f,e)}else{const e=new Set(F.filter(e=>e.children.length>0).map(e=>e.id));_(e),f&&Ob(f,e)}},[B,F,f]),q=l(e=>{k(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),W=l(()=>{k(O?[]:j)},[O,j]),H=l(e=>{A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),K=l(e=>F.find(a=>a.id===e),[F]),Y=l((e,a)=>{if(d)return void d(e,a);const t=n.find(a=>a.id===e);if(t){if(i){const e=a?K(a):null;i(t.id,e?.id_user||null)}else N.mutate({id_user:t.id,id_leader:a&&K(a)?.id_user||null});return}const r=K(e);if(!r)return;const o=a?K(a):null;y.mutate({id:r.id,id_leader:o?.id_user||null})},[d,n,i,K,y,N]),X=l((e,a)=>{c?c(e,a):(e.forEach(e=>Y(e,a)),k([]))},[c,Y]),J=l(e=>{M(e),z(null),T(!0)},[]),Z=l(()=>{M(void 0),z(null),T(!0)},[]),ee=l(()=>{T(!1),M(void 0),z(null)},[]),ae=l((e,a)=>{const t=S.has(e)&&S.size>1?Array.from(S):[e];a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t)),a.currentTarget.style.opacity="0.4"},[S]),te=s(()=>[{key:"subordinatesCount",header:"Subordinados",hoverContent:e=>e.subordinateNames&&e.subordinateNames.length>0?t("div",{className:"space-y-1.5",children:[a("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subordinados diretos:"}),[...e.subordinateNames].sort((e,a)=>e.localeCompare(a)).map(e=>t("div",{className:"flex items-center gap-2 text-sm",children:[a(ge,{className:"h-3 w-3 text-muted-foreground"}),a("span",{children:e})]},e))]}):a("p",{className:"text-xs text-muted-foreground",children:"Sem subordinados diretos"})},{key:"email",header:"Email",className:"text-left",width:180,render:e=>t("span",{className:"flex items-center gap-1.5 text-muted-foreground text-sm",children:[a(Ke,{className:"h-3.5 w-3.5"}),e.email||"—"]})}],[]),re=u??te;if(v)return a("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center space-y-2",children:[a("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full mx-auto"}),a("p",{className:"text-sm text-muted-foreground",children:"Carregando..."})]})});if(b)return a("div",{className:"flex items-center justify-center h-full",children:t("div",{className:"text-center",children:[a("p",{className:"text-destructive mb-4",children:"Erro ao carregar hierarquia de liderança"}),a($i,{onClick:()=>x(),children:e.t("try_again")})]})});const ne=F.filter(a=>a.name!==e.t("inactive_user")).length;return t("div",{className:"flex flex-col h-full gap-3 p-4",children:[t("div",{className:"flex items-center justify-between",children:[t("div",{className:"flex gap-2 items-center",children:[t($i,{size:"sm",onClick:Z,children:[a(Q,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a($i,{size:"sm",variant:"outline",onClick:V,children:t(r,B?{children:[a(D,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[a(U,{className:"h-4 w-4 mr-1"}),"Expandir"]})}),a("div",{className:"flex items-center gap-2 ml-4",children:t("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-muted rounded-md",children:[a(Ze,{className:"h-4 w-4 text-muted-foreground"}),t("span",{className:"text-sm font-medium",children:[ne," usuário",1!==ne?"s":""," associado",1!==ne?"s":""]})]})})]}),a("p",{className:"text-xs text-muted-foreground",children:"Arraste as linhas para reorganizar • Selecione múltiplos para mover em lote"})]}),a(Lv,{data:g||[],columns:re,nameKey:"name",nameHeader:p,expandedIds:w,onToggleExpand:$,iconComponent:a(Ze,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:q,onSelectAll:W,isAllSelected:O,onMoveNode:Y,onMoveNodes:X,rootDropLabel:h,emptyMessage:e.t("leadership_no_hierarchy"),renderActions:e=>a($i,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>J(e),children:a(G,{className:"h-4 w-4"})})}),n.length>0&&t("div",{className:"border rounded-lg overflow-hidden",children:[t("button",{type:"button",onClick:()=>P(e=>!e),className:"w-full px-4 py-2.5 bg-muted/50 border-b flex items-center gap-2 hover:bg-muted/70 transition-colors cursor-pointer",children:[a(E?D:U,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a(ba,{className:"h-4 w-4 text-muted-foreground"}),a("span",{className:"text-sm font-medium",children:"Usuários não associados"}),t("span",{className:"text-xs text-muted-foreground ml-1",children:["(",n.length,")"]}),S.size>0&&t("span",{className:"text-xs text-primary ml-1",children:["(",S.size," selecionado",S.size>1?"s":"",")"]}),a("span",{className:"text-xs text-muted-foreground ml-auto",children:"Arraste para a hierarquia acima"})]}),E&&a("div",{className:"divide-y",children:n.map(e=>t("div",{draggable:!0,onDragStart:a=>ae(e.id,a),onDragEnd:e=>{e.currentTarget.style.opacity="1"},className:Fi("flex items-center gap-3 px-4 py-2.5 hover:bg-accent/50 cursor-grab active:cursor-grabbing transition-colors",S.has(e.id)&&"bg-primary/5"),children:[a(qo,{checked:S.has(e.id),onCheckedChange:()=>H(e.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),a("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),a(ge,{className:"h-4 w-4 text-muted-foreground shrink-0"}),t("div",{className:"flex flex-col min-w-0",children:[a("span",{className:"text-sm truncate",children:e.name}),a("span",{className:"text-xs text-muted-foreground truncate",children:e.email})]})]},e.id))})]}),t("div",{className:"px-3 py-2 bg-muted/20 border rounded-lg text-xs text-muted-foreground flex justify-between",children:[t("span",{children:["Usuários associados: ",ne]}),n.length>0&&t("span",{children:["Usuários não associados: ",n.length]})]}),a(Ub,{open:I,onOpenChange:ee,leader:R,prefilledLeaderId:L,title:R?e.t("edit_name"):L?e.t("leadership_add_subordinate"):e.t("leadership_add_root")},`leadership-dialog-${f}`)]})}function $b(e){const[a,t]=o(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:i,onSuccess:s,onError:l}=e||{};return{upload:async(e,a)=>{if(!r){const e=new Error("uploadFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de upload não configurada. Verifique a documentação."}),e}t(!0);try{const t={...i,...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 n=await r(e,t);return C.success("Sucesso",{description:"Arquivo enviado com sucesso"}),s?.(n),n}catch(n){const e=n instanceof Error?n:new Error("Erro ao fazer upload");throw C.error("Erro",{description:e.message}),l?.(e),e}finally{t(!1)}},deleteMedia:async(e,a)=>{if(!n){const e=new Error("deleteFunction não fornecida");throw C.error("Erro de configuração",{description:"Função de delete não configurada."}),e}try{await n(e,a),C.success("Sucesso",{description:"Arquivo removido com sucesso"})}catch(t){throw C.error("Erro",{description:"Erro ao remover o arquivo"}),t}},uploading:a}}function Vb(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 qb(e,a){const t=Vb(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Wb(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function Hb(e,a){const t=Wb(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Gb(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function Kb(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Yb(e,a,t){switch(a||Kb(e)){case"youtube":return qb(e,t);case"vimeo":return Hb(e,t);default:return e}}function Qb({value:n,onChange:i,onSubmit:l,onCancel:d,uploadFunction:c,deleteFunction:m,uploadOptions:p}){const{t:h}=Ga(),[f,g]=o(n||{inputType:"url",controls:!0}),v=u(null),b=u(null),{upload:x,uploading:y}=$b({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["video/*"],maxSize:104857600}}),{upload:N,uploading:w}=$b({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["image/*"],maxSize:5242880}}),_=s(()=>Kb(f.videoUrl||Gb(f.embedCode)||""),[f.videoUrl,f.embedCode]),k=(e,a)=>{const t={...f,[e]:a};g(t),i(t)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:h("input_type")}),t(Mo,{value:f.inputType||"url",onValueChange:e=>k("inputType",e),children:[a(Fo,{children:a(zo,{})}),t(Oo,{children:[a($o,{value:"url",children:"URL"}),a($o,{value:"upload",children:h("file_upload")}),a($o,{value:"embed",children:h("embed_code")})]})]})]}),"upload"===f.inputType&&c&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Arquivo"}),t("div",{className:"flex gap-2",children:[a("input",{ref:v,type:"file",accept:"video/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await x(a),t={...f,videoUrl:e.url,videoFile:e.name,videoPath:e.path,videoSize:e.size,title:f.title||a.name.replace(/\.[^/.]+$/,"")};g(t),i(t)}catch(t){}finally{v.current&&(v.current.value="")}},className:"hidden"}),a($i,{type:"button",variant:"outline",onClick:()=>v.current?.click(),disabled:y,children:t(r,y?{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ya,{className:"mr-2 h-4 w-4"}),"Selecionar vídeo"]})}),f.videoFile&&t("span",{className:"text-xs text-muted-foreground truncate self-center",children:["Arquivo: ",f.videoFile," (",Math.round((f.videoSize||0)/1024/1024)," MB)"]})]})]}),"embed"===f.inputType&&t("div",{className:"space-y-2",children:[a(Hi,{children:h("embed_code")}),a(Wo,{placeholder:h("paste_embed_code"),value:f.embedCode||"",onChange:e=>k("embedCode",e.target.value),rows:4,className:"font-mono text-sm"})]}),c&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Thumbnail"}),t("div",{className:"flex gap-2",children:[a(qi,{type:"url",placeholder:"URL da thumbnail",value:f.thumbnail||"",onChange:e=>k("thumbnail",e.target.value),className:"flex-1"}),a("input",{ref:b,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await N(a),t={...f,thumbnail:e.url,thumbnailFile:e.name,thumbnailPath:e.path};g(t),i(t)}catch(t){}finally{b.current&&(b.current.value="")}},className:"hidden"}),a($i,{type:"button",variant:"outline",onClick:()=>b.current?.click(),disabled:w,children:t(r,w?{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ya,{className:"mr-2 h-4 w-4"}),"Upload"]})})]}),f.thumbnailFile&&t("p",{className:"text-xs text-muted-foreground",children:["Thumbnail: ",f.thumbnailFile]})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"title",children:"Título"}),a(qi,{id:"title",placeholder:h("video_title"),value:f.title||"",onChange:e=>k("title",e.target.value)})]}),t("div",{className:"flex gap-6",children:[t("div",{className:"flex items-center gap-2",children:[a(qo,{id:"autoplay",checked:f.autoplay||!1,onCheckedChange:e=>k("autoplay",!0===e)}),a(Hi,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),t("div",{className:"flex items-center gap-2",children:[a(qo,{id:"controls",checked:!1!==f.controls,onCheckedChange:e=>k("controls",!0===e)}),a(Hi,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:"Preview"}),a("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const r=f.videoUrl||Gb(f.embedCode)||"";if(!r)return a("div",{className:"text-center py-8 text-muted-foreground",children:"Nenhum conteúdo para visualizar"});if("file"===_)return t("video",{controls:!1!==f.controls,autoPlay:f.autoplay,poster:f.thumbnail,className:"w-full h-auto rounded-md",playsInline:!0,children:[a("source",{src:r}),"Seu navegador não suporta este vídeo."]});const n="youtube"===_?qb(r,f.autoplay):Hb(r,f.autoplay);return a("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:a("iframe",{title:f.title||e.t("video"),src:n,className:"absolute inset-0 w-full h-full rounded-md",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})()})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[a($i,{variant:"outline",onClick:d,children:"Cancelar"}),a($i,{onClick:()=>{f.videoUrl||f.embedCode?l(f):C.error("Erro",{description:h("no_video_selected")})},disabled:!(f.videoUrl||f.embedCode),children:"Salvar"})]})]})}function Xb({content:r,className:n="",style:i}){const o=r.videoUrl||Gb(r.embedCode)||"";if(!o)return null;const s=Kb(o);return a(Gi,{className:`overflow-hidden my-4 ${n}`,style:i,children:t(Xi,{className:"p-0",children:["file"===s?t("video",{controls:!1!==r.controls,autoPlay:r.autoplay,poster:r.thumbnail,className:"w-full h-auto",playsInline:!0,muted:r.autoplay,children:[a("source",{src:o}),"Seu navegador não suporta vídeos HTML5."]}):a("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:a("iframe",{title:r.title||e.t("video"),src:"youtube"===s?qb(o,r.autoplay):Hb(o,r.autoplay),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})}),r.title&&a("div",{className:"p-4",children:a("p",{className:"text-sm font-medium",children:r.title})})]})})}function Jb({value:e,onChange:n,onSubmit:i,onCancel:s,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const{t:m}=Ga(),[p,h]=o(e||{alignment:"center",allowDownload:!1}),f=u(null),{upload:g,uploading:v}=$b({uploadFunction:l,deleteFunction:d,defaultOptions:{...c,allowedTypes:["image/*"],maxSize:5242880}}),b=(e,a)=>{const t={...p,[e]:a};h(t),n(t)};return t("div",{className:"space-y-6",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:"URL"}),t("div",{className:"flex gap-2",children:[a(qi,{type:"url",placeholder:"https://exemplo.com/imagem.jpg",value:p.imageUrl||"",onChange:e=>b("imageUrl",e.target.value),className:"flex-1"}),l&&t(r,{children:[a("input",{ref:f,type:"file",accept:"image/*",onChange:async e=>{const a=e.target.files?.[0];if(a)try{const e=await g(a),t={...p,imageUrl:e.url,imageFile:e.name,imagePath:e.path,imageSize:e.size};h(t),n(t)}catch(t){}finally{f.current&&(f.current.value="")}},className:"hidden"}),a($i,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:t(r,v?{children:[a(T,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ya,{className:"mr-2 h-4 w-4"}),"Upload"]})})]})]}),p.imageFile&&t("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",p.imageFile," (",Math.round((p.imageSize||0)/1024)," KB)"]})]}),p.imageUrl&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Preview"}),a("div",{className:"border rounded-lg p-4 bg-muted/30",children:a("div",{className:"flex "+("left"===p.alignment?"justify-start":"right"===p.alignment?"justify-end":"justify-center"),children:a("img",{src:p.imageUrl,alt:p.alt||"Preview",style:{width:p.width?`${p.width}px`:"auto",height:p.height?`${p.height}px`:"auto",maxWidth:"100%"},className:"rounded-lg shadow-md"})})})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"caption",children:"Legenda"}),a(Wo,{id:"caption",placeholder:"Legenda",value:p.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"alt",children:m("alt_text")}),a(qi,{id:"alt",placeholder:m("alt_text"),value:p.alt||"",onChange:e=>b("alt",e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:"Alinhamento"}),t(Mo,{value:p.alignment||"center",onValueChange:e=>b("alignment",e),children:[a(Fo,{children:a(zo,{})}),t(Oo,{children:[a($o,{value:"left",children:"Esquerda"}),a($o,{value:"center",children:"Centro"}),a($o,{value:"right",children:"Direita"})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"width",children:"Largura"}),a(qi,{id:"width",type:"number",placeholder:"px",value:p.width||"",onChange:e=>b("width",e.target.value?Number(e.target.value):void 0)})]}),t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"height",children:"Altura"}),a(qi,{id:"height",type:"number",placeholder:"px",value:p.height||"",onChange:e=>b("height",e.target.value?Number(e.target.value):void 0)})]})]}),t("div",{className:"flex items-center gap-2",children:[a(qo,{id:"allowDownload",checked:p.allowDownload||!1,onCheckedChange:e=>b("allowDownload",!0===e)}),a(Hi,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[a($i,{variant:"outline",onClick:s,children:"Cancelar"}),a($i,{onClick:()=>{p.imageUrl?i(p):C.error("Erro",{description:m("no_image_selected")})},disabled:!p.imageUrl,children:"Salvar"})]})]})}function Zb({content:e,className:r="",style:n}){const{t:i}=Ga();if(!e.imageUrl)return null;const o={left:"justify-start",center:"justify-center",right:"justify-end"}[e.alignment||"center"];return a("div",{className:`flex ${o} my-4 ${r}`,style:n,children:t("div",{className:"space-y-2 max-w-full",children:[a("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&&a("p",{className:"text-sm text-muted-foreground text-center italic",children:e.caption}),e.allowDownload&&e.imageUrl&&t("a",{href:e.imageUrl,download:!0,className:"flex items-center gap-2 text-sm text-primary hover:underline justify-center",children:[a(Je,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function ex(e,a){return e/a}function ax(e,a,t,r){const n=ex(e,a);return t&&!r?{width:t,height:Math.round(t/n)}:r&&!t?{width:Math.round(r*n),height:r}:{width:e,height:a}}function tx(e){const a=[".jpg",".jpeg",".png",".gif",".webp",".svg",".bmp",".ico"];try{const t=new URL(e);return a.some(e=>t.pathname.toLowerCase().endsWith(e))}catch{const t=e.toLowerCase();return a.some(e=>t.endsWith(e))}}function rx(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"}}function nx(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function ix(){const{alias:e}=kl(),[a,t]=o(null),[r,n]=o(!0);m(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=rl(),{data:n,error:i}=await r.schema("common").from("sign_configs").select("*").eq("alias",e).is("deleted_at",null).maybeSingle();a||t(n)}catch(r){a||t(null)}finally{a||n(!1)}})(),()=>{a=!0}},[e]);return{config:a,isLoading:r,saveConfig:l(async(a,r)=>{if(!e)throw new Error("Alias not available");const n=rl(),{data:i,error:o}=await n.schema("common").from("sign_configs").upsert({alias:e,api_key:a,environment:r,updated_at:(new Date).toISOString()},{onConflict:"alias"}).select().maybeSingle();if(o)throw o;return t(i),i},[e])}}const ox=import.meta.env.VITE_SUPABASE_URL,sx=Js();async function lx(e,a,t){const r=Ys.getSupabaseToken(),n={"Content-Type":"application/json",apikey:sx};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${ox}/functions/v1/${e}`,{method:"POST",headers:n,body:JSON.stringify({action:a,data:t})});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`Erro na requisição: ${i.status}`)}return i}const dx={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await lx(a,t,{content_base64:e.contentBase64,filename:e.filename,signer_email:e.signerEmail,signer_name:e.signerName})).json()},async getSignedDocument(e){const a="d4sign"===e.provider?"d4sign":"clicksign";return(await lx(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let cx=null;function ux(){return window.Clicksign?Promise.resolve():cx||(cx=new Promise((e,a)=>{const t=document.createElement("script");t.src="https://cdn-public-library.clicksign.com/embedded/embedded.min-2.1.0.js",t.onload=()=>e(),t.onerror=()=>a(new Error("Falha ao carregar script do Clicksign")),document.head.appendChild(t)}),cx)}const mx="clicksign-container";function px({signerId:e,environment:r="sandbox",onSign:n,onError:i,onClose:s}){const{t:l}=Ga(),d=u(null),[c,p]=o(!0),[h,f]=o(null);return m(()=>{let a=!1;return d.current&&(d.current.unmount(),d.current=null),f(null),p(!0),ux().then(()=>{if(a)return;const t=new window.Clicksign(e);t.endpoint="production"===r?"https://app.clicksign.com":"https://sandbox.clicksign.com",t.origin=window.origin,t.mount(mx),t.on("loaded",function(){p(!1)}),t.on("signed",function(){n?.()}),t.on("resized",function(e){const a=e,t=document.getElementById(mx);t&&a?.data?.height&&(t.style.height=a.data.height+"px")}),t.on("error",function(e){p(!1),i?.(e instanceof Error?e:new Error(l("sign_widget_error")))}),t.on("closed",function(){s?.()}),d.current=t}).catch(e=>{a||(f("Falha ao carregar o script de assinatura."),p(!1),i?.(e))}),()=>{a=!0,d.current&&(d.current.unmount(),d.current=null)}},[e,r]),t("div",{className:"relative h-full",children:[c&&a("div",{className:"absolute inset-0 flex items-center justify-center",children:t("div",{className:"flex items-center gap-2 text-muted-foreground",children:[a(T,{className:"h-5 w-5 animate-spin"}),a("span",{className:"text-sm",children:"Carregando documento..."})]})}),h&&a("div",{className:"absolute inset-0 flex items-center justify-center",children:a("p",{className:"text-sm text-destructive",children:h})}),a("div",{id:mx,style:{height:"600px"}})]})}function hx({documentKey:r,signerEmail:n,signerName:i,keySigner:s,environment:d,onSign:c,onError:p}){const h=u(null),[f,g]=o("loading"),[v,b]=o(null),x="production"===d?"https://secure.d4sign.com.br/embed/viewblob":"https://sandbox.d4sign.com.br/embed/viewblob",y=(()=>{const e=new URLSearchParams({email:n,display_name:i||"",disable_preview:"0"});return s&&e.set("key_signer",s),`${x}/${r}?${e.toString()}`})(),N=l(a=>"signed"===a.data?(g("ready"),void c?.()):"wrong-data"===a.data?(g("error"),b(e.t("sign_incorrect_data")),void p?.(new Error(e.t("sign_incorrect_data")))):void 0,[c,p]);m(()=>(window.addEventListener("message",N,!1),()=>{window.removeEventListener("message",N,!1)}),[N]);const w=l(()=>{"loading"===f&&g("ready")},[f]);return"error"===f?t(rc,{variant:"danger",className:"my-4",children:[a(nc,{children:e.t("sign_doc_load_error")}),a(ic,{children:v||"Ocorreu um erro inesperado ao carregar o documento para assinatura. Tente novamente."})]}):t("div",{className:"relative h-full",children:["loading"===f&&a("div",{className:"absolute inset-0 flex items-center justify-center",children:t("div",{className:"flex items-center gap-2 text-muted-foreground",children:[a(T,{className:"h-5 w-5 animate-spin"}),a("span",{className:"text-sm",children:"Carregando documento..."})]})}),a("iframe",{ref:h,id:"d4sign-container",src:y,width:"100%",style:{height:"600px",border:0},allow:"geolocation",onLoad:w})]})}function fx({file:r,onDocumentSigned:n,onError:i,showEventLog:s=!1}){const{user:d,alias:c}=kl(),{config:p,isLoading:h}=ix(),{t:f}=Ga(),[g,v]=o(null),[b,x]=o(!1),[y,N]=o(null),[w,_]=o("sandbox"),[k,S]=o("clicksign"),[A,E]=o(null),[D,P]=o(null),[I,R]=o(!1),[M,L]=o(0),[z,F]=o(!1),[U,j]=o([]),O=u(null),B=u(null),$=l(e=>{s&&j(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[s]),V=l(async a=>{if(v(a),N(null),E(null),P(null),$(`Arquivo selecionado: ${a.name}`),c&&d){x(!0);try{const t=p?.provider??"clicksign";S(t),$(`Provedor resolvido: ${t}`);const r=new FileReader,n=await new Promise((e,t)=>{r.onload=()=>{const a=r.result;e(a)},r.onerror=t,r.readAsDataURL(a)});$(`Criando envelope para assinatura via ${t}...`);const o=await dx.createEnvelopeWithSigner({alias:c,contentBase64:n,filename:a.name,signerEmail:d.email||"",signerName:d.name||"",provider:t});$(`Envelope criado: ${o.envelope_id}`),E({envelope_id:o.envelope_id,document_id:o.document_id,signer_email:o.signer_email,key_signer:o.signer_id}),_(o.environment),S(o.provider||t),"d4sign"===t?($("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),N(o.document_id),C.success(f("sign_doc_sent","Documento enviado! Assine abaixo."))):o.signer_id?($(`Signer ID obtido: ${o.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),N(o.signer_id),C.success(f("sign_doc_sent","Documento enviado! Assine abaixo."))):($(e.t("sign_signer_unavailable")),C.error(f("sign_access_error","Não foi possível obter o acesso para assinatura. Tente novamente.")),i?.(new Error(f("sign_signer_unavailable"))))}catch(t){const a=t instanceof Error?t:new Error(f("sign_process_error",f("sign_doc_process_error"))),r=a.message||"";r.includes("MONTHLY_LIMIT_REACHED")?($(e.t("sign_monthly_limit")),C.error(f("sign_monthly_limit","Limite mensal de assinaturas atingido. Entre em contato com o administrador para ampliar seu plano."))):($(`Erro: ${r}`),C.error(r)),i?.(a)}finally{x(!1)}}},[c,d,$,i,p]);m(()=>{r&&c&&d&&!h&&r!==B.current&&(B.current=r,V(r))},[r,c,d,h,V]);const q=l(async()=>{if(!A||!c)return;R(!0),L(0),F(!1),$("Buscando documento assinado...");for(let t=1;t<=6;t++){L(t),$(`Tentativa ${t}/6...`);try{const a=await dx.getSignedDocument({alias:c,envelopeId:A.envelope_id,documentId:A.document_id,provider:k});if(a.download_url)return $(e.t("sign_doc_available")),P(a.download_url),void R(!1)}catch(a){$(`Erro na tentativa ${t}: ${a instanceof Error?a.message:f("unknown_error")}`)}t<6&&($("Aguardando 10 segundos para próxima tentativa..."),await new Promise(e=>setTimeout(e,1e4)))}$(e.t("sign_fetch_failed")),R(!1),F(!0)},[A,c,$,k]),W=l(async()=>{$("Documento assinado com sucesso!"),C.success(f("sign_signed_success","Documento assinado com sucesso!")),N(null),A&&c&&(n?.({success:!0,provider:k,envelope_id:A.envelope_id,document_id:A.document_id,signer_id:y||"",environment:w}),await q())},[$,n,A,y,c,w,k,q]);if(!c)return a(Gi,{className:"border-amber-200 bg-amber-50",children:a(Xi,{className:"flex items-start gap-3 py-6",children:t("div",{children:[a("p",{className:"font-medium text-amber-800",children:f("sign_auth_required","Autenticação necessária")}),a("p",{className:"text-sm text-amber-700 mt-1",children:f("sign_login_required","Faça login para utilizar a assinatura digital.")})]})})});const H="d4sign"===k?"D4Sign":"Clicksign",G=()=>s&&U.length>0?a("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:U.map((e,t)=>a("div",{children:e},t))}):null;return A&&!y&&(D||I||z)?t("div",{className:"space-y-4",children:[a(Gi,{className:"border-green-200 bg-green-50",children:t(Xi,{className:"flex flex-col items-center gap-4 py-8",children:[a(aa,{className:"h-12 w-12 text-green-600"}),t("div",{className:"text-center",children:[a("p",{className:"text-lg font-semibold text-green-800",children:f("sign_signed_success","Documento assinado com sucesso!")}),a("p",{className:"text-sm text-green-700 mt-1",children:g?.name})]}),I?t("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[t("div",{className:"flex items-center gap-2",children:[a(T,{className:"h-4 w-4 animate-spin"}),f("sign_preparing_doc","Preparando documento assinado...")," (",f("sign_attempt","tentativa")," ",M,"/6)"]}),a("p",{className:"text-xs text-muted-foreground",children:f("sign_waiting_provider",`Aguardando processamento pelo ${H}...`)})]}):D?a($i,{asChild:!0,variant:"default",className:"gap-2",children:t("a",{href:D,target:"_blank",rel:"noopener noreferrer",children:[a(Je,{className:"h-4 w-4"}),f("sign_download_signed","Baixar documento assinado")]})}):z?t("div",{className:"text-center space-y-3",children:[t("div",{className:"space-y-1",children:[a("p",{className:"text-sm text-muted-foreground",children:f("sign_fetch_failed","Não foi possível obter o documento assinado após 1 minuto.")}),a("p",{className:"text-xs text-muted-foreground",children:f("sign_email_fallback","O documento será enviado para o seu e-mail assim que estiver disponível.")})]}),t($i,{variant:"secondary",className:"gap-2",onClick:q,children:[a(ue,{className:"h-4 w-4"}),f("sign_try_again","Tentar novamente")]})]}):null]})}),a(G,{})]}):y?t("div",{className:"space-y-4",children:["d4sign"===k?a(hx,{documentKey:y,signerEmail:A?.signer_email||d?.email||"",signerName:d?.name,keySigner:A?.key_signer,environment:w,onSign:W,onError:i}):a(px,{signerId:y,environment:w,onSign:W,onError:i}),a(G,{})]}):r&&(b||h)?a(Gi,{children:t(Xi,{className:"flex items-center justify-center gap-3 py-10",children:[a(T,{className:"h-6 w-6 animate-spin text-primary"}),a("p",{className:"font-medium",children:f("sign_sending_doc","Enviando documento para assinatura...")})]})}):t("div",{className:"space-y-4",children:[a("input",{ref:O,type:"file",accept:"application/pdf",className:"hidden",onChange:e=>{const a=e.target.files?.[0];a&&"application/pdf"===a.type?V(a):C.error(f("sign_select_pdf","Selecione um arquivo PDF"))}}),a(Gi,b?{children:t(Xi,{className:"flex items-center justify-center gap-3 py-10",children:[a(T,{className:"h-6 w-6 animate-spin text-primary"}),a("p",{className:"font-medium",children:f("sign_sending_doc","Enviando documento para assinatura...")})]})}:{className:"border-dashed border-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>O.current?.click(),children:t(Xi,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[a(ya,{className:"h-8 w-8 text-muted-foreground"}),t("div",{className:"text-center",children:[a("p",{className:"font-medium",children:f("sign_select_pdf","Selecione um arquivo PDF")}),a("p",{className:"text-sm text-muted-foreground",children:f("sign_click_to_select","Clique para escolher o documento para assinatura")})]})]})}),a(G,{})]})}function gx({onSaved:e}){const{config:r,isLoading:n,saveConfig:i}=ix(),{t:s}=Ga(),[l,d]=o(""),[c,u]=o("sandbox"),[p,h]=o(!1);m(()=>{!n&&r&&(d(r.api_key),u(r.environment))},[r,n]);return n?a("div",{className:"flex items-center justify-center py-8",children:a(T,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t("div",{className:"space-y-4",children:[t("div",r?{className:"flex items-center gap-2 text-sm text-emerald-600",children:[a(le,{className:"h-4 w-4"}),a("span",{children:s("sign_configured",s("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[a(O,{className:"h-4 w-4"}),a("span",{children:s("sign_not_configured",s("sign_not_configured_unit"))})]}),t(Gi,{children:[a(Ki,{children:a(Yi,{className:"text-base",children:s("sign_digital_config")})}),a(Xi,{children:t("form",{onSubmit:async a=>{if(a.preventDefault(),l.trim()){h(!0);try{await i(l.trim(),c),C.success(s("sign_config_saved",s("sign_config_saved_success"))),e?.()}catch(t){C.error(s("sign_config_save_error",s("sign_config_save_err")))}finally{h(!1)}}else C.error(s("sign_api_key_required",s("sign_api_key_info")))},className:"space-y-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{htmlFor:"sign-api-key",children:"API Key"}),a(qi,{id:"sign-api-key",type:"password",placeholder:s("sign_api_key_placeholder",s("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:s("sign_environment","Ambiente")}),t(Mo,{value:c,onValueChange:e=>u(e),children:[a(Fo,{children:a(zo,{})}),t(Oo,{children:[a($o,{value:"sandbox",children:"Sandbox (Testes)"}),a($o,{value:"production",children:"Produção"})]})]})]}),t($i,{type:"submit",disabled:p,children:[p&&a(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?s("sign_update_config",s("sign_update_config_btn")):s("sign_save_config",s("sign_save_config_btn"))]})]})})]})]})}var vx,bx,xx,yx,Nx,wx,_x,Cx,kx,Sx;(bx=vx||(vx={}))[bx.waitingStart=1]="waitingStart",bx[bx.running=2]="running",bx[bx.effectivenessCheck=3]="effectivenessCheck",bx[bx.done=4]="done",bx[bx.suspended=5]="suspended",bx[bx.canceled=6]="canceled",(yx=xx||(xx={}))[yx.low=0]="low",yx[yx.medium=1]="medium",yx[yx.high=2]="high",(wx=Nx||(Nx={}))[wx.plan=2]="plan",wx[wx.occurrence=3]="occurrence",wx[wx.risk=4]="risk",wx[wx.decisions=5]="decisions",wx[wx.audit=6]="audit",wx[wx.strategyExtension=7]="strategyExtension",wx[wx.standardization=8]="standardization",wx[wx.supplier=9]="supplier",wx[wx.auditItems=10]="auditItems",(Cx=_x||(_x={}))[Cx.currentProgress=1]="currentProgress",Cx[Cx.cumulativeProgress=2]="cumulativeProgress",(Sx=kx||(kx={})).uploading="uploading",Sx.waiting="waiting",Sx.done="done",Sx.error="error",Sx.canceled="canceled",Sx.duplicateItem="duplicateItem";const Ax={[vx.waitingStart]:"#D6D6D6",[vx.running]:"#DAE9F4",[vx.effectivenessCheck]:"#1B75BB29",[vx.done]:"#DDEECA",[vx.suspended]:"#FFF2D6",[vx.canceled]:"#F4433629"},Ex={[vx.waitingStart]:"#666666",[vx.running]:"#1B75BB",[vx.effectivenessCheck]:"#1B75BB",[vx.done]:"#4CAF50",[vx.suspended]:"#FF9800",[vx.canceled]:"#F44336"},Dx={[vx.waitingStart]:"waiting-start",[vx.running]:"running",[vx.effectivenessCheck]:"effectiveness-check",[vx.done]:"done",[vx.suspended]:"suspended",[vx.canceled]:"canceled"};function Px(){return{[vx.waitingStart]:e.t("ap_status_waiting_start"),[vx.running]:e.t("ap_status_running"),[vx.effectivenessCheck]:e.t("ap_status_effectiveness_check"),[vx.done]:e.t("ap_status_done"),[vx.suspended]:e.t("ap_status_suspended"),[vx.canceled]:e.t("ap_status_canceled")}}const Ix=new Proxy({},{get:(e,a)=>{if("symbol"==typeof a)return;return Px()[a]}});function Tx(){return[{id:"immediate",label:e.t("ap_type_immediate")},{id:"corrective",label:e.t("ap_type_corrective")},{id:"preventive",label:e.t("ap_type_preventive")},{id:"improvement",label:e.t("ap_type_improvement")},{id:"standardization",label:e.t("ap_type_standardization")}]}const Rx=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}];function Mx(){return[{id:xx.low,label:e.t("ap_priority_low"),color:"#4CAF50"},{id:xx.medium,label:e.t("ap_priority_medium"),color:"#FF9800"},{id:xx.high,label:e.t("ap_priority_high"),color:"#F44336"}]}const Lx=[{id:xx.low,label:"Baixa",color:"#4CAF50"},{id:xx.medium,label:"Média",color:"#FF9800"},{id:xx.high,label:"Alta",color:"#F44336"}],zx=[vx.done,vx.canceled],Fx=[vx.waitingStart,vx.running,vx.effectivenessCheck,vx.suspended];function Ux(e){const{actionPlan:a,isNew:t=!1,config:r,onSave:n,onCancel:i,onDelete:s,onChangeStatus:d}=e,[c,u]=o({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});m(()=>{a&&u(e=>({...e,formData:a,isFormDisabled:r?.disableFields||zx.includes(a.statusId)}))},[a,r?.disableFields]),m(()=>{u(a=>({...a,isLoading:e.isLoading||!1}))},[e.isLoading]);const p=l((e,a)=>{u(t=>({...t,formData:{...t.formData,[e]:a}}))},[]),h=l(e=>{u(a=>({...a,activeTab:e}))},[]),f=l(async()=>{if(n){u(e=>({...e,isSaving:!0}));try{await n(c.formData)}finally{u(e=>({...e,isSaving:!1}))}}},[n,c.formData]),g=l(async e=>{if(d&&c.formData.id){u(e=>({...e,isLoading:!0}));try{await d(c.formData.id,e)}finally{u(e=>({...e,isLoading:!1}))}}},[d,c.formData.id]),v=l(async()=>{if(s&&c.formData.id){u(e=>({...e,isLoading:!0}));try{await s(c.formData.id)}finally{u(e=>({...e,isLoading:!1}))}}},[s,c.formData.id]);return{formData:c.formData,isLoading:c.isLoading,isSaving:c.isSaving,activeTab:c.activeTab,isFormDisabled:c.isFormDisabled,updateField:p,setActiveTab:h,save:f,changeStatus:g,remove:v,cancel:i}}const jx={[vx.waitingStart]:{label:"",color:"#8B7355",icon:We},[vx.running]:{label:"",color:"#2E7D5B",icon:wa},[vx.effectivenessCheck]:{label:"",color:"#4A6FA5",icon:Ge},[vx.done]:{label:"",color:"#3D7A40",icon:aa},[vx.suspended]:{label:"",color:"#6B7280",icon:Na},[vx.canceled]:{label:"",color:"#B44A4A",icon:E}};function Ox({status:e,labels:t,className:r,size:n,showIcon:i,variant:o}){const s=Px(),l=jx[e];if(!l)return null;const d=t?.[e]||s[e]||"";return a(Yh,{label:d,color:l.color,icon:l.icon,size:n,showIcon:i,variant:o,className:r})}function Bx({formData:e,updateField:r,disabled:n=!1,users:o=[],places:s=[],actionTypes:l,causes:d=[],parentActions:c=[],config:u}){const{t:m}=Ga(),p=u?.requiredFields,h=l||Rx,f=e=>{if(u?.hiddenFields?.includes(e))return!1;if(u?.visibleFields&&u.visibleFields.length>0)return u.visibleFields.includes(e);const a=`${e}Visible`;return!p||!(a in p)||!1!==p[a]},g=e=>p?!!p[e]:"name"===e,v=i.useMemo(()=>{if(e.startDate&&e.endDate){const a=new Date(e.startDate),t=new Date(e.endDate).getTime()-a.getTime();return Math.max(0,Math.ceil(t/864e5))}return e.duration||0},[e.startDate,e.endDate,e.duration]);return t("div",{className:"space-y-6 p-1",children:[t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),a(qi,{value:e.name||"",onChange:e=>r("name",e.target.value),maxLength:500,disabled:n,placeholder:m("ap_plan_name_placeholder")})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f("responsibleWho")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),t(Mo,{value:e.responsibleId||"",onValueChange:e=>r("responsibleId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_responsible")})}),a(Oo,{children:o.map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]}),f("checkerWho")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),t(Mo,{value:e.checkerId||"",onValueChange:e=>r("checkerId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_checker")})}),a(Oo,{children:o.map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f("place")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),t(Mo,{value:e.placeId||"",onValueChange:e=>r("placeId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_place")})}),a(Oo,{children:$x(s).map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]}),f("planType")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),t(Mo,{value:e.typeId||"",onValueChange:e=>r("typeId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_type")})}),a(Oo,{children:h.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[f("priority")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),t(Mo,{value:e.priorityType?.toString()||"",onValueChange:e=>r("priorityType",Number(e)),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_priority")})}),a(Oo,{children:Lx.map(e=>a($o,{value:e.id.toString(),children:t("span",{className:"flex items-center gap-2",children:[a("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:e.color}}),e.label]})},e.id))})]})]}),c.length>0&&t("div",{className:"space-y-2",children:[a(Hi,{children:m("ap_belongs_to")}),t(Mo,{value:e.parentId||"",onValueChange:e=>r("parentId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_parent")})}),a(Oo,{children:c.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]})]}),t("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[f("startDate")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),a(Tu,{date:e.startDate?new Date(e.startDate):void 0,onDateChange:e=>r("startDate",e||null),disabled:n,placeholder:m("ap_select_date")})]}),f("endDate")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),a(Tu,{date:e.endDate?new Date(e.endDate):void 0,onDateChange:e=>r("endDate",e||null),disabled:n,placeholder:m("ap_select_date"),disabledDates:e.startDate?a=>a<new Date(e.startDate):void 0})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:m("ap_duration_days")}),a(qi,{type:"number",value:v,disabled:!0,className:"bg-muted"})]})]}),f("estimatedCost")&&t("div",{className:"space-y-2 max-w-xs",children:[a(Hi,{className:Fi(g("estimatedCost")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Custo Estimado"}),t("div",{className:"relative",children:[a("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm",children:"R$"}),a(qi,{type:"number",min:0,step:.01,value:e.estimatedCost||"",onChange:e=>r("estimatedCost",Number(e.target.value)),disabled:n,className:"pl-9",placeholder:"0,00"})]})]}),f("cause")&&d.length>0&&t("div",{className:"space-y-2",children:[a(Hi,{children:"Causa"}),t(Mo,{value:e.causeId||"",onValueChange:e=>r("causeId",e),disabled:n,children:[a(Fo,{children:a(zo,{placeholder:m("ap_select_cause")})}),a(Oo,{children:d.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]}),f("description")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),a(Wo,{value:e.description||"",onChange:e=>r("description",e.target.value),maxLength:4e3,disabled:n,rows:4,placeholder:m("ap_description_placeholder")})]}),f("justification")&&t("div",{className:"space-y-2",children:[a(Hi,{className:Fi(g("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),a(Wo,{value:e.justification||"",onChange:e=>r("justification",e.target.value),maxLength:4e3,disabled:n,rows:4,placeholder:m("ap_justification_placeholder")})]})]})}function $x(e,a=0){const t=[];for(const r of e)t.push({...r,depth:a}),r.children?.length&&t.push(...$x(r.children,a+1));return t}function Vx(e){const{progress:a,onReportProgress:t,onEditProgress:r,onDeleteProgress:n}=e,[i,s]=o(!1),[d,c]=o(null),u=!!a&&Fx.includes(a.status),m=l(async e=>{if(t&&a){s(!0);try{const r=100===e.percentProgress;await t({id:a.id,...e,conclude:r})}finally{s(!1)}}},[t,a]),p=l(async e=>{if(r){s(!0);try{await r(e)}finally{s(!1),c(null)}}},[r]),h=l(async e=>{if(n){s(!0);try{await n(e)}finally{s(!1)}}},[n]);return{progress:a,canReportProgress:u,isSubmitting:i,editingReport:d,setEditingReport:c,reportProgress:m,editProgress:p,deleteProgress:h}}function qx(e){if(!e)return"";let a=(e||"").trim();if(!a)return"00:00";if(a.includes(":")){const e=a.split(":");if(e.length>=2){const a=e[0].replace(/\D/g,""),t=e[1].replace(/\D/g,"");let r=parseInt(a)||0,n=parseInt(t)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}if(a=a.replace(/\D/g,""),!a)return"00:00";let t=0,r=0;return 4===a.length?(t=parseInt(a.substring(0,2))||0,r=parseInt(a.substring(2,4))||0,t+=Math.floor(r/60),r%=60):(t=parseInt(a)||0,r=0),`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}function Wx(e){if(null==e)return"00:00";const a=String(e).replace(/\D/g,"");if(a.length<3){let e=parseInt(a)||0;const t=Math.floor(e/60);return e%=60,`${t.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}{const e=a.slice(-2),t=a.slice(0,-2);let r=parseInt(t)||0,n=parseInt(e)||0;return r+=Math.floor(n/60),n%=60,`${r.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}`}}function Hx(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function Gx({open:e,onOpenChange:r,report:n,onSave:s,isSubmitting:l=!1}){const{t:d}=Ga(),[c,u]=o(n?.percentProgress||0),[m,p]=o(n?.timeProgress||""),[h,f]=o(n?.comments||""),g=c!==(n?.percentProgress??0)||m!==(n?.timeProgress??"")||h!==(n?.comments??"");i.useEffect(()=>{n&&(u(n.percentProgress),p(n.timeProgress||""),f(n.comments||""))},[n]);return a(mo,{open:e,onOpenChange:r,children:t(bo,{className:"sm:max-w-md",variant:"form",isDirty:g,children:[a(xo,{children:a(wo,{children:d("ap_edit_progress")})}),t("div",{className:"space-y-4 py-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:d("ap_progress_percent")}),a(qi,{type:"number",min:0,max:100,value:c,onChange:e=>u(Number(e.target.value))})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:d("ap_time_spent")}),a(qi,{value:m,onChange:e=>p(e.target.value),onBlur:()=>p(qx(m)||""),placeholder:"00:00"})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:d("ap_comments")}),a(Wo,{value:h,onChange:e=>f(e.target.value),rows:3,maxLength:4e3})]})]}),t(No,{children:[a($i,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancelar"}),a($i,{onClick:()=>{n&&s({...n,percentProgress:c,timeProgress:qx(m)||"00:00",comments:h})},disabled:l,children:l?"Salvando...":"Salvar"})]})]})})}function Kx(e){const{t:r}=Ga(),{progress:n,canReportProgress:i,isSubmitting:s,editingReport:l,setEditingReport:d,reportProgress:c,editProgress:u,deleteProgress:m}=Vx(e),[p,h]=o(""),[f,g]=o(""),[v,b]=o("");if(!n)return a("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Sem dados de progresso disponíveis"});const x=Hx(n.percentProgress),y=!p,N=!p&&!f&&!v;return t("div",{className:"space-y-6 p-1",children:[t("div",{className:"rounded-lg border bg-card p-4 space-y-3",children:[t("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"font-medium",children:r("ap_overall_progress")}),t("span",{className:"font-semibold",style:{color:x||void 0},children:[n.percentProgress,"%"]})]}),a(Tm,{value:n.percentProgress,className:"h-3"}),n.timeProgress&&t("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",Wx(n.timeProgress)]})]}),i&&t("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[a("h4",{className:"text-sm font-medium",children:r("ap_report_progress")}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:r("ap_progress_percent")}),a(qi,{type:"number",min:0,max:100,value:p,onChange:e=>h(e.target.value),placeholder:"0"})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:r("ap_time_spent")}),a(qi,{value:f,onChange:e=>g(e.target.value),onBlur:()=>g(qx(f)||""),placeholder:"00:00"})]})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:r("ap_comments")}),a(Wo,{value:v,onChange:e=>b(e.target.value),rows:3,maxLength:4e3,placeholder:r("ap_progress_comment_placeholder")})]}),t("div",{className:"flex gap-2 justify-end",children:[a($i,{variant:"outline",size:"sm",onClick:()=>{h(""),g(""),b("")},disabled:N||s,children:"Limpar"}),a($i,{size:"sm",onClick:async()=>{const e=Number(p);(e||0===e)&&(await c({percentProgress:e,timeProgress:qx(f)||"00:00",comments:v}),h(""),g(""),b(""))},disabled:y||s,children:s?"Reportando...":"Reportar"})]})]}),n.reports.length>0&&t("div",{className:"space-y-3",children:[a("h4",{className:"text-sm font-medium",children:r("ap_reports_history")}),a("div",{className:"space-y-2",children:n.reports.map(e=>a(Yx,{report:e,onEdit:()=>d(e),onDelete:()=>m(e.id),disabled:!i},e.id))})]}),a(Gx,{open:!!l,onOpenChange:e=>!e&&d(null),report:l,onSave:u,isSubmitting:s})]})}function Yx({report:r,onEdit:n,onDelete:i,disabled:o}){const s=r.date?new Date(r.date):null,l=Hx(r.percentProgress);return t("div",{className:"flex items-start gap-3 rounded-lg border bg-card p-3",children:[a("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:r.userName?.charAt(0)?.toUpperCase()||"?"}),t("div",{className:"flex-1 min-w-0 space-y-1",children:[t("div",{className:"flex items-center gap-2 text-sm",children:[a("span",{className:"font-medium truncate",children:r.userName}),s&&a("span",{className:"text-xs text-muted-foreground",children:s.toLocaleDateString("pt-BR")})]}),t("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[t("span",{style:{color:l||void 0},className:"font-semibold",children:[r.percentProgress,"%"]}),r.timeProgress&&t("span",{children:["Tempo: ",Wx(r.timeProgress)]})]}),r.comments&&a("p",{className:"text-xs text-muted-foreground mt-1",children:r.comments})]}),!o&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[a(ss,{onClick:n,children:e.t("edit")}),a(ss,{className:"text-destructive",onClick:i,children:e.t("ap_delete")})]})]})]})}function Qx({predecessors:e=[],availablePredecessors:r=[],onAdd:n,onRemove:o,disabled:s=!1}){const{t:l}=Ga(),[d,c]=i.useState(""),u=r.filter(a=>!e.some(e=>e.predecessorId===a.id));return t("div",{className:"space-y-6 p-1",children:[!s&&u.length>0&&t("div",{className:"flex items-end gap-3",children:[t("div",{className:"flex-1 space-y-2",children:[a(Hi,{children:l("ap_add_predecessor")}),t(Mo,{value:d,onValueChange:c,children:[a(Fo,{children:a(zo,{placeholder:l("ap_select_action")})}),a(Oo,{children:u.map(e=>a($o,{value:e.id,children:e.label},e.id))})]})]}),t($i,{size:"sm",onClick:()=>{d&&n&&(n(d),c(""))},disabled:!d,children:[a(Q,{className:"h-4 w-4 mr-1"}),"Adicionar"]})]}),e.length>0?a("div",{className:"space-y-2",children:e.map(e=>t("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[t("div",{className:"flex items-center gap-3",children:[e.predecessorCode&&a("span",{className:"text-xs text-muted-foreground font-mono",children:e.predecessorCode}),a("span",{className:"text-sm font-medium",children:e.predecessorName}),null!=e.predecessorStatus&&a(Ox,{status:e.predecessorStatus})]}),!s&&o&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),a(os,{align:"end",children:a(ss,{className:"text-destructive",onClick:()=>o(e.predecessorId),children:"Remover"})})]})]},e.id))}):a("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum predecessor adicionado"})]})}function Xx({costs:e=[],onAdd:r,onEdit:n,onDelete:i,disabled:s=!1}){const{t:l}=Ga(),[d,c]=o(""),[u,m]=o(""),p=e.reduce((e,a)=>e+(a.value||0),0);return t("div",{className:"space-y-6 p-1",children:[t("div",{className:"rounded-lg border bg-card p-4 flex items-center justify-between",children:[a("span",{className:"text-sm font-medium",children:l("ap_total_cost")}),t("span",{className:"text-lg font-semibold text-foreground",children:["R$ ",p.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),!s&&r&&t("div",{className:"rounded-lg border bg-card p-4 space-y-4",children:[a("h4",{className:"text-sm font-medium",children:l("ap_add_cost")}),t("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Hi,{children:"Descrição"}),a(qi,{value:d,onChange:e=>c(e.target.value),placeholder:l("ap_cost_description")})]}),t("div",{className:"space-y-2",children:[a(Hi,{children:"Valor (R$)"}),a(qi,{type:"number",min:0,step:.01,value:u,onChange:e=>m(e.target.value),placeholder:"0,00"})]})]}),a("div",{className:"flex justify-end",children:t($i,{size:"sm",onClick:()=>{d&&u&&r&&(r({description:d,value:Number(u),date:(new Date).toISOString()}),c(""),m(""))},disabled:!d||!u,children:[a(Q,{className:"h-4 w-4 mr-1"}),"Adicionar"]})})]}),e.length>0?a("div",{className:"space-y-2",children:e.map(e=>t("div",{className:"flex items-center justify-between rounded-lg border bg-card p-3",children:[t("div",{className:"flex-1 min-w-0",children:[a("p",{className:"text-sm font-medium truncate",children:e.description}),e.date&&a("p",{className:"text-xs text-muted-foreground",children:new Date(e.date).toLocaleDateString("pt-BR")})]}),t("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-sm font-semibold whitespace-nowrap",children:["R$ ",e.value.toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]}),!s&&(n||i)&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[n&&a(ss,{onClick:()=>n(e),children:l("edit")}),i&&a(ss,{className:"text-destructive",onClick:()=>i(e.id),children:l("ap_delete")})]})]})]})]},e.id))}):a("div",{className:"flex items-center justify-center py-8 text-sm text-muted-foreground",children:"Nenhum custo registrado"})]})}function Jx({comments:e=[],currentUserId:r,onAdd:n,onEdit:i,onDelete:s,disabled:l=!1,maxLength:d=4e3}){const{t:c}=Ga(),[u,m]=o(""),[p,h]=o(!1),[f,g]=o(null),[v,b]=o(""),x=()=>{g(null),b("")};return t("div",{className:"space-y-6 p-1",children:[!l&&n&&t("div",{className:"space-y-3",children:[a(Wo,{value:u,onChange:e=>m(e.target.value),placeholder:c("ap_add_comment_placeholder"),maxLength:d,rows:3}),t("div",{className:"flex items-center justify-between",children:[d&&t("span",{className:"text-xs text-muted-foreground",children:[u.length,"/",d]}),t("div",{className:"flex gap-2 ml-auto",children:[a($i,{variant:"outline",size:"sm",onClick:()=>m(""),disabled:!u||p,children:"Limpar"}),a($i,{size:"sm",onClick:async()=>{if(u.trim()&&n){h(!0);try{await n(u),m("")}finally{h(!1)}}},disabled:!u.trim()||p,children:p?"Enviando...":"Comentar"})]})]})]}),t("div",{className:"space-y-1",children:[e.length>0?t("div",{className:"flex items-center gap-2 mb-3",children:[a("span",{className:"text-sm font-medium",children:c("ap_comments")}),a(Go,{variant:"info",className:"text-[10px] px-1.5 py-0",children:e.length})]}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[a(_a,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:"Nenhum comentário adicionado"})]}),e.map(e=>t("div",{className:"flex gap-3 rounded-lg border bg-card p-3",children:[a("div",{className:"flex-shrink-0 h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground overflow-hidden",children:e.userPhotoUrl?a("img",{src:e.userPhotoUrl,alt:e.userName,className:"h-full w-full object-cover"}):e.userName?.charAt(0)?.toUpperCase()||"?"}),t("div",{className:"flex-1 min-w-0 space-y-1",children:[t("div",{className:"flex items-center gap-2 text-sm",children:[a("span",{className:"font-medium truncate",children:e.userName}),e.userEmail&&a("span",{className:"text-xs text-muted-foreground truncate",children:e.userEmail}),a("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:Zx(e.dateEdited||e.dateCreation)}),e.dateEdited&&a("span",{className:"text-xs text-muted-foreground italic",children:"editado"})]}),f===e.id?t("div",{className:"space-y-2",children:[a(Wo,{value:v,onChange:e=>b(e.target.value),maxLength:d,rows:3}),t("div",{className:"flex gap-2 justify-end",children:[a($i,{variant:"outline",size:"sm",onClick:x,disabled:p,children:"Cancelar"}),a($i,{size:"sm",onClick:()=>(async e=>{if(v.trim()&&i){h(!0);try{await i({...e,text:v,stringText:v}),g(null),b("")}finally{h(!1)}}})(e),disabled:!v.trim()||p,children:p?"Salvando...":"Salvar"})]})]}):a("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:e.stringText||e.text})]}),!l&&r===e.userId&&f!==e.id&&t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[i&&a(ss,{onClick:()=>(e=>{g(e.id),b(e.stringText||e.text)})(e),children:c("edit")}),s&&a(ss,{className:"text-destructive",onClick:()=>(async e=>{if(s){h(!0);try{await s(e)}finally{h(!1)}}})(e.id),children:"Excluir"})]})]})]},e.id))]})]})}function Zx(e){const{t:a}=Ga();if(!e)return"";const t=new Date(e);return`${t.toLocaleDateString("pt-BR")} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function ey({history:e=[],isLoading:r=!1}){const{t:n}=Ga();return r?a("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:"Carregando histórico..."}):0===e.length?t("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[a(We,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:n("ap_no_history")})]}):a("div",{className:"p-1",children:t("div",{className:"relative",children:[a("div",{className:"absolute left-4 top-0 bottom-0 w-px bg-border"}),a("div",{className:"space-y-0",children:e.map((e,r)=>t("div",{className:"relative flex gap-4 pb-6 last:pb-0",children:[a("div",{className:"relative z-10 flex-shrink-0 h-8 w-8 rounded-full bg-primary/10 border-2 border-primary/30 flex items-center justify-center",children:e.icon?a("span",{className:"text-xs text-primary",children:e.icon}):a("div",{className:"h-2 w-2 rounded-full bg-primary"})}),t("div",{className:"flex-1 min-w-0 rounded-lg border bg-card p-3 space-y-2",children:[t("div",{children:[a("h4",{className:"text-sm font-medium",children:e.translateEvent||e.eventName}),e.eventDescription&&a("p",{className:"text-xs text-muted-foreground",children:e.eventDescription})]}),t("div",{className:"flex items-center gap-2",children:[a("div",{className:"flex-shrink-0 h-6 w-6 rounded-full bg-muted overflow-hidden flex items-center justify-center text-[10px] font-medium text-muted-foreground",children:e.userPhotoUrl?a("img",{src:e.userPhotoUrl,alt:e.userName,className:"h-full w-full object-cover"}):e.userName?.charAt(0)?.toUpperCase()||"?"}),t("div",{className:"min-w-0",children:[a("span",{className:"text-xs font-medium truncate block",children:e.userName}),e.userEmail&&a("span",{className:"text-[10px] text-muted-foreground truncate block",children:e.userEmail})]})]}),t("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[t("div",{className:"flex items-center gap-1",children:[a(ye,{className:"h-3 w-3"}),a("span",{children:ay(e.date)})]}),t("div",{className:"flex items-center gap-1",children:[a(We,{className:"h-3 w-3"}),a("span",{children:ty(e.date)})]}),e.isMobileRequest&&t("div",{className:"flex items-center gap-1",children:[a(Ca,{className:"h-3 w-3"}),a("span",{children:n("ap_via_app")})]})]})]})]},e.id))})]})})}function ay(e){const{t:a}=Ga();return new Date(e).toLocaleDateString("pt-BR")}function ty(e){const{t:a}=Ga();return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function ry({attachments:e=[],onUpload:n,onDelete:i,onRename:s,onDownload:l,onView:d,disabled:c=!1}){const{t:m}=Ga(),p=u(null),[h,f]=o(null),[g,v]=o(""),b=async e=>{g.trim()&&s&&(await s(e.id,g),f(null),v(""))},x=()=>{f(null),v("")};return t("div",{className:"space-y-4 p-1",children:[!c&&n&&t(r,{children:[a("input",{ref:p,type:"file",multiple:!0,className:"hidden",onChange:e=>{const a=e.target.files;if(a&&n){for(let e=0;e<a.length;e++){const t=a.item(e);t&&n(t)}p.current&&(p.current.value="")}}}),t($i,{size:"sm",onClick:()=>p.current?.click(),children:[a(Q,{className:"h-4 w-4 mr-1"}),"Adicionar anexo"]})]}),e.length>0?a("div",{className:"space-y-2",children:e.map(e=>t("div",{className:Fi("flex items-center gap-3 rounded-lg border bg-card p-3",e.status===kx.error&&"border-destructive/50 bg-destructive/5",e.status===kx.canceled&&"opacity-50"),children:[a("div",{className:"flex-shrink-0 h-9 w-9 rounded bg-muted flex items-center justify-center",children:a("span",{className:"text-[10px] font-bold uppercase text-muted-foreground",children:e.extension.replace(".","").substring(0,4)})}),t("div",{className:"flex-1 min-w-0 space-y-1",children:[h===e.id?t("div",{className:"flex items-center gap-2",children:[a("input",{className:"flex-1 text-sm border rounded px-2 py-1 bg-background",value:g,onChange:e=>v(e.target.value),onKeyDown:a=>{"Enter"===a.key&&b(e),"Escape"===a.key&&x()},autoFocus:!0}),a($i,{size:"sm",variant:"outline",onClick:x,children:m("cancel")}),a($i,{size:"sm",onClick:()=>b(e),children:m("save")})]}):a("button",{type:"button",className:"text-sm font-medium truncate block text-left hover:underline cursor-pointer",onClick:()=>d?.(e.id),children:e.name}),(e.status===kx.uploading||e.status===kx.waiting)&&a(Tm,{value:e.progress||0,className:"h-1.5"}),e.status===kx.error&&a("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),e.status===kx.duplicateItem&&a("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),e.status===kx.canceled&&a("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),t("div",{className:"flex items-center gap-2",children:[e.status===kx.done&&t(r,{children:[a("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:ny(e.size)}),t(Jo,{children:[a(Zo,{asChild:!0,children:a(Vi,{})}),t(os,{align:"end",children:[s&&!c&&a(ss,{onClick:()=>(e=>{const a=e.name.replace(e.extension,"");f(e.id),v(a)})(e),children:"Renomear"}),d&&a(ss,{onClick:()=>d(e.id),children:"Visualizar"}),l&&a(ss,{onClick:()=>l(e.id),children:"Download"}),i&&!c&&t(r,{children:[a(us,{}),a(ss,{className:"text-destructive",onClick:()=>i(e.id),children:"Excluir"})]})]})]})]}),e.status===kx.uploading&&a($i,{variant:"outline",size:"sm",onClick:()=>i?.(e.id),children:"Cancelar"})]})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[a(ka,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function ny(e){const{t:a}=Ga();if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,t)).toFixed(1))} ${["B","KB","MB","GB"][t]}`}function iy(e){const{formData:r,isLoading:n,isSaving:i,activeTab:o,isFormDisabled:s,updateField:l,setActiveTab:d,save:c,changeStatus:u,remove:m,cancel:p}=Ux(e),{t:h}=Ga(),{isNew:f=!1,config:g,users:v,places:b,actionTypes:x,causes:y,parentActions:N,progress:w,predecessors:_,availablePredecessors:C,costs:k,comments:S,history:A,attachments:E,attachmentsSlot:D,commentsSlot:P,historySlot:I,onAddPredecessor:T,onRemovePredecessor:R,onAddCost:M,onEditCost:L,onDeleteCost:z,onAddComment:F,onEditComment:U,onDeleteComment:j,onUploadAttachment:O,onDeleteAttachment:B,onRenameAttachment:$,onDownloadAttachment:V,onViewAttachment:q}=e;if(n&&!r.id)return a(Qo,{isLoading:!0,children:a("div",{})});const W=function(e){const{t:a}=Ga();if(!e)return[];return{[vx.waitingStart]:[vx.running,vx.suspended,vx.canceled],[vx.running]:[vx.effectivenessCheck,vx.done,vx.suspended,vx.canceled],[vx.effectivenessCheck]:[vx.running,vx.done,vx.suspended,vx.canceled],[vx.done]:[vx.running],[vx.suspended]:[vx.running,vx.canceled],[vx.canceled]:[vx.waitingStart]}[e]||[]}(r.statusId);return t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex items-center justify-between border-b bg-card px-6 py-4",children:[t("div",{className:"flex items-center gap-4",children:[p&&a($i,{variant:"ghost",size:"icon",onClick:p,children:a(je,{className:"h-4 w-4"})}),t("div",{className:"space-y-1",children:[t("div",{className:"flex items-center gap-3",children:[a("h1",{className:"text-lg font-semibold",children:f?h("ap_new_action"):r.name||h("ap_action_plan")}),!f&&r.statusId&&a(Ox,{status:r.statusId})]}),r.code&&a("p",{className:"text-xs text-muted-foreground font-mono",children:r.code})]})]}),t("div",{className:"flex items-center gap-2",children:[!f&&W.length>0&&!s&&t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"outline",size:"sm",children:"Alterar Status"})}),a(os,{align:"end",children:W.map(e=>a(ss,{onClick:()=>u(e),children:Ix[e]},e))})]}),!f&&e.onDelete&&t(Jo,{children:[a(Zo,{asChild:!0,children:a($i,{variant:"ghost",size:"icon",children:a(ra,{className:"h-4 w-4"})})}),a(os,{align:"end",children:a(ss,{className:"text-destructive",onClick:m,children:"Excluir"})})]})]})]}),a("div",{className:"flex-1 min-h-0 overflow-y-auto",children:a("div",{className:"max-w-4xl mx-auto px-6 py-6",children:t(Pc,{value:o,onValueChange:d,children:[t(Ic,{className:"mb-6",children:[a(Tc,{value:"general",children:"Geral"}),!f&&a(Tc,{value:"progress",children:"Progresso"}),!f&&g?.enablePredecessors&&a(Tc,{value:"predecessors",children:h("ap_predecessors")}),!f&&g?.enableCosts&&a(Tc,{value:"costs",children:"Custos"}),!f&&g?.enableAttachments&&a(Tc,{value:"attachments",children:h("ap_attachments")}),!f&&g?.enableComments&&a(Tc,{value:"comments",children:h("ap_comments")}),!f&&g?.enableHistory&&a(Tc,{value:"history",children:"Histórico"})]}),a(Rc,{value:"general",children:a(Bx,{formData:r,updateField:l,disabled:s,users:v,places:b,actionTypes:x,causes:y,parentActions:N,config:g})}),!f&&a(Rc,{value:"progress",children:a(Kx,{...e})}),!f&&g?.enablePredecessors&&a(Rc,{value:"predecessors",children:a(Qx,{predecessors:_,availablePredecessors:C,onAdd:T,onRemove:R,disabled:s})}),!f&&g?.enableCosts&&a(Rc,{value:"costs",children:a(Xx,{costs:k,onAdd:M,onEdit:L,onDelete:z,disabled:s})}),!f&&g?.enableAttachments&&a(Rc,{value:"attachments",children:D||a(ry,{attachments:E,onUpload:O,onDelete:B,onRename:$,onDownload:V,onView:q,disabled:s})}),!f&&g?.enableComments&&a(Rc,{value:"comments",children:P||a(Jx,{comments:S,onAdd:F,onEdit:U,onDelete:j,disabled:s})}),!f&&g?.enableHistory&&a(Rc,{value:"history",children:I||a(ey,{history:A})})]})})}),t("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[p&&a($i,{variant:"outline",onClick:p,disabled:i,children:"Cancelar"}),a($i,{onClick:c,disabled:i||s,children:i?"Salvando...":"Salvar"})]})]})}const oy=["application/x-msdownload","application/x-msdos-program","application/x-executable","application/x-javascript","application/javascript","text/javascript","text/vbscript","application/sql","application/x-sh","application/x-shellscript","application/hta","application/vnd.ms-word.document.macroEnabled.12","application/vnd.ms-excel.sheet.macroEnabled.12","application/vnd.ms-powerpoint.presentation.macroEnabled.12"];function sy(e){if(!e)return"";if(e<1024)return`${e} Bytes`;const a=e/1024;if(a<1024)return`${Math.round(a)} KB`;const t=a/1024;if(t<1024)return`${Math.round(t)} MB`;const r=t/1024;return Math.round(100*r)/100+" GB"}function ly(e){const a=e.lastIndexOf(".");return-1===a?"":e.substring(a+1).toLowerCase()}function dy({storedFile:e,customFileName:r,allowedExtensions:n,customExtensionErrorMessage:i,minSizeInBytes:s=1,maxSizeInBytes:d=314572800,showDownloadButton:c=!0,showViewButton:m=!0,showReplaceButton:p=!0,showCloseButton:h=!0,required:f=!1,touched:g=!1,disabled:v=!1,error:b,onFileSelect:x,onFileRemove:y,onFileReplace:N,onDownload:w,onView:_,className:C}){const{t:k}=Ga(),S=u(null),[A,D]=o(null),[P,I]=o(null),[T,R]=o(!1),M=A||e,L=A?.name||e?.name||"",z=A?.size||e?.size;L&&ly(L);const F=r||L,U=c&&!A&&!!e,j=m&&!A&&!!e,O=!!P||!!b||f&&g&&!M,B=!!M,$=l(e=>{if(oy.includes(e.type))return{type:"forbidden-type"};if(e.size<=s)return{type:"min-size"};if(e.size>=d)return{type:"max-size"};if(n?.length){const a=ly(e.name);if(!n.includes(a))return{type:"extension",message:i}}return null},[s,d,n,i]),V=l(e=>{const a=e.target.files?.[0];if(!a)return;const t=$(a);if(t)return I(t),D(null),void(S.current&&(S.current.value=""));I(null),D(a),x?.(a),S.current&&(S.current.value="")},[$,x]),q=l(e=>{if(e.preventDefault(),e.stopPropagation(),v)return;const a=e.dataTransfer.files?.[0];if(!a)return;const t=$(a);if(t)return I(t),void D(null);I(null),D(a),x?.(a)},[v,$,x]),W=l(e=>{e.preventDefault(),e.stopPropagation()},[]),H=l(()=>{N?.(),S.current?.click()},[N]),G=l(()=>{D(null),I(null),y?.(),S.current&&(S.current.value="")},[y]),K=l(async()=>{if(!T&&e&&w){R(!0);try{await w(e)}finally{R(!1)}}},[T,e,w]),Y=l(()=>{e&&_&&_(e)},[e,_]),Q=l(()=>{v||S.current?.click()},[v]),X=(()=>{if(b)return b;if(!P)return f&&g&&!M?k("required_field"):null;switch(P.type){case"extension":return P.message||k("sign_file_not_allowed");case"forbidden-type":return k("sign_file_type_not_allowed");case"min-size":return`Tamanho mínimo: ${sy(s)}`;case"max-size":return`Tamanho máximo: ${sy(d)}`;default:return k("file_error")}})();return t("div",{className:Fi("space-y-1",C),children:[a("div",{className:Fi("rounded-md border border-dashed transition-colors",B&&"border-solid border-border",!B&&"border-muted-foreground/30 hover:border-primary/50 cursor-pointer",O&&"border-destructive border-solid",v&&"opacity-50 pointer-events-none"),children:t("div",B?{className:"flex items-center justify-between px-3 min-h-[36px]",children:[t("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[a(Be,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),a("p",{className:"text-xs truncate",children:F})]}),t("div",{className:"flex items-center gap-2 shrink-0",children:[null!=z&&a("span",{className:"text-xs text-muted-foreground",children:sy(z)}),t("div",{className:"flex items-center gap-0.5",children:[U&&w&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:T,onClick:K,children:a(Je,{className:"h-3.5 w-3.5 text-primary"})})}),a(gs,{children:"Download"})]}),j&&_&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:Y,children:a(Ce,{className:"h-3.5 w-3.5 text-primary"})})}),a(gs,{children:"Visualizar"})]}),p&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:H,children:a(ue,{className:"h-3.5 w-3.5 text-primary"})})}),a(gs,{children:"Substituir"})]}),h&&t(hs,{children:[a(fs,{asChild:!0,children:a($i,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:G,children:a(E,{className:"h-3 w-3 text-muted-foreground"})})}),a(gs,{children:k("remove")})]})]})]})]}:{className:"flex items-center justify-center gap-2 min-h-[36px] px-3",tabIndex:0,onClick:Q,onKeyDown:e=>"Enter"===e.key&&Q(),onDrop:q,onDragOver:W,children:[a(Sa,{className:"h-4 w-4 text-muted-foreground"}),t("p",{className:"text-xs font-medium text-muted-foreground",children:["Arraste ou ",a("span",{className:"text-primary",children:"selecione um arquivo"})]})]})}),X&&a("p",{className:"text-xs text-destructive",children:X}),a("input",{ref:S,type:"file",className:"hidden",accept:n?.map(e=>`.${e}`).join(","),onChange:V,disabled:v})]})}var cy,uy,my,py,hy,fy;function gy(e){switch(e.type){case cy.text:return e.textValue;case cy.number:return e.numberValue;case cy.date:return e.dateValue;case cy.time:return e.timeValue;case cy.url:case cy.singleSelection:case cy.multiSelection:return e.itemsValue;case cy.questions:return e.questionsValue;case cy.readOnlyText:return e.textValue;default:return null}}function vy(e,a){if(!a)return!0;const t=null!=gy(e)&&""!==gy(e)&&!(Array.isArray(gy(e))&&0===gy(e).length);return!1!==e.isActive||t}function by(e){return e.filter(e=>e.type!==cy.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===cy.text?e.textValue:void 0,numberValue:e.type===cy.number?e.numberValue:void 0,dateValue:e.type===cy.date?e.dateValue:void 0,timeValue:e.type===cy.time?e.timeValue:void 0,itemsValue:[cy.url,cy.singleSelection,cy.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===cy.questions?e.questionsValue:void 0}))}function xy(e,a){return a?.length?e.map(e=>{const t=a.find(a=>a.formFieldAssociationId===e.id);if(!t)return e;const r={...e};switch(e.type){case cy.text:r.textValue=t.textValue;break;case cy.number:r.numberValue=t.numberValue;break;case cy.date:r.dateValue=t.dateValue;break;case cy.time:r.timeValue=t.timeValue;break;case cy.url:case cy.singleSelection:case cy.multiSelection:r.itemsValue=t.itemsValue||[];break;case cy.questions:r.questionsValue=t.questionsValue||[]}return r}):e}function yy(e){const a=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===cy.readOnlyText)return;const t=gy(e);if((null==t||""===t||Array.isArray(t)&&0===t.length)&&a.push(e.id),e.type===cy.number&&null!=t){const r=e.config;null!=r?.min&&t<r.min&&a.push(e.id),null!=r?.max&&t>r.max&&a.push(e.id)}}),{valid:0===a.length,invalidFields:[...new Set(a)]}}function Ny({field:e}){return t("div",{className:"space-y-1",children:[e.name&&a("p",{className:"text-sm font-medium text-foreground",children:e.name}),e.description&&a("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:e.description}),e.textValue&&a("p",{className:"text-sm text-muted-foreground italic",children:e.textValue})]})}function wy({field:e,readOnly:r,onChange:n}){const i=e.config,o=i?.multiline??!1,s=r||e.readOnly,l=a=>{n?.({...e,textValue:a})};return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),o?a(Wo,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:s,rows:4}):a(qi,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:s})]})}function _y({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,o=e.dateValue?"string"==typeof e.dateValue?e.dateValue.substring(0,10):new Date(e.dateValue).toISOString().substring(0,10):"";return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a(qi,{type:"date",value:o,onChange:a=>{return t=a.target.value,void n?.({...e,dateValue:t||void 0});var t},placeholder:e.placeholder,disabled:i})]})}function Cy({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,o=e=>{if(!e)return;const[a,t]=e.split(":").map(Number);return 60*a+t};return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a(qi,{type:"time",value:(e=>{if(null==e)return"";const a=e%60;return`${Math.floor(e/60).toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`})(e.timeValue),onChange:a=>n?.({...e,timeValue:o(a.target.value)}),placeholder:e.placeholder,disabled:i})]})}function ky({field:e,readOnly:r,onChange:n}){const i=e.config,s=i?.multiple??!1,l=r||e.readOnly,[d,c]=o(""),u=e.itemsValue||[],m=()=>{if(!d.trim())return;const a={value:crypto.randomUUID(),text:d.trim()};n?.({...e,itemsValue:[...u,a]}),c("")};if(!s){const r=u[0]?.text||"";return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),t("div",{className:"flex items-center gap-2",children:[a(qi,{type:"url",value:r,onChange:a=>(a=>{const t={value:a,text:a};n?.({...e,itemsValue:a?[t]:[]})})(a.target.value),placeholder:e.placeholder||"https://",disabled:l}),r&&a($i,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:a("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:a(pe,{className:"h-4 w-4"})})})]})]})}return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),!l&&t("div",{className:"flex items-center gap-2",children:[a(qi,{type:"url",value:d,onChange:e=>c(e.target.value),placeholder:e.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),a($i,{variant:"outline",size:"icon",onClick:m,disabled:!d.trim(),className:"flex-shrink-0",children:a(Q,{className:"h-4 w-4"})})]}),u.length>0&&a("div",{className:"space-y-1",children:u.map((r,i)=>t("div",{className:"flex items-center gap-2 text-sm",children:[a("a",{href:r.text,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline truncate flex-1",children:r.text}),!l&&a($i,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>(a=>{const t=u.filter((e,t)=>t!==a);n?.({...e,itemsValue:t})})(i),children:a(H,{className:"h-3 w-3"})})]},r.value))})]})}function Sy({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=null!=i?.decimals&&i.decimals>0?(1/Math.pow(10,i.decimals)).toString():"1";return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a(qi,{type:"number",value:e.numberValue??"",onChange:a=>(a=>{if(""===a)return void n?.({...e,numberValue:void 0});const t=parseFloat(a);isNaN(t)||n?.({...e,numberValue:t})})(a.target.value),placeholder:e.placeholder,disabled:o,min:i?.min,max:i?.max,step:s}),null!=i?.min&&null!=i?.max&&t("p",{className:"text-xs text-muted-foreground",children:["Min: ",i.min," | Max: ",i.max]})]})}function Ay({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=i?.viewMode??my.dropdown,l=i?.data?.filter(a=>!1!==a.isActive||e.itemsValue?.some(e=>e.value===a.value))||[],d=e.itemsValue?.[0]?.value||"",c=a=>{const t=l.find(e=>e.value===a);if(!t)return;const r={value:t.value,text:t.text,isActive:t.isActive};n?.({...e,itemsValue:[r]})};return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),s===my.dropdown&&t(Mo,{value:d,onValueChange:c,disabled:o,children:[a(Fo,{children:a(zo,{placeholder:e.placeholder||"Selecione..."})}),a(Oo,{children:l.map(e=>t($o,{value:e.value,children:[e.text,!1===e.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},e.value))})]}),(s===my.radio||s===my.buttons)&&a(Rm,{value:d,onValueChange:c,disabled:o,className:Fi(s===my.buttons?"flex flex-wrap gap-2":"space-y-2"),children:l.map(r=>t("div",{className:"flex items-center gap-2",children:[a(Mm,{value:r.value,id:`${e.id}-${r.value}`}),t(Hi,{htmlFor:`${e.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))}),!o&&d&&!e.required&&a("button",{type:"button",onClick:()=>{n?.({...e,itemsValue:[]})},className:"text-xs text-muted-foreground hover:text-foreground underline",children:"Limpar seleção"})]})}function Ey({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=i?.viewMode??my.dropdown,l=i?.data?.filter(a=>!1!==a.isActive||e.itemsValue?.some(e=>e.value===a.value))||[],d=new Set(e.itemsValue?.map(e=>e.value)||[]);return t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),(e.itemsValue?.length??0)>0&&a("div",{className:"flex flex-wrap gap-1.5",children:e.itemsValue.map(r=>t(Go,{variant:"secondary",className:"gap-1 pr-1",children:[a("span",{className:"text-xs",children:r.text}),!o&&a("button",{type:"button",onClick:()=>(a=>{const t=(e.itemsValue||[]).filter(e=>e.value!==a);n?.({...e,itemsValue:t})})(r.value),className:"rounded-full p-0.5 hover:bg-muted-foreground/20",children:a(E,{className:"h-3 w-3"})})]},r.value))}),!o&&a("div",{className:Fi(s===my.checkbox?"space-y-2":"grid grid-cols-2 gap-2 border rounded-md p-3 max-h-48 overflow-y-auto"),children:l.map(r=>t("div",{className:"flex items-center gap-2",children:[a(qo,{id:`${e.id}-${r.value}`,checked:d.has(r.value),onCheckedChange:()=>(a=>{const t=e.itemsValue||[],r=t.some(e=>e.value===a.value)?t.filter(e=>e.value!==a.value):[...t,{value:a.value,text:a.text,isActive:a.isActive}];n?.({...e,itemsValue:r})})(r),disabled:o}),t(Hi,{htmlFor:`${e.id}-${r.value}`,className:"text-sm font-normal cursor-pointer",children:[r.text,!1===r.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]})]},r.value))})]})}function Dy({field:e,readOnly:r,onChange:n}){const i=e.config,o=r||e.readOnly,s=i?.questions||[],l=i?.options||[],d=e.questionsValue||[];return 0===s.length||0===l.length?t("div",{className:"space-y-1.5",children:[a(Hi,{children:e.name}),a("p",{className:"text-xs text-muted-foreground",children:"Nenhuma questão configurada"})]}):t("div",{className:"space-y-1.5",children:[a(Hi,{className:Fi(e.required&&"after:content-['*'] after:text-destructive after:ml-0.5"),children:e.name}),e.description&&a("p",{className:"text-xs text-muted-foreground",children:e.description}),a("div",{className:"border rounded-md overflow-x-auto",children:t("table",{className:"w-full text-sm",children:[a("thead",{children:t("tr",{className:"border-b bg-muted/50",children:[a("th",{className:"text-left p-2 font-medium min-w-[150px]",children:"Pergunta"}),l.map(e=>a("th",{className:"text-center p-2 font-medium min-w-[80px]",children:e.text},e.value))]})}),a("tbody",{children:s.map((r,i)=>t("tr",{className:Fi(i<s.length-1&&"border-b"),children:[a("td",{className:"p-2 text-muted-foreground",children:r.text}),l.map(t=>{return a("td",{className:"text-center p-2",children:a(Rm,{value:(i=r.value,d.find(e=>e.questionValue===i)?.optionValue||""),onValueChange:a=>((a,t,r,i)=>{const o={questionValue:a,questionText:t,optionValue:r,optionText:i},s=d.filter(e=>e.questionValue!==a);s.push(o),n?.({...e,questionsValue:s})})(r.value,r.text,a,t.text),disabled:o,className:"flex justify-center",children:a(Mm,{value:t.value,id:`${e.id}-${r.value}-${t.value}`})})},t.value);var i})]},r.value))})]})})]})}function Py({fields:e,readOnly:t=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:i}){const o=l(a=>{if(i?.(a),n){const t=e.map(e=>e.id===a.id?a:e);n(t)}},[e,n,i]),s=e.filter(e=>vy(e,r));return 0===s.length?null:a("div",{className:"space-y-4",children:s.map(e=>a(Iy,{field:e,readOnly:t,onChange:o},e.id))})}function Iy({field:e,readOnly:t,onChange:r}){const n={field:e,readOnly:t,onChange:r};switch(e.type){case cy.readOnlyText:return a(Ny,{...n});case cy.text:return a(wy,{...n});case cy.date:return a(_y,{...n});case cy.time:return a(Cy,{...n});case cy.url:return a(ky,{...n});case cy.number:return a(Sy,{...n});case cy.singleSelection:return a(Ay,{...n});case cy.multiSelection:return a(Ey,{...n});case cy.questions:return a(Dy,{...n});default:return null}}function Ty({queryParams:e,events:r,softwares:n,users:i=[],permissions:s={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:d=!1,onFilter:c,onReset:u,onExport:m,onSoftwareChange:p}){const[h,f]=o(e.softwareId),[g,v]=o(e.eventId),[b,x]=o(e.userId||"all"),[y,N]=o(Ry(e.startDate)),[w,_]=o(Ry(e.endDate)),C=l(e=>{const a=parseInt(e);f(a),p?.(a)},[p]),k=l(()=>{c({...e,softwareId:h,eventId:g,userId:"all"===b?void 0:b,startDate:new Date(y),endDate:new Date(w),software:n.find(e=>e.id===h)?.software||e.software,event:r.find(e=>e.id===g)?.name||e.event})},[e,h,g,b,y,w,n,r,c]),S=l(()=>{const a=new Date;a.setHours(0,0,0,0),N(Ry(a)),_(Ry(a)),v(e.eventId),s.viewAllEvents&&x("all"),u?.()},[e.eventId,s.viewAllEvents,u]),A=s.viewOnlyMyEvents&&!s.viewAllEvents,E=h&&g&&y&&w;return t("div",{className:"flex flex-wrap items-end gap-3 rounded-lg border border-border bg-card p-3",children:[t("div",{className:"flex flex-col gap-1 min-w-[180px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Módulo *"}),t(Mo,{value:String(h),onValueChange:C,disabled:d,children:[a(Fo,{className:"h-8 text-xs",children:a(zo,{placeholder:"Selecione..."})}),a(Oo,{children:n.map(e=>a($o,{value:String(e.id),className:"text-xs",children:e.translation},e.id))})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Evento *"}),t(Mo,{value:String(g),onValueChange:e=>v(parseInt(e)),disabled:d,children:[a(Fo,{className:"h-8 text-xs",children:a(zo,{placeholder:"Selecione..."})}),a(Oo,{children:r.map(e=>a($o,{value:String(e.id),className:"text-xs",children:e.translation},e.id))})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Usuário *"}),t(Mo,{value:b,onValueChange:x,disabled:d||A,children:[a(Fo,{className:"h-8 text-xs",children:a(zo,{placeholder:"Selecione..."})}),t(Oo,{children:[a($o,{value:"all",className:"text-xs",children:"Todos"}),i.map(e=>a($o,{value:e.id,className:"text-xs",children:e.name},e.id))]})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"De *"}),a(qi,{type:"date",value:y,onChange:e=>N(e.target.value),className:"h-8 text-xs",max:w,disabled:d})]}),t("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[a(Hi,{className:"text-xs text-muted-foreground",children:"Até *"}),a(qi,{type:"date",value:w,onChange:e=>_(e.target.value),className:"h-8 text-xs",min:y,disabled:d})]}),t("div",{className:"flex items-center gap-2 ml-auto",children:[t($i,{variant:"outline",size:"sm",onClick:S,disabled:d,children:[a(Aa,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),s.download&&m&&t($i,{variant:"outline",size:"sm",onClick:()=>m("xlsx"),disabled:d,children:[a(Je,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),t($i,{size:"sm",onClick:k,disabled:d||!E,children:[a(Ea,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function Ry(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function My(e,a,t,r="Anônimo"){return e.map(e=>({...e,translatedSoftware:zy(e.software,t),user:e.userEmail||e.userName||r,translatedEvent:Ly(e.eventName,a),date:new Date(e.dateTime)})).sort((e,a)=>(a.date?.getTime()??0)-(e.date?.getTime()??0))}function Ly(e,a){const t=a.find(a=>a.name===e);return t?.translation||e}function zy(e,a){const t=e.includes(".")?e.split(".").pop():e,r=a.find(e=>e.software===t);return r?.translation||t}function Fy(e,a){const t=[],r={...qy,...a?.labels},n=e.eventName;t.push({name:r.event,value:n});const i=e.entities?.[0];if(i&&(t.push({name:r.entityName,value:Uy(i)}),i.description&&t.push({name:r.description,value:i.description}),i.justification&&t.push({name:r.justification,value:i.justification}),i.statusName&&t.push({name:r.status,value:i.statusName}),i.equipmentType&&t.push({name:r.type,value:i.equipmentType}),i.extra?.length)){[...new Set(i.extra.map(e=>e.property))].forEach(e=>{const a=i.extra.filter(a=>a.property===e).map(e=>e.value||"").join(", ");t.push({name:$y(e),value:a})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const i=jy(e,n,a?.translateProperty),o=Oy(e,null,n,r,a);o&&t.push({name:i,value:o})})}),e.entities?.forEach(e=>{if(e.association?.length){const a=e.association.filter(e=>""!==e.id).map(e=>{const a=Uy(e);return`(${e.softwareName||e.type}) ${a}`});a.length&&t.push({name:r.references,value:a.join(", ")})}}),i?.isElectronicSigned&&t.push({name:r.security,value:"🛡️ "+r.electronicSigned}),t.push({name:r.accomplishedBy,value:e.userName?`${e.userName} (${e.userEmail})`:e.userEmail});const o=a?.formatDate?a.formatDate(e.dateTime):Vy(e.dateTime);return t.push({name:r.accomplishedIn,value:o}),t}function Uy(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function jy(e,a,t){if(e.propertyCustomName)return e.propertyCustomName;const r=$y(e.property);return t?t(a,r):r}function Oy(e,a,t,r,n){if(e.propertyResource||(e.propertyResource=a?`${a.propertyResource}.${e.property}`:e.property),e.children?.length){if(e.newValue){const a=jy(e,t,n?.translateProperty),i=function(e,a){switch(e.state){case"Added":return a.stateAdded;case"Modified":return e.children?.some(e=>"Removed"===e.property)?a.stateRemoved:a.stateModified;default:return""}}(e,r);let o=`${a}: "${By(e,"newValue",r,n)}" ${i}`;const s=e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Oy(a,e,t,r,n)));return s.some(Boolean)&&(o+="\n"+s.filter(Boolean).join("\n")),o}return e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Oy(a,e,t,r,n))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const i=By(e,"oldValue",r,n),o=By(e,"newValue",r,n);return`${a?jy(e,t,n?.translateProperty)+": ":""}${r.changedFrom} "${i}" ${r.changedTo} "${o}"`}const i=By(e,"newValue",r,n);return a?`${jy(e,t,n?.translateProperty)}: ${i}`:i}function By(e,a,t,r){const n=e[a];return null==n||""===n?"Modified"===e.state||"Added"===e.state||"Unchanged"===e.state?t.uninformed:"":"string"==typeof n&&function(e){if("string"!=typeof e)return!1;if(!/^\d{4}[-/]\d{2}[-/]\d{2}/.test(e))return!1;const a=new Date(e);return!isNaN(a.getTime())}(n)?r?.formatDate?r.formatDate(n):Vy(n):String(n)}function $y(e){return e.replace(/([A-Z])/g,(e,a,t)=>`${t>0?"-":""}${a.toLowerCase()}`)}function Vy(e){try{return new Date(e).toLocaleString()}catch{return e}}(uy=cy||(cy={}))[uy.readOnlyText=1]="readOnlyText",uy[uy.text=2]="text",uy[uy.date=3]="date",uy[uy.time=4]="time",uy[uy.url=5]="url",uy[uy.number=6]="number",uy[uy.singleSelection=7]="singleSelection",uy[uy.multiSelection=8]="multiSelection",uy[uy.questions=9]="questions",(py=my||(my={}))[py.dropdown=1]="dropdown",py[py.buttons=2]="buttons",py[py.radio=3]="radio",py[py.checkbox=4]="checkbox",(fy=hy||(hy={}))[fy.custom=1]="custom",fy[fy.users=2]="users",fy[fy.usersLists=3]="usersLists";const qy={event:"Evento",entityName:"Item",description:e.t("audit_description"),justification:"Justificativa",status:"Status",type:"Tipo",references:e.t("audit_references"),security:e.t("audit_security"),electronicSigned:e.t("audit_esign"),accomplishedBy:"Realizado por",accomplishedIn:"Realizado em",changedFrom:"de",changedTo:"para",uninformed:e.t("audit_not_informed"),stateAdded:"(adicionado)",stateModified:"(modificado)",stateRemoved:"(removido)"};function Wy({documentId:e,onFetchDetails:r,onClose:n,labels:i,translateProperty:s,translatePropertyValue:d,formatDate:c}){const[u,p]=o(!1),[h,f]=o([]),[g,v]=o(null),b=l(async e=>{p(!0),v(null);try{const a=Fy(await r(e),{translateProperty:s,translatePropertyValue:d,formatDate:c,labels:i});f(a)}catch(a){v("Erro ao carregar detalhes da trilha de auditoria."),f([])}finally{p(!1)}},[r,s,d,c,i]);return m(()=>{e&&b(e)},[e,b]),e?t("div",{className:"flex flex-col h-full bg-background",children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border bg-muted/30",children:[a("h3",{className:"text-sm font-semibold text-foreground",children:"Detalhes da Auditoria"}),a($i,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:n,children:a(E,{className:"h-4 w-4"})})]}),a("div",{className:"flex-1 overflow-y-auto",children:u?t("div",{className:"flex items-center justify-center p-6",children:[a(Yo,{size:"md"}),a("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando detalhes..."})]}):g?a("div",{className:"p-6 text-sm text-destructive",children:g}):a("table",{className:"w-full text-xs",children:a("tbody",{children:h.map((e,r)=>t("tr",{className:r%2==0?"bg-background":"bg-muted/20",children:[a("td",{className:"px-4 py-2.5 font-semibold text-foreground whitespace-nowrap align-top w-[180px] border-b border-border/50",children:e.name}),a("td",{className:"px-4 py-2.5 text-muted-foreground break-words border-b border-border/50",children:a("span",{dangerouslySetInnerHTML:{__html:e.value.replace(/\n/g,"<br />")}})})]},r))})})})]}):null}function Hy({title:r,softwares:n,softwareId:i,permissions:s={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},callbacks:d,limit:c=2e3,currentUserId:p,labels:h,formatDate:f,anonymousLabel:g=e.t("anonymous")}){const{t:v}=Ga();r??v("audit_trail");const[b,x]=o(!0),[y,N]=o([]),[w,_]=o([]),[C,k]=o([]),[S,A]=o(null),[E,D]=o(!1),P=u(null),I=new Date;I.setHours(0,0,0,0);const[T,R]=o({software:n.find(e=>e.id===i)?.software||"",softwareId:i,event:"All",eventId:1,startDate:I,endDate:I,limit:c,softwares:n,userId:s.viewOnlyMyEvents&&!s.viewAllEvents?p:void 0});m(()=>{(async()=>{x(!0);try{const[e,a]=await Promise.all([d.onFetchEvents(T.softwareId),d.onFetchUsers?.()??Promise.resolve([])]);_(e),k(a),await M(T,e)}catch(e){}finally{x(!1)}})()},[]);const M=l(async(e,a)=>{try{const t=My((await d.onFetchTrails(e)).data,a||w,n,g);N(t)}catch(t){}},[d,w,n,g]),L=l(async e=>{x(!0),R(e);try{await M(e)}finally{x(!1)}},[M]),z=l(async e=>{try{const a=await d.onFetchEvents(e);_(a)}catch(a){}},[d]),F=l(e=>{A(e.documentId),D(!0)},[]),U=l(()=>{D(!1),A(null)},[]),j=l(async()=>{const e={...T,startDate:I,endDate:I,eventId:1,userId:s.viewAllEvents?void 0:p};R(e),x(!0);try{await M(e)}finally{x(!1)}},[T,M]),O=l(e=>{d.onExport?.(e,y)},[d,y]),B=l(e=>{try{return new Date(e).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return e}},[]);return t("div",{className:"flex flex-col h-full",children:[a("div",{className:"p-3",children:a(Ty,{queryParams:T,events:w,softwares:n,users:C,permissions:s,isLoading:b,onFilter:L,onReset:j,onExport:s.download?O:void 0,onSoftwareChange:z})}),t("div",{className:"flex flex-1 min-h-0 relative",children:[t("div",{className:Fi("flex-1 overflow-auto transition-all duration-300",E?"mr-[400px]":""),children:[b?t("div",{className:"flex items-center justify-center h-64",children:[a(Yo,{size:"md"}),a("span",{className:"ml-2 text-sm text-muted-foreground",children:"Carregando trilha de auditoria..."})]}):0===y.length?t("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[a(Be,{className:"h-12 w-12 mb-3 opacity-30"}),a("p",{className:"text-sm",children:"Nenhum registro encontrado"}),a("p",{className:"text-xs mt-1",children:"Ajuste os filtros e tente novamente"})]}):t("table",{className:"w-full text-xs border-collapse",children:[a("thead",{className:"sticky top-0 z-10",children:t("tr",{className:"bg-muted/60 border-b border-border",children:[a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(Da,{className:"h-3 w-3"}),"Módulo"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(We,{className:"h-3 w-3"}),"Data"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(ge,{className:"h-3 w-3"}),"Usuário"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:t("div",{className:"flex items-center gap-1.5",children:[a(Be,{className:"h-3 w-3"}),"Evento"]})}),a("th",{className:"px-3 py-2 text-left font-medium text-muted-foreground",children:"Item"}),a("th",{className:"px-3 py-2 w-10"})]})}),a("tbody",{children:y.map((e,r)=>t("tr",{onClick:()=>F(e),className:Fi("cursor-pointer border-b border-border/50 transition-colors","hover:bg-accent/50",S===e.documentId&&"bg-accent",r%2==0?"bg-background":"bg-muted/10"),children:[a("td",{className:"px-3 py-2 text-foreground",children:e.translatedSoftware}),a("td",{className:"px-3 py-2 text-muted-foreground whitespace-nowrap",children:e.date?B(e.date.toISOString()):"—"}),a("td",{className:"px-3 py-2 text-foreground",children:e.user}),a("td",{className:"px-3 py-2 text-foreground",children:e.translatedEvent}),a("td",{className:"px-3 py-2 text-foreground truncate max-w-[200px]",title:e.entityName,children:e.entityName}),a("td",{className:"px-3 py-2",children:a(Ce,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},e.documentId||r))})]}),!b&&y.length>0&&t("div",{className:"px-3 py-2 text-xs text-muted-foreground border-t border-border bg-muted/20",children:[y.length," registro",1!==y.length?"s":""]})]}),a("div",{ref:P,className:Fi("fixed right-0 top-0 h-full w-[400px] border-l border-border bg-background shadow-lg z-30","transition-transform duration-300 ease-in-out",E?"translate-x-0":"translate-x-full"),children:E&&a(Wy,{documentId:S,onFetchDetails:d.onFetchDetails,onClose:U,labels:h,translateProperty:d.translateProperty,translatePropertyValue:d.translatePropertyValue,formatDate:f||B})})]})]})}function Gy({open:r,onOpenChange:n,returnSteps:i,initialObservation:s="",title:l=e.t("approval_execute_action"),descriptions:d=[],setDefaultApproverOnInit:c=!0,onSubmit:u}){const[m,p]=o(!0),[h,f]=o(c&&i.length>0?i[0].id:null),[g,v]=o(s),b=e=>{p(e),e&&!c?f(null):!e&&!c&&i.length>0&&f(i[0].id)},x=g!==s||!m;return a(mo,{open:r,onOpenChange:n,children:t(bo,{className:"sm:max-w-[480px]",variant:"form",isDirty:x,children:[a(xo,{children:a(wo,{children:l})}),t("div",{className:"space-y-4",children:[d.length>0&&a("div",{className:"space-y-1 text-sm text-muted-foreground",children:d.map((e,t)=>a("p",{dangerouslySetInnerHTML:{__html:e}},t))}),t("div",{className:"flex gap-4",children:[t("label",{className:"flex items-center gap-2 cursor-pointer",children:[a("input",{type:"radio",name:"approved",checked:m,onChange:()=>b(!0),className:"accent-primary"}),a("span",{className:"text-sm",children:e.t("approval_approve")})]}),t("label",{className:"flex items-center gap-2 cursor-pointer",children:[a("input",{type:"radio",name:"approved",checked:!m,onChange:()=>b(!1),className:"accent-primary"}),a("span",{className:"text-sm",children:e.t("approval_reprove_radio")})]})]}),t("div",{className:"space-y-1.5",children:[a(Hi,{children:"Etapa"}),t(Mo,{value:h??void 0,onValueChange:f,disabled:m,children:[a(Fo,{children:a(zo,{placeholder:e.t("approval_select_step")})}),a(Oo,{children:i.map(e=>a($o,{value:e.id,children:e.name},e.id))})]})]}),t("div",{className:"space-y-1.5",children:[a(Hi,{children:e.t("approval_opinion")}),a(Wo,{value:g,onChange:e=>v(e.target.value),maxLength:4e3,rows:4,autoFocus:!0}),t("p",{className:"text-xs text-muted-foreground text-right",children:[g.length,"/",4e3]})]})]}),t(No,{children:[a($i,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),a($i,{onClick:()=>{if(!g.trim())return void C.error("Formulário inválido. Preencha todos os campos obrigatórios.");const e=m?null:i.find(e=>e.id===h);u({approved:m,returnStepId:m?null:h,returnType:e?.type??null,observation:g})},disabled:!x,children:"Concluir"})]})]})})}function Ky({open:e,onOpenChange:r,approvers:n,isLoading:i=!1,ignoreUserIds:l=[],onSubmit:d}){const{t:c}=Ga(),[u,m]=o(null),p=s(()=>{const e=new Set(l);return n.filter(a=>!e.has(a.id))},[n,l]),h=s(()=>p.map(e=>({value:e.id,label:e.name})),[p]);return a(mo,{open:e,onOpenChange:r,children:t(bo,{className:"sm:max-w-[450px]",variant:"form",isDirty:!!u,children:[a(xo,{children:a(wo,{children:c("approval_select_approver")})}),a(Qo,{isLoading:i,type:"spinner",children:a("div",{className:"space-y-4",children:a(Rs,{options:h,value:u??void 0,onValueChange:e=>m("string"==typeof e?e:e?.[0]??null),placeholder:c("approval_select_approver_placeholder"),searchPlaceholder:c("approval_search_approver")})})}),t(No,{children:[a($i,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),a($i,{onClick:()=>{if(!u)return;const e=p.find(e=>e.id===u);e&&d(e)},disabled:!u||i,children:"Concluir"})]})]})})}function Yy(e){const{t:a}=Ga();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function Qy({text:e,maxLength:r=130}){const{t:n}=Ga(),[i,s]=o(!1);return e.length<=r?a("span",{children:e}):t("span",{children:[i?e:`${e.substring(0,r)}... `,a("button",{className:"text-primary hover:underline text-sm cursor-pointer",onClick:()=>s(!i),children:n(i?"approval_read_less":"approval_read_more")})]})}function Xy({approver:e}){if(1===e.type&&e.approverId)return t(bu,{className:"h-9 w-9 shrink-0",children:[a(xu,{src:e.photoUrl,alt:e.name}),a(yu,{className:"text-xs",children:e.name?.substring(0,2).toUpperCase()})]});const r=2===e.type?Ze:3===e.type?Pa:ge;return a("div",{className:"h-9 w-9 rounded-full bg-muted-foreground/30 flex items-center justify-center shrink-0",children:a(r,{className:"h-4 w-4 text-background"})})}function Jy({approver:e}){return e.date?t("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-green-500/10 text-foreground",children:[a(le,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:Yy(e.date)}),1!==e.type&&e.approvedUsername&&t("span",{className:"text-xs text-muted-foreground",children:["por ",e.approvedUsername]})]}):e.returnDate?t("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-red-500/10 text-foreground",children:[a(Ia,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:Yy(e.returnDate)})]}):t("span",{className:"inline-flex items-center gap-1 text-xs rounded px-2 py-0.5 bg-muted text-muted-foreground",children:[a(O,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function Zy({approver:e}){const{t:r}=Ga(),n=1!==e.type||e.approverId?e.name:"A definir";return t("div",{children:[2===e.type&&a("p",{className:"text-xs text-muted-foreground",children:r("approval_user_group")}),3===e.type&&a("p",{className:"text-xs text-muted-foreground",children:"Local"}),a("p",{className:"text-sm font-medium break-words",children:n}),a(Jy,{approver:e})]})}function eN({config:e,isLoading:r=!1,onClose:n,onApprove:i,onDefineApprover:s,onRefreshSteps:d,availableApprovers:c=[],isLoadingApprovers:u=!1}){const{t:m}=Ga(),[p,h]=o(!1),[f,g]=o(!1),[v,b]=o(""),[x,y]=o(""),[N,w]=o(!1),[_,C]=o(""),k=r||p,S=l((e,a)=>{b(e),y(a??""),g(!0)},[]),A=l(async a=>{g(!1),h(!0);if(!await i(e.associationId,{stepApproverId:v,...a}))return S(v,a.observation),void h(!1);n(),h(!1)},[e.associationId,v,i,n,S]),D=l(e=>{C(e),w(!0)},[]),P=l(async a=>{w(!1),h(!0),await s(e.associationId,_,a),await(d?.(e.associationId)),h(!1)},[e.associationId,_,s,d]),I=e.approvalFlowSteps.find(e=>e.isCurrentStep)?.approvers.filter(e=>1===e.type&&e.approverId).map(e=>e.approverId)??[],T=(a,t)=>e.canApprove&&a.isCurrentStep&&t.approverId&&!t.date&&t.canApprove,R=(a,t)=>!e.flowReproved&&a.isCurrentStep&&1===t.type&&t.canApprove&&(!t.approverId||t.isToBeDefined);return t("div",{className:"w-[550px] max-w-[900px] min-w-[400px] h-full flex flex-col bg-background",children:[t("div",{className:"shrink-0 shadow-sm px-1 py-2 flex items-center gap-1 border-l-4",style:{borderLeftColor:e.color},children:[a($i,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0",children:a(E,{className:"h-5 w-5"})}),a("span",{className:"text-lg font-medium",children:e.title})]}),k?a(Qo,{isLoading:!0,type:"spinner",className:"flex-1",children:a("div",{})}):t("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[e.approvalFlowInfo.length>0&&a("div",{className:"space-y-1",children:e.approvalFlowInfo.map((e,t)=>a("div",{className:Fi("flex items-center gap-1.5 text-sm",e.color&&"rounded-lg px-2 py-1"),style:e.color?{color:e.color,backgroundColor:e.backgroundColor}:void 0,children:e.title?`${e.title}: ${e.value}`:e.value},t))}),a("hr",{className:"border-border"}),e.approvalFlowSteps.map(r=>t("div",{className:Fi("space-y-2",(!r.isCurrentStep||e.flowReproved)&&"opacity-50"),children:[t("p",{className:"font-semibold text-sm",children:[r.index,". Etapa: ",r.name]}),r.description&&a("p",{className:"text-sm text-muted-foreground break-words",children:a(Qy,{text:r.description})}),r.returnDate&&t("div",{className:"border-y border-border py-3 mt-3 space-y-1",children:[t("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-xs rounded px-1.5 py-0.5 bg-red-500/10 text-red-600",children:"Retorno de etapa"}),t("span",{className:"text-xs text-muted-foreground",children:[r.returnUserName," em ",Yy(r.returnDate)]})]}),r.returnObservation&&a("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:a(Qy,{text:r.returnObservation})})]}),r.approvers.map(e=>t("div",{className:"p-2 space-y-1",children:[t("div",{className:"flex items-center justify-between gap-2",children:[t("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[a(Xy,{approver:e}),a(Zy,{approver:e})]}),T(r,e)&&a($i,{size:"sm",onClick:()=>S(e.id),children:"Aprovar"}),R(r,e)&&a($i,{size:"sm",variant:"outline",onClick:()=>D(e.id),children:"Selecionar"})]}),e.observation&&a("p",{className:"text-sm text-muted-foreground break-words ml-11",children:a(Qy,{text:e.observation})}),e.returnObservation&&a("p",{className:"text-sm text-muted-foreground break-words ml-11",children:a(Qy,{text:e.returnObservation})})]},e.id))]},r.id))]}),a(Gy,{open:f,onOpenChange:g,returnSteps:e.returnSteps,initialObservation:x,title:e.approveDialogTitle,descriptions:e.approveDialogDescriptions,setDefaultApproverOnInit:e.approveDialogSetDefaultApproverOnInit,onSubmit:A}),a(Ky,{open:N,onOpenChange:w,approvers:c,isLoading:u,ignoreUserIds:I,onSubmit:P})]})}var aN,tN;function rN({users:e,value:r,onChange:n,disabled:i=!1,placeholder:d="Buscar membro da equipe...",confirmRemoval:c=!0,confirmTitle:u,confirmMessage:m="Tem certeza que deseja remover este membro da equipe?",emptyMessage:p,className:h}){const{t:f}=Ga(),g=u??f("leadership_remove_team"),v=p??f("leadership_no_members"),[b,x]=o(""),[y,N]=o(!1),[w,_]=o(null),C=s(()=>new Set(r),[r]),k=s(()=>e.filter(e=>C.has(e.id)),[e,C]),S=s(()=>e.filter(e=>!C.has(e.id)).map(e=>({value:e.id,label:e.name})),[e,C]),A=l(e=>{e&&!C.has(e)&&(n([...r,e]),x(""))},[r,n,C]),D=l(e=>{c?(_(e),N(!0)):n(r.filter(a=>a!==e))},[r,n,c]),P=l(()=>{w&&n(r.filter(e=>e!==w)),N(!1),_(null)},[w,r,n]);return t("div",{className:Fi("space-y-3",h),children:[a("div",{className:"flex items-start gap-3",children:a("div",{className:"flex-1",children:a(Rs,{options:S,value:b,onValueChange:e=>{const a="string"==typeof e?e:e?.[0]??"";x(a),a&&A(a)},placeholder:d,searchPlaceholder:"Buscar...",disabled:i})})}),t("div",{className:"flex items-center gap-2",children:[a("span",{className:"text-sm text-muted-foreground",children:"Selecionados"}),a("span",{className:"text-xs bg-muted text-muted-foreground rounded-full px-2 py-0.5 font-medium",children:k.length})]}),k.length>0?a("div",{className:"space-y-2",children:k.map(e=>t("div",{className:"flex items-center border border-border rounded-lg p-2 gap-3",children:[t(bu,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(xu,{src:e.avatar,alt:e.name}),a(yu,{className:"text-xs",children:e.name?.substring(0,2).toUpperCase()})]}),a("div",{className:"flex-1 min-w-0",children:a("p",{className:"text-sm font-medium truncate",title:e.name,dangerouslySetInnerHTML:{__html:e.title||e.name}})}),t("div",{className:"flex items-center gap-2 shrink-0 text-xs text-muted-foreground",children:[e.roleName&&t("span",{className:"flex items-center gap-1",children:[a(Ta,{className:"h-3.5 w-3.5"}),a("span",{className:"truncate max-w-[120px]",children:e.roleName})]}),e.placeName&&t("span",{className:"flex items-center gap-1",children:[a(Pa,{className:"h-3.5 w-3.5"}),a("span",{className:"truncate max-w-[120px]",children:e.placeName})]}),a("button",{type:"button",className:Fi("text-muted-foreground hover:text-destructive transition-colors",i&&"opacity-50 pointer-events-none"),onClick:()=>!i&&D(e.id),title:f("remove"),children:a(E,{className:"h-4 w-4"})})]})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[a(ge,{className:"h-12 w-12 mb-2 opacity-30"}),a("p",{className:"text-sm",children:v})]}),a(mo,{open:y,onOpenChange:N,children:t(bo,{className:"sm:max-w-[400px]",children:[a(xo,{children:a(wo,{children:g})}),a("p",{className:"text-sm text-muted-foreground",children:m}),t(No,{children:[a($i,{variant:"ghost",onClick:()=>N(!1),children:"Cancelar"}),a($i,{variant:"destructive",onClick:P,children:"Remover"})]})]})})]})}(tN=aN||(aN={}))[tN.ApprovalFlow=1]="ApprovalFlow",tN[tN.Association=2]="Association";export{pr as AUTH_CONFIG,nu as AccessDeniedDialog,hu as Accordion,vu as AccordionContent,fu as AccordionItem,gu as AccordionTrigger,Vi as ActionButton,Vi as ActionMenu,ld as ActionMenuItems,ry as ActionPlanAttachmentsTab,Jx as ActionPlanCommentsTab,Xx as ActionPlanCostTab,Bx as ActionPlanGeneralTab,ey as ActionPlanHistoryTab,iy as ActionPlanPage,Qx as ActionPlanPredecessorsTab,Gx as ActionPlanProgressDialog,Kx as ActionPlanProgressTab,Ox as ActionPlanStatusBadge,Xh as AggregationType,rc as Alert,ic as AlertDescription,eo as AlertDialog,co as AlertDialogAction,uo as AlertDialogCancel,no as AlertDialogContent,lo as AlertDialogDescription,oo as AlertDialogFooter,io as AlertDialogHeader,ro as AlertDialogOverlay,to as AlertDialogPortal,so as AlertDialogTitle,ao as AlertDialogTrigger,nc as AlertTitle,ec as AliasRedirect,Zd as AliasRouteGuard,Zh as AnalysisFunctionality,Yv as AppHeader,ob as AppLayout,ib as AppSidebar,aN as ApprovalFlowReturnStep,eN as ApprovalSidenav,Gy as ApproveDialog,Wy as AuditTrailDetails,Ty as AuditTrailFilter,Hy as AuditTrailPage,ol as AuthErrorInterceptor,Cl as AuthProvider,yl as AuthService,Rs as AutoComplete,bu as Avatar,yu as AvatarFallback,xu as AvatarImage,Go as Badge,Fd as BaseForm,mm as Blockquote,db as BodyContent,Nu as Breadcrumb,Au as BreadcrumbEllipsis,_u as BreadcrumbItem,Cu as BreadcrumbLink,wu as BreadcrumbList,ku as BreadcrumbPage,Su as BreadcrumbSeparator,Pg as BurndownPanel,$i as Button,Du as ButtonGroup,zx as CLOSED_STATUSES,hr as CRUD_CONFIG,Xf as CURRENCY_FIELDS,Pu as Calendar,oc as CallbackPage,Gi as Card,Xi as CardContent,Qi as CardDescription,Ji as CardFooter,Ki as CardHeader,jl as CardSkeleton,Yi as CardTitle,kg as CartesianPanel,Hp as ChartContainer,Qp as ChartLegend,Xp as ChartLegendContent,Gp as ChartStyle,Kp as ChartTooltip,Yp as ChartTooltipContent,qo as Checkbox,Sc as Collapsible,Ec as CollapsibleContent,Ac as CollapsibleTrigger,Ed as ColorPicker,_d as ColumnSettingsPopover,js as ComboTree,Rs as Combobox,Ns as Command,ws as CommandDialog,ks as CommandEmpty,Ss as CommandGroup,_s as CommandInput,Es as CommandItem,Cs as CommandList,As as CommandSeparator,Ds as CommandShortcut,lb as ContentContainer,Gl as ContextMenu,rd as ContextMenuCheckboxItem,ad as ContextMenuContent,Yl as ContextMenuGroup,td as ContextMenuItem,id as ContextMenuLabel,Ql as ContextMenuPortal,Jl as ContextMenuRadioGroup,nd as ContextMenuRadioItem,od as ContextMenuSeparator,sd as ContextMenuShortcut,Xl as ContextMenuSub,ed as ContextMenuSubContent,Zl as ContextMenuSubTrigger,Kl as ContextMenuTrigger,uu as CoreProviders,bd as CrudActionBar,Dv as CrudActionMenu,Av as CrudGrid,Wd as CrudPageInternal,jd as CrudPagination,Pv as CrudPrimitiveFilterBar,Ud as CrudPrimitivePagination,Ev as CrudPrimitiveTable,kd as CrudTable,Py as CustomFormFields,hx as D4SignWidget,Qf as DASHBOARD_STORAGE_KEYS,mi as DATETIME_FORMATS,Rx as DEFAULT_ACTION_TYPES,fi as DEFAULT_DATETIME_FORMAT,hi as DEFAULT_LOCALE,gi as DEFAULT_TIMEZONE,Qg as DashboardForm,Nf as DashboardFormTab,ef as DashboardFunctionality,Xg as DashboardGeneralView,Fg as DashboardGrid,kf as DashboardLanguage,qg as DashboardList,tf as DashboardListType,nf as DashboardPageTime,sf as DashboardPanelDimension,uf as DashboardPanelOrderBy,df as DashboardPanelOrderByType,pf as DashboardPanelPeriod,jg as DashboardPanelRenderer,ff as DashboardPanelType,_f as DashboardShareType,vf as DashboardUpdateTime,Og as DashboardView,xf as DashboardViewType,Pv as DataFilterBar,Iu as DataList,Ud as DataPagination,Ev as DataTable,Tu as DatePicker,mo as Dialog,yo as DialogBody,fo as DialogClose,bo as DialogContent,_o as DialogDescription,No as DialogFooter,xo as DialogHeader,go as DialogOverlay,ho as DialogPortal,wo as DialogTitle,po as DialogTrigger,fh as DialogWizard,vs as DisabledMenuItem,fx as DocumentSigner,Ru as Drawer,zu as DrawerClose,Uu as DrawerContent,$u as DrawerDescription,Ou as DrawerFooter,ju as DrawerHeader,Fu as DrawerOverlay,Lu as DrawerPortal,Bu as DrawerTitle,Mu as DrawerTrigger,Jo as DropdownMenu,ls as DropdownMenuCheckboxItem,os as DropdownMenuContent,es as DropdownMenuGroup,ss as DropdownMenuItem,cs as DropdownMenuLabel,as as DropdownMenuPortal,rs as DropdownMenuRadioGroup,ds as DropdownMenuRadioItem,us as DropdownMenuSeparator,ms as DropdownMenuShortcut,ts as DropdownMenuSub,is as DropdownMenuSubContent,ns as DropdownMenuSubTrigger,Zo as DropdownMenuTrigger,kx as EAttachmentItemStatus,cy as ECustomFormFieldType,my as EFieldViewMode,hy as ESelectionFieldDataSource,Nx as ETaskPlanAssociationType,xx as ETaskPlanPriority,vx as ETaskPlanStatus,_x as ETaskPlanTypeProgress,ph as ElectronicSignatureDialog,Wl as EllipsisText,fb as EmailService,ql as EmptyState,Rs as EntitySelect,Dc as ErrorBoundary,uh as ExportDialog,sh as ExportFormat,oy as FORBIDDEN_FILE_TYPES,wh as FilePrintType,yh as FileViewerType,qd as FilterBar,Co as Form,Io as FormControl,_y as FormDateField,To as FormDescription,So as FormField,Do as FormItem,Po as FormLabel,Ro as FormMessage,Ey as FormMultiSelectionField,Sy as FormNumericField,Dy as FormQuestionsField,Ay as FormSingleSelectionField,Ol as FormSkeleton,wy as FormTextField,Cy as FormTimeField,ky as FormUrlField,Wu as Grid,tm as H1,rm as H2,nm as H3,im as H4,Bl as HeaderSkeleton,Hu as HoverCard,Ku as HoverCardContent,Gu as HoverCardTrigger,Rd as IconPicker,Rh as IframeDialog,Jb as ImageEditor,Zb as ImageRenderer,um as InlineCode,qi as Input,Yu as InputGroup,Xu as InputGroupAddon,Zu as InputGroupButton,em as InputGroupInput,am as InputGroupTextarea,Jf as LINK_PROPERTIES,wr as LOGO_CONFIG,Hi as Label,lm as Large,sm as Lead,Ub as LeadershipDialog,Fb as LeadershipForm,Bb as LeadershipPage,pm as List,wg as ListPanel,Qo as LoadingState,Nc as LocaleProvider,sc as LoginPage,_r as MESSAGES,Kc as MODULES_DATA,Yf as MONTHS_MAP,vb as ManageAccessModal,Tg as MatrixRiskPanel,Af as MatrixViewType,Tp as Menubar,Up as MenubarCheckboxItem,zp as MenubarContent,Ep as MenubarGroup,Fp as MenubarItem,Op as MenubarLabel,Ap as MenubarMenu,Dp as MenubarPortal,Ip as MenubarRadioGroup,jp as MenubarRadioItem,Bp as MenubarSeparator,$p as MenubarShortcut,Pp as MenubarSub,Lp as MenubarSubContent,Mp as MenubarSubTrigger,Rp as MenubarTrigger,Sv as MindMap,tb as ModalStateProvider,ou as ModuleAccessGuard,Xc as ModuleGrid,su as ModuleOfferContent,Cc as ModuleProvider,Jc as ModulesContent,ru as ModulesDialog,Gc as ModulesFooterCards,Rs as MultiSelect,Oh as MultiselectPermissions,cm as Muted,hm as NavigationMenu,xm as NavigationMenuContent,wm as NavigationMenuIndicator,gm as NavigationMenuItem,ym as NavigationMenuLink,fm as NavigationMenuList,bm as NavigationMenuTrigger,Nm as NavigationMenuViewport,Vv as NavigationProvider,yg as NumericPanel,ih as OnboardingDialog,Th as OnlineEditorDialog,om as P,Lx as PRIORITIES,lr as PROD_PROJECT_ID,Fx as PROGRESS_ALLOWED_STATUSES,_m as PageBreadcrumb,dc as PageMetadataProvider,km as Pagination,Sm as PaginationContent,Im as PaginationEllipsis,Am as PaginationItem,Em as PaginationLink,Pm as PaginationNext,Dm as PaginationPrevious,Gf as PaletteType,fg as PanelError,hg as PanelHeader,Df as PanelItemsPerPanel,gg as PanelLoader,vg as PanelNoData,If as PanelSortType,Rf as PanelState,bg as PanelUnavailable,Dg as ParetoPanel,Ig as PerformancePanel,Eg as PiePanel,bb as PlaceCard,xb as PlacesList,Ff as PlanType,bs as Popover,ys as PopoverContent,xs as PopoverTrigger,Tm as Progress,Xd as ProtectedRoute,Nr as QUALIEX_CONFIG,yr as QUERY_KEYS,hl as QualiexEnrichmentService,sl as QualiexErrorInterceptor,zd as QualiexUserField,jf as QueriesContextType,Bf as QueriesShareType,Vf as QuickFilterDashboard,Rm as RadioGroup,Mm as RadioGroupItem,Ny as ReadOnlyTextField,Hh as ReportRequestList,Bh as ReportRequestStatus,Fm as ResizableHandle,zm as ResizablePanel,Lm as ResizablePanelGroup,ah as RichTextEditor,Wf as RiskCriticality,fr as SEARCH_CONFIG,Ax as STATUS_COLORS,Ix as STATUS_LABELS,Dx as STATUS_MAP,Ex as STATUS_TEXT_COLORS,ui as SUPPORTED_LOCALES,Dd as ScrollArea,Pd as ScrollBar,Mo as Select,Ky as SelectApproverDialog,Oo as SelectContent,Lo as SelectGroup,$o as SelectItem,Bo as SelectLabel,jo as SelectScrollDownButton,Uo as SelectScrollUpButton,Rs as SelectSearch,Vo as SelectSeparator,Fo as SelectTrigger,zo as SelectValue,Zi as Separator,Um as Sheet,Hm as SheetBody,Om as SheetClose,qm as SheetContent,Ym as SheetDescription,Gm as SheetFooter,Wm as SheetHeader,$m as SheetOverlay,Bm as SheetPortal,Km as SheetTitle,jm as SheetTrigger,ep as Sidebar,Xv as SidebarActionTrigger,lp as SidebarContent,op as SidebarFooter,dp as SidebarGroup,up as SidebarGroupAction,mp as SidebarGroupContent,cp as SidebarGroupLabel,sb as SidebarHeader,np as SidebarInput,rp as SidebarInset,Kv as SidebarLogo,pp as SidebarMenu,vp as SidebarMenuAction,bp as SidebarMenuBadge,gp as SidebarMenuButton,hp as SidebarMenuItem,xp as SidebarMenuSkeleton,yp as SidebarMenuSub,wp as SidebarMenuSubButton,Np as SidebarMenuSubItem,Zm as SidebarProvider,tp as SidebarRail,sp as SidebarSeparator,$l as SidebarSkeleton,ap as SidebarTrigger,gx as SignConfigForm,px as SignWidget,dy as SingleFileUpload,Ps as Skeleton,_p as Slider,dm as Small,Xo as SonnerToaster,Yo as Spinner,oh as SplitButton,Vd as Stack,Yh as StatusBadge,hh as StepSelector,hh as Stepper,Gh as StimulsoftViewer,Md as Switch,pi as TIMEZONES,Sp as TabPageContent,kp as TabPageHeader,Cp as TabPageLayout,Pl as Table,Tl as TableBody,Fl as TableCaption,zl as TableCell,Rl as TableFooter,Ll as TableHead,Il as TableHeader,Hl as TableResizeHandle,Ml as TableRow,dd as TableRowActions,Ul as TableSkeleton,Pc as Tabs,Rc as TabsContent,Ic as TabsList,Tc as TabsTrigger,rN as TeamSelector,Mh as TermsOfUseDialog,Lh as TermsOfUseViewer,Ng as TextPanel,Wo as Textarea,mh as Timepicker,Xo as Toaster,hd as Toggle,gd as ToggleGroup,vd as ToggleGroupItem,Ys as TokenManager,Os as TokenService,hs as Tooltip,gs as TooltipContent,ps as TooltipProvider,fs as TooltipTrigger,js as TreeSelect,Lv as TreeTable,Wl as TruncatedCell,xh as UpdatesNotification,Fh as UsersGroupsSelector,Qb as VideoEditor,Xb as VideoRenderer,Ph as ViewerDialog,Lf as VisualizationType,vc as addAppTranslations,nv as addChild,iv as addSibling,Sr as assets,Ho as badgeVariants,Fy as buildDetailRows,wb as buildHierarchy,zi as buildModuleUrl,cg as buildPlacesTree,Dh as buildWopiUrl,Eu as buttonGroupVariants,Bi as buttonVariants,ex as calculateAspectRatio,$y as camelToDash,Fi as cn,Hd as createCrudPage,Fv as createCrudRoutingConfig,Zg as createMindMapNode,zv as createRoutingHandlers,vl as createService,Gd as createSimpleSaveHandler,Al as createSimpleService,Qh as createStatusConfig,Cr as createTranslatedMessages,dg as currencyFormatter,ji as debounce,cl as deriveEmailField,dl as deriveNameField,ul as deriveUsernameField,_i as detectBrowserLocale,Si as detectBrowserPreferences,Ci as detectBrowserTimezone,Kb as detectVideoProvider,gb as emailService,Qs as errorService,_v as exportMindMap,rx as extractImageFileName,lg as extractNumberFromCurrency,Wb as extractVimeoId,Vb as extractYouTubeId,Nb as filterAndPromoteOrphans,bi as findDatetimeFormat,vi as findLocale,ev as findNode,xi as findTimezone,_b as flattenTree,sy as formatBytes,Pi as formatCurrency,Di as formatDate,Ei as formatDatetime,nx as formatFileSize,Wx as formatTime,qx as formatTimeProgress,Kd as generateCrudConfig,Jg as generateNodeId,Ti as generatePastelBg,Tx as getActionTypes,Mi as getContrastRatio,Mg as getDefaultPanelSize,ur as getEnvironmentConfig,gy as getFieldValue,ly as getFileExtension,by as getFormFieldValues,rg as getLinkFromRow,Ri as getLuminance,Lg as getMinPanelSize,Sh as getOnlineViewerType,Mx as getPriorities,Hx as getProgressColor,xr as getQualiexApiUrl,Px as getStatusLabels,rl as getSupabaseClient,kh as getViewerType,Eh as getWopiViewer,Li as handleExternalLink,kv as importMindMap,ki as inferDatetimeFormat,Qu as inputGroupAddonVariants,Ju as inputGroupButtonVariants,sg as isCurrency,br as isDevEnvironment,mr as isDevSupabaseProject,tx as isImageUrl,gr as isLovablePreview,ag as isNullOrEmptyField,Ni as isValidDatetimeFormat,yi as isValidLocale,wi as isValidTimezone,ux as loadClicksignScript,du as loadForlogicFonts,Ar as logoSrc,pb as mergeTranslationFiles,sv as moveNode,vm as navigationMenuTriggerStyle,Yb as normalizeVideoUrl,Hb as normalizeVimeoUrl,qb as normalizeYouTubeUrl,Gb as parseIframeSrc,yb as placeService,My as processTrails,tg as processUrl,ll as qualiexApi,ov as removeNode,ax as resizeKeepingAspect,ml as resolveFieldMappings,Hv as resolvePageTitle,dv as setCollapsedAll,xy as setFormFieldValues,mc as setupQualiexCore,vy as shouldShowField,vr as shouldUseDevTokens,dx as signService,Oi as slugify,Er as smallLogoSrc,Zf as sortByMonthYear,ng as toQueryString,lv as toggleCollapsed,pd as toggleVariants,Hc as trackFooterClick,Wc as trackInterestClick,qc as trackModuleClick,Ui as trimTextFields,Ux as useActionPlan,Vx as useActionPlanProgress,cb as useActiveModules,Jd as useAliasFromUrl,kl as useAuth,Sd as useBaseForm,cu as useClarity,Nd as useColumnManager,md as useColumnResize,Ab as useCreateMultipleLeadersMutation,Sb as useCreateSingleLeaderMutation,Sl as useCrud,Gv as useDebounce,tu as useDerivedContractedModules,Ao as useFormField,nb as useHasOpenModal,hb as useI18nFormatters,Dl as useIsMobile,Cb as useLeadershipApi,wc as useLocale,El as useMediaQuery,$b as useMediaUpload,rb as useModalState,au as useModuleAccess,kc as useModuleConfig,qv as useNavigation,uc as usePageMetadata,cc as usePageMetadataContext,Wv as usePageTitle,Qv as usePermissionQuery,Ld as useQualiexUsers,Db as useRemoveLeaderMutation,Cm as useRouteBreadcrumbs,ub as useRowResize,Jm as useSidebar,eb as useSidebarResize,ix as useSignConfig,Pb as useSyncSubordinatesMutation,Eb as useUpdateLeaderMutation,bh as useUpdatesNotification,mb as useWizard,yy as validateFields};
|