forlogic-core 2.1.1 → 2.1.2

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 s,useMemo as o,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{EllipsisVertical as S,X as A,ChevronDown as E,ChevronUp as D,Check as P,Loader2 as T,Loader2Icon as I,OctagonXIcon as R,TriangleAlertIcon as M,InfoIcon as L,CircleCheckIcon as z,ChevronRight as F,Circle as j,AlertCircle as U,Search as O,FileX as B,Edit as $,PowerOff as q,Power as V,Trash2 as W,Pencil as H,ToggleRight as G,ToggleLeft as K,Plus as Y,LayoutGrid as Q,List as X,Table2 as J,Columns3 as Z,GripVertical as ee,Group as ae,ArrowUp as te,ArrowDown as re,Target as ne,Trophy as ie,Award as se,Sparkles as oe,Flame as le,Zap as de,Key as ce,Shield as ue,EyeOff as me,Eye as pe,Unlock as he,Lock as fe,Archive as ge,FolderOpen as ve,Folder as be,FileText as xe,Save as ye,Copy as Ne,Share as we,Upload as _e,Download as Ce,HelpCircle as ke,Info as Se,Bell as Ae,Clock as Ee,ArrowRight as De,ArrowLeft as Pe,ChevronLeft as Te,Minus as Ie,Filter as Re,Bookmark as Me,Book as Le,Video as ze,Music as Fe,Image as je,Camera as Ue,MapPin as Oe,Calendar as Be,Phone as $e,Mail as qe,Settings as Ve,User as We,Home as He,Heart as Ge,Star as Ke,ChevronsLeft as Ye,ChevronsRight as Qe,CheckCircle as Xe,AlertTriangle as Je,RefreshCw as Ze,ExternalLink as ea,NotebookText as aa,Building2 as ta,LogOut as ra,MoreHorizontal as na,PanelLeft as ia,Edit3 as sa,Code as oa,Heading1 as la,Heading2 as da,Heading3 as ca,Bold as ua,Italic as ma,Underline as pa,Strikethrough as ha,ListOrdered as fa,Highlighter as ga,Link as va,RemoveFormatting as ba,Undo as xa,Redo as ya,ImageIcon as Na,FileSpreadsheet as wa,FileImage as _a,ShieldCheck as Ca,Coffee as ka,CheckCheck as Sa,Users as Aa,TriangleAlert as Ea,CheckCircle2 as Da,Hourglass as Pa,MoreVertical as Ta,ArrowUpToLine as Ia,UserPen as Ra,Menu as Ma,Crown as La,UserPlus as za,MessageSquare as Fa,Smartphone as ja,Paperclip as Ua,CloudUpload as Oa,RotateCcw as Ba,Layers as $a,XCircle as qa}from"lucide-react";import*as Va from"@radix-ui/react-label";import*as Wa from"@radix-ui/react-dialog";import*as Ha from"@radix-ui/react-separator";import*as Ga from"@radix-ui/react-alert-dialog";import{useFormContext as Ka,FormProvider as Ya,Controller as Qa,appendErrors as Xa,useForm as Ja}from"react-hook-form";import*as Za from"@radix-ui/react-select";import*as et from"@radix-ui/react-checkbox";import*as at from"@radix-ui/react-dropdown-menu";import*as tt from"@radix-ui/react-tooltip";import*as rt from"@radix-ui/react-popover";import{useTranslation as nt,initReactI18next as it,I18nextProvider as st}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as ot from"@radix-ui/react-scroll-area";import{createClient as lt}from"@supabase/supabase-js";import{useQueryClient as dt,useQuery as ct,useMutation as ut,QueryClient as mt,QueryClientProvider as pt}from"@tanstack/react-query";import{useSearchParams as ht,useParams as ft,useNavigate as gt,useLocation as vt,Navigate as bt,Link as xt}from"react-router-dom";import*as yt from"@radix-ui/react-context-menu";import*as Nt from"@radix-ui/react-toggle-group";import*as wt from"@radix-ui/react-toggle";import*as _t from"@radix-ui/react-switch";import*as Ct from"@radix-ui/react-collapsible";import*as kt from"@radix-ui/react-tabs";import*as St from"@radix-ui/react-accordion";import*as At from"@radix-ui/react-avatar";import{DayPicker as Et}from"react-day-picker";import{Drawer as Dt}from"vaul";import*as Pt from"@radix-ui/react-hover-card";import*as Tt from"@radix-ui/react-navigation-menu";import*as It from"@radix-ui/react-progress";import*as Rt from"@radix-ui/react-radio-group";import*as Mt from"react-resizable-panels";import*as Lt from"@radix-ui/react-slider";import*as zt from"@radix-ui/react-menubar";import*as Ft from"recharts";import{ResponsiveContainer as jt,XAxis as Ut,YAxis as Ot,CartesianGrid as Bt,Tooltip as $t,Legend as qt,BarChart as Vt,Bar as Wt,AreaChart as Ht,Area as Gt,LineChart as Kt,Line as Yt,PieChart as Qt,Pie as Xt,Cell as Jt,ComposedChart as Zt}from"recharts";import{useEditor as er,EditorContent as ar}from"@tiptap/react";import tr from"@tiptap/starter-kit";import rr from"@tiptap/extension-underline";import nr from"@tiptap/extension-link";import{TextStyle as ir}from"@tiptap/extension-text-style";import{Color as sr}from"@tiptap/extension-color";import or from"@tiptap/extension-highlight";import{useSensors as lr,useSensor as dr,PointerSensor as cr,DndContext as ur,closestCenter as mr}from"@dnd-kit/core";import{SortableContext as pr,rectSortingStrategy as hr,useSortable as fr}from"@dnd-kit/sortable";import{z as gr}from"zod";import{validateFieldsNatively as vr,toNestErrors as br}from"@hookform/resolvers";const xr="ccjfvpnndclajkleyqkc",yr={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},Nr={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 wr(){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===xr?yr:Nr}function _r(){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!==xr}const Cr={get oauth(){const e=wr();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},kr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},Sr={debounceDelay:500},Ar=()=>{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},Er=()=>Ar(),Dr=Ar,Pr=()=>wr().qualiexApiUrl,Tr={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},Ir={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},Rr={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},Mr={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}`}},Lr=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)}}),zr=`https://${wr().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,Fr={logo:Rr.isQualiex?`${zr}/logo-qualiex-white.svg`:`${zr}/saber-gestao-white.png`,smallLogo:Rr.isQualiex?`${zr}/logo-forlogic-white.svg`:`${zr}/small.svg`,favicon:`${zr}/favicon.png`},jr=Fr.logo,Ur=Fr.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=Fr.favicon,document.head.appendChild(e)}const Or={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 Br(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const $r={date:Br({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:Br({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:Br({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},qr={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Vr(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 Wr(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 s=i[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(s)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(s));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(s.length)}}}function Hr(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 s=e.valueCallback?e.valueCallback(i[0]):i[0];s=t.valueCallback?t.valueCallback(s):s;return{value:s,rest:a.slice(n.length)}}}const Gr={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=Or[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:$r,formatRelative:(e,a,t,r)=>qr[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:Vr({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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:Hr({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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 Kr={};function Yr(){return Kr}const Qr=6048e5;function Xr(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 Jr(e){const a=Xr(e);return a.setHours(0,0,0,0),a}function Zr(e){const a=Xr(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 en(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function an(e){const a=Xr(e),t=function(e,a){const t=Jr(e),r=Jr(a),n=+t-Zr(t),i=+r-Zr(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Xr(e),t=en(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function tn(e,a){const t=Yr(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Xr(e),i=n.getDay(),s=(i<r?7:0)+i-r;return n.setDate(n.getDate()-s),n.setHours(0,0,0,0),n}function rn(e){return tn(e,{weekStartsOn:1})}function nn(e){const a=Xr(e),t=a.getFullYear(),r=en(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=rn(r),i=en(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const s=rn(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=s.getTime()?t:t-1}function sn(e){const a=Xr(e),t=+rn(a)-+function(e){const a=nn(e),t=en(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),rn(t)}(a);return Math.round(t/Qr)+1}function on(e,a){const t=Xr(e),r=t.getFullYear(),n=Yr(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=en(e,0);s.setFullYear(r+1,0,i),s.setHours(0,0,0,0);const o=tn(s,a),l=en(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const d=tn(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function ln(e,a){const t=Xr(e),r=+tn(t,a)-+function(e,a){const t=Yr(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=on(e,a),i=en(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),tn(i,a)}(t,a);return Math.round(r/Qr)+1}function dn(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const cn={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return dn("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):dn(t+1,2)},d:(e,a)=>dn(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)=>dn(e.getHours()%12||12,a.length),H:(e,a)=>dn(e.getHours(),a.length),m:(e,a)=>dn(e.getMinutes(),a.length),s:(e,a)=>dn(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return dn(Math.trunc(r*Math.pow(10,t-3)),a.length)}},un="midnight",mn="noon",pn="morning",hn="afternoon",fn="evening",gn="night",vn={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 cn.y(e,a)},Y:function(e,a,t,r){const n=on(e,r),i=n>0?n:1-n;if("YY"===a){return dn(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):dn(i,a.length)},R:function(e,a){return dn(nn(e),a.length)},u:function(e,a){return dn(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 dn(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 dn(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 cn.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 dn(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=ln(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):dn(n,a.length)},I:function(e,a,t){const r=sn(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):dn(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):cn.d(e,a)},D:function(e,a,t){const r=an(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):dn(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 dn(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 dn(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 dn(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?mn:0===r?un: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?fn:r>=12?hn:r>=4?pn:gn,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 cn.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):cn.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):dn(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):dn(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):cn.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):cn.s(e,a)},S:function(e,a){return cn.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return xn(r);case"XXXX":case"XX":return yn(r);default:return yn(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return xn(r);case"xxxx":case"xx":return yn(r);default:return yn(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+bn(r,":");default:return"GMT"+yn(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+bn(r,":");default:return"GMT"+yn(r,":")}},t:function(e,a,t){return dn(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return dn(e.getTime(),a.length)}};function bn(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+dn(i,2)}function xn(e,a){if(e%60==0){return(e>0?"-":"+")+dn(Math.abs(e)/60,2)}return yn(e,a)}function yn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+dn(Math.trunc(r/60),2)+a+dn(r%60,2)}const Nn=(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"})}},wn=(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"})}},_n={p:wn,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return Nn(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}}",Nn(r,a)).replace("{{time}}",wn(n,a))}},Cn=/^D+$/,kn=/^Y+$/,Sn=["D","DD","YY","YYYY"];function An(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=Xr(e);return!isNaN(Number(t))}const En=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Dn=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Pn=/^'([^]*?)'?$/,Tn=/''/g,In=/[a-zA-Z]/;function Rn(e,a,t){const r=Yr(),n=t?.locale??r.locale??Gr,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Xr(e);if(!An(o))throw new RangeError("Invalid time value");let l=a.match(Dn).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,_n[a])(e,n.formatLong)}return e}).join("").match(En).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:Mn(e)};if(vn[a])return{isToken:!0,value:e};if(a.match(In))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const d={firstWeekContainsDate:i,weekStartsOn:s,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return kn.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return Cn.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(Sn.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,vn[i[0]])(o,i,n.localize,d)}).join("")}function Mn(e){const a=e.match(Pn);return a?a[1].replace(Tn,"'"):e}function Ln(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 zn(e,a){const t=function(e){jn[e]||(jn[e]=On?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 jn[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=Fn[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 Fn={year:0,month:1,day:2,hour:3,minute:4,second:5};const jn={},Un=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")),On="06/25/2014, 00:00:00"===Un||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===Un;function Bn(e,a,t,r,n,i,s){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,i,s),o}const $n=36e5,qn={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Vn(e,a,t){if(!e)return 0;let r,n,i=qn.timezoneZ.exec(e);if(i)return 0;if(i=qn.timezoneHH.exec(e),i)return r=parseInt(i[1],10),Hn(r)?-r*$n:NaN;if(i=qn.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return Hn(r,e)?(n=Math.abs(r)*$n+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(Gn[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Gn[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return Bn(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=Wn(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=Wn(new Date(n),t);if(a===i)return a;n-=i-a;const s=Wn(new Date(n),t);if(i===s)return i;return Math.max(i,s)}(a,n,e);return-i}return NaN}function Wn(e,a){const t=zn(e,a),r=Bn(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 Hn(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Gn={};const Kn={X:function(e,a,t){const r=Yn(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Jn(r);case"XXXX":case"XX":return Xn(r);default:return Xn(r,":")}},x:function(e,a,t){const r=Yn(t.timeZone,e);switch(a){case"x":return Jn(r);case"xxxx":case"xx":return Xn(r);default:return Xn(r,":")}},O:function(e,a,t){const r=Yn(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+Qn(i,2)}(r,":");default:return"GMT"+Xn(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return Ln("short",e,t);default:return Ln("long",e,t)}}};function Yn(e,a){const t=e?Vn(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function Qn(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function Xn(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Qn(Math.floor(r/60),2)+a+Qn(Math.floor(r%60),2)}function Jn(e,a){if(e%60==0){return(e>0?"-":"+")+Qn(Math.abs(e)/60,2)}return Xn(e,a)}function Zn(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 ei=36e5,ai=6e4,ti={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 ri(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=ti.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=ti.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=ti.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=ti.YYY[a],r=ti.YYYYY[a];let n=ti.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=ti.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),s=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=ti.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,li(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=ti.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=oi(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=ti.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return li(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=ti.Www.exec(e),i)return n=parseInt(i[1],10)-1,di(n)?ni(a,n):new Date(NaN);if(i=ti.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return di(n,e)?ni(a,n,e):new Date(NaN)}return null}(i,n);if(null===s||isNaN(s.getTime()))return new Date(NaN);if(s){const e=s.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=ti.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),ci(a)?a%24*ei:NaN;if(r=ti.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),ci(a,t)?a%24*ei+t*ai:NaN;if(r=ti.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return ci(a,t,e)?a%24*ei+t*ai+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Vn(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Zn(new Date(e+n)),t=Zn(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function ni(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 ii=[31,28,31,30,31,30,31,31,30,31,30,31],si=[31,29,31,30,31,30,31,31,30,31,30,31];function oi(e){return e%400==0||e%4==0&&e%100!=0}function li(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=oi(e);if(r&&t>si[a])return!1;if(!r&&t>ii[a])return!1}return!0}function di(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function ci(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const ui=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function mi(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match(ui);if(r){const n=ri(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],s=e.replace(a,"'"+Kn[a[0]](n,a,t)+"'");return i?s.substring(0,r-1)+s.substring(r+1):s},a)}return Rn(e,a,t)}(function(e,a,t){const r=Vn(a,e=ri(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 pi={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"}},hi={date:Br({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:Br({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Br({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},fi={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"},gi={lastWeek:"'el' eeee 'pasado a las' p",yesterday:"'ayer a las' p",today:"'hoy a las' p",tomorrow:"'mañana a las' p",nextWeek:"eeee 'a las' p",other:"P"},vi={code:"es",formatDistance:(e,a,t)=>{let r;const n=pi[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:hi,formatRelative:(e,a,t,r)=>1!==a.getHours()?gi[e]:fi[e],localize:{ordinalNumber:(e,a)=>Number(e)+"º",era:Vr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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:Hr({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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}},bi={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"}},xi={date:Br({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:Br({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:Br({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},yi={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"},Ni={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=bi[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:xi,formatRelative:(e,a,t,r)=>{const n=yi[e];return"function"==typeof n?n(a):n},localize:{ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Vr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Vr({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:Vr({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:Vr({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:Vr({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:Hr({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:Wr({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:Wr({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:Wr({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:Wr({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:Wr({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}},wi=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],_i=[{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"}],Ci=[{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"}],ki="pt-BR",Si="dd/MM/yyyy HH:mm",Ai="America/Sao_Paulo",Ei=e=>wi.find(a=>a.value===e),Di=e=>_i.find(a=>a.value===e),Pi=e=>Ci.find(a=>a.value===e),Ti=e=>wi.some(a=>a.value===e),Ii=e=>_i.some(a=>a.value===e),Ri=e=>Ci.some(a=>a.value===e),Mi=()=>{if("undefined"==typeof navigator)return ki;const e=navigator.language;if(Ti(e))return e;const a=e.split("-")[0],t=wi.find(e=>e.value.startsWith(a));return t?.value||ki},Li=()=>{if("undefined"==typeof Intl)return Ai;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return Ri(e)?e:Ai}catch{return Ai}},zi=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||Si),Fi=()=>{const e=Mi();return{locale:e,timezone:Li(),datetimeFormat:zi(e)}},ji={"pt-BR":Ni,"en-US":Gr,"es-ES":vi},Ui=(e,a=Si,t=Ai,r=ki)=>{if(!e)return"";const n=N(e);if(!w(n))return"Data inválida";const i=ji[r]||Ni;try{return mi(n,t,a,{locale:i})}catch(s){return mi(n,Ai,a,{locale:i})}},Oi=(e,a=ki,t=Ai)=>{if(!e)return"";const r=N(e);if(!w(r))return"Data inválida";const n=ji[a]||Ni;try{return mi(r,t,"PP",{locale:n})}catch(i){return mi(r,Ai,"PP",{locale:n})}},Bi=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function $i(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 qi(e,a){return a?e.replace(/\{alias\}/g,a):e}function Vi(...e){return x(b(e))}const Wi=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(Wi);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=Wi(r);return a}return e},Hi=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Gi=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),Ki=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"}}),Yi=n.forwardRef(({className:e,variant:t,size:r,asChild:n=!1,...i},s)=>a(n?g:"button",{className:Vi(Ki({variant:t,size:r,className:e})),ref:s,...i}));Yi.displayName="Button";const Qi=i.forwardRef(({className:e,children:t,variant:r="action",...n},i)=>a(Yi,{ref:i,variant:r,size:"icon",className:Vi("h-8 w-8",e),...n,children:t||a(S,{size:16})}));Qi.displayName="ActionButton";const Xi=n.forwardRef(({className:e,type:r,showCharCount:i,maxLength:s,onChange:o,...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:Vi("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:s,onChange:e=>{u(e.target.value.length),o?.(e)},...l}),i&&s&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[c," / ",s]})]})});Xi.displayName="Input";const Ji=v("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zi=n.forwardRef(({className:e,...t},r)=>a(Va.Root,{ref:r,className:Vi(Ji(),e),...t}));Zi.displayName=Va.Root.displayName;const es=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));es.displayName="Card";const as=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("flex flex-col space-y-1.5 p-6",e),...t}));as.displayName="CardHeader";const ts=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Vi("text-2xl font-semibold leading-none tracking-tight",e),...t}));ts.displayName="CardTitle";const rs=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Vi("text-sm text-muted-foreground",e),...t}));rs.displayName="CardDescription";const ns=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("p-6 pt-0",e),...t}));ns.displayName="CardContent";const is=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("flex items-center p-6 pt-0",e),...t}));is.displayName="CardFooter";const ss=n.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...n},i)=>a(Ha.Root,{ref:i,decorative:r,orientation:t,className:Vi("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...n}));ss.displayName=Ha.Root.displayName;const os=Ga.Root,ls=Ga.Trigger,ds=Ga.Portal,cs=n.forwardRef(({className:e,...t},r)=>a(Ga.Overlay,{className:Vi("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}));cs.displayName=Ga.Overlay.displayName;const us=n.forwardRef(({className:e,...r},n)=>t(ds,{children:[a(cs,{}),a(Ga.Content,{ref:n,className:Vi("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})]}));us.displayName=Ga.Content.displayName;const ms=({className:e,...t})=>a("div",{className:Vi("flex flex-col space-y-2 text-center sm:text-left",e),...t});ms.displayName="AlertDialogHeader";const ps=({className:e,...t})=>a("div",{className:Vi("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});ps.displayName="AlertDialogFooter";const hs=n.forwardRef(({className:e,...t},r)=>a(Ga.Title,{ref:r,className:Vi("text-lg font-semibold",e),...t}));hs.displayName=Ga.Title.displayName;const fs=n.forwardRef(({className:e,...t},r)=>a(Ga.Description,{ref:r,className:Vi("text-sm text-muted-foreground",e),...t}));fs.displayName=Ga.Description.displayName;const gs=n.forwardRef(({className:e,...t},r)=>a(Ga.Action,{ref:r,className:Vi(Ki(),e),...t}));gs.displayName=Ga.Action.displayName;const vs=n.forwardRef(({className:e,...t},r)=>a(Ga.Cancel,{ref:r,className:Vi(Ki({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));vs.displayName=Ga.Cancel.displayName;const bs=Wa.Root,xs=Wa.Trigger,ys=Wa.Portal,Ns=Wa.Close,ws=n.forwardRef(({className:e,...t},r)=>a(Wa.Overlay,{ref:r,className:Vi("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}));ws.displayName=Wa.Overlay.displayName;const _s={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"}},Cs=n.forwardRef(({className:r,children:i,size:s,variant:o="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),E=n.useRef(!1),D=s??(d||c||u||m||p||h?void 0:"md"),P=D?_s[D]:{},T={...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},I=n.useCallback(e=>{"form"===o&&l?(S.current=e,k(!0)):e()},[o,l]),R=n.useRef(null),M="destructive"!==o;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(ys,{children:[a(ws,{}),t(Wa.Content,{ref:_,className:Vi("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:T,onInteractOutside:e=>{"form"!==o&&"destructive"!==o?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==o)return"form"===o&&l?(e.preventDefault(),void I(()=>{E.current=!0,R.current?.click()})):void N?.(e);e.preventDefault()},...w,children:[i,M&&t(Wa.Close,{ref:R,onClick:e=>{E.current?E.current=!1:"form"===o&&l&&(e.preventDefault(),I(()=>{E.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(A,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]}),a(os,{open:C,onOpenChange:k,children:t(us,{children:[t(ms,{children:[a(hs,{children:f}),a(fs,{children:g})]}),t(ps,{children:[a(vs,{onClick:()=>{k(!1),S.current=null},children:v}),a(gs,{onClick:()=>{k(!1),S.current?.(),S.current=null},children:b})]})]})})]})});Cs.displayName=Wa.Content.displayName;const ks=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Vi("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(ss,{className:"mt-2"})]});ks.displayName="DialogHeader";const Ss=({className:e,...t})=>a("div",{className:Vi("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",e),...t});Ss.displayName="DialogBody";const As=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(ss,{className:"mb-4"}),a("div",{className:Vi("flex flex-row justify-end gap-2",e),...n,children:r})]});As.displayName="DialogFooter";const Es=n.forwardRef(({className:e,...t},r)=>a(Wa.Title,{ref:r,className:Vi("text-xl font-semibold leading-none tracking-tight",e),...t}));Es.displayName=Wa.Title.displayName;const Ds=n.forwardRef(({className:e,...t},r)=>a(Wa.Description,{ref:r,className:Vi("text-sm text-muted-foreground",e),...t}));Ds.displayName=Wa.Description.displayName;const Ps=Ya,Ts=n.createContext({}),Is=({...e})=>a(Ts.Provider,{value:{name:e.name},children:a(Qa,{...e})}),Rs=()=>{const e=n.useContext(Ts),a=n.useContext(Ms),{getFieldState:t,formState:r}=Ka(),i=t(e.name,r);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:s}=a;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...i}},Ms=n.createContext({}),Ls=n.forwardRef(({className:e,...t},r)=>{const i=n.useId();return a(Ms.Provider,{value:{id:i},children:a("div",{ref:r,className:Vi("space-y-1.5",e),...t})})});Ls.displayName="FormItem";const zs=n.forwardRef(({className:e,...t},r)=>{const{error:n,formItemId:i}=Rs();return a(Zi,{ref:r,className:Vi(n&&"text-destructive",e),htmlFor:i,...t})});zs.displayName="FormLabel";const Fs=n.forwardRef(({...e},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:s}=Rs();return a(g,{ref:t,id:n,"aria-describedby":r?`${i} ${s}`:`${i}`,"aria-invalid":!!r,...e})});Fs.displayName="FormControl";const js=n.forwardRef(({className:e,...t},r)=>{const{formDescriptionId:n}=Rs();return a("p",{ref:r,id:n,className:Vi("text-sm text-muted-foreground",e),...t})});js.displayName="FormDescription";const Us=n.forwardRef(({className:e,children:t,...r},n)=>{const{error:i,formMessageId:s}=Rs(),o=i?String(i?.message):t;return o?a("p",{ref:n,id:s,className:Vi("text-sm font-medium text-destructive",e),...r,children:o}):null});Us.displayName="FormMessage";const Os=Za.Root,Bs=Za.Group,$s=Za.Value,qs=n.forwardRef(({className:e,children:r,...n},i)=>t(Za.Trigger,{ref:i,className:Vi("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(Za.Icon,{asChild:!0,children:a(E,{className:"h-4 w-4 opacity-50"})})]}));qs.displayName=Za.Trigger.displayName;const Vs=n.forwardRef(({className:e,...t},r)=>a(Za.ScrollUpButton,{ref:r,className:Vi("flex cursor-default items-center justify-center py-1",e),...t,children:a(D,{className:"h-4 w-4"})}));Vs.displayName=Za.ScrollUpButton.displayName;const Ws=n.forwardRef(({className:e,...t},r)=>a(Za.ScrollDownButton,{ref:r,className:Vi("flex cursor-default items-center justify-center py-1",e),...t,children:a(E,{className:"h-4 w-4"})}));Ws.displayName=Za.ScrollDownButton.displayName;const Hs=n.forwardRef(({className:e,children:r,position:n="popper",container:i,collisionBoundary:s,...o},l)=>a(Za.Portal,{container:i,children:t(Za.Content,{ref:l,className:Vi("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:s,...o,children:[a(Vs,{}),a(Za.Viewport,{className:Vi("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),a(Ws,{})]})}));Hs.displayName=Za.Content.displayName;const Gs=n.forwardRef(({className:e,...t},r)=>a(Za.Label,{ref:r,className:Vi("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Gs.displayName=Za.Label.displayName;const Ks=n.forwardRef(({className:e,children:r,...n},i)=>t(Za.Item,{ref:i,className:Vi("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(Za.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),a(Za.ItemText,{children:r})]}));Ks.displayName=Za.Item.displayName;const Ys=n.forwardRef(({className:e,...t},r)=>a(Za.Separator,{ref:r,className:Vi("-mx-1 my-1 h-px bg-muted",e),...t}));Ys.displayName=Za.Separator.displayName;const Qs=n.forwardRef(({className:e,...t},r)=>a(et.Root,{ref:r,className:Vi("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(et.Indicator,{className:Vi("flex items-center justify-center text-current"),children:a(P,{className:"h-4 w-4"})})}));Qs.displayName=et.Root.displayName;const Xs=n.forwardRef(({className:e,showCharCount:r,maxLength:i,onChange:s,...o},l)=>{const[d,c]=n.useState(0);n.useEffect(()=>{"string"==typeof o.value?c(o.value.length):"string"==typeof o.defaultValue&&c(o.defaultValue.length)},[o.value,o.defaultValue]);return t("div",{className:"w-full",children:[a("textarea",{className:Vi("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),s?.(e)},...o}),r&&i&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",i]})]})});Xs.displayName="Textarea";const Js=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"}}),Zs=n.forwardRef(({className:e,variant:t,...r},n)=>a("div",{ref:n,className:Vi(Js({variant:t}),e),...r}));Zs.displayName="Badge";const eo={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function ao({size:e="md",className:t}){return a(T,{className:Vi("animate-spin text-muted-foreground",eo[e],t)})}function to({isLoading:e,children:n,className:i,type:s="spinner",size:o="md"}){return e?"overlay"===s?t("div",{className:Vi("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(ao,{size:o})})]}):a("div","skeleton"===s?{className:Vi("animate-pulse",i),children:a("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Vi("flex items-center justify-center py-8",i),children:a(ao,{size:o})}):a(r,{children:n})}const ro=({...e})=>a(k,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:a(z,{className:"h-4 w-4"}),info:a(L,{className:"h-4 w-4"}),warning:a(M,{className:"h-4 w-4"}),error:a(R,{className:"h-4 w-4"}),loading:a(I,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...e}),no=at.Root,io=at.Trigger,so=at.Group,oo=at.Portal,lo=at.Sub,co=at.RadioGroup,uo=n.forwardRef(({className:e,inset:r,children:n,...i},s)=>t(at.SubTrigger,{ref:s,className:Vi("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(F,{className:"ml-auto h-4 w-4"})]}));uo.displayName=at.SubTrigger.displayName;const mo=n.forwardRef(({className:e,...t},r)=>a(at.SubContent,{ref:r,className:Vi("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}));mo.displayName=at.SubContent.displayName;const po=n.forwardRef(({className:e,sideOffset:t=4,...r},n)=>a(at.Portal,{children:a(at.Content,{ref:n,sideOffset:t,className:Vi("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})}));po.displayName=at.Content.displayName;const ho=n.forwardRef(({className:e,inset:t,...r},n)=>a(at.Item,{ref:n,className:Vi("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}));ho.displayName=at.Item.displayName;const fo=n.forwardRef(({className:e,children:r,checked:n,...i},s)=>t(at.CheckboxItem,{ref:s,className:Vi("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(at.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),r]}));fo.displayName=at.CheckboxItem.displayName;const go=n.forwardRef(({className:e,children:r,...n},i)=>t(at.RadioItem,{ref:i,className:Vi("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(at.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));go.displayName=at.RadioItem.displayName;const vo=n.forwardRef(({className:e,inset:t,...r},n)=>a(at.Label,{ref:n,className:Vi("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));vo.displayName=at.Label.displayName;const bo=n.forwardRef(({className:e,...t},r)=>a(at.Separator,{ref:r,className:Vi("-mx-1 my-1 h-px bg-muted",e),...t}));bo.displayName=at.Separator.displayName;const xo=({className:e,...t})=>a("span",{className:Vi("ml-auto text-xs tracking-widest opacity-60",e),...t});xo.displayName="DropdownMenuShortcut";const yo=({delayDuration:e=300,...t})=>a(tt.Provider,{delayDuration:e,...t}),No=tt.Root,wo=tt.Trigger,_o=n.forwardRef(({className:e,sideOffset:t=4,...r},n)=>a(tt.Content,{ref:n,sideOffset:t,className:Vi("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),...r}));_o.displayName=tt.Content.displayName;const Co=n.forwardRef(({children:e,disabledReason:r,className:n},i)=>{const s=a(ho,{ref:i,className:Vi("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(yo,{delayDuration:100,children:t(No,{children:[a(wo,{asChild:!0,children:a("div",{className:"w-full",children:s})}),a(_o,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):s});Co.displayName="DisabledMenuItem";const ko=rt.Root,So=rt.Trigger,Ao=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,container:n,...i},s)=>a(rt.Portal,{container:n,children:a(rt.Content,{ref:s,align:t,sideOffset:r,className:Vi("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})}));Ao.displayName=rt.Content.displayName;const Eo=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));Eo.displayName="Command";const Do=({children:e,...t})=>a("div",{...t,children:a(Eo,{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})}),Po=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:Vi("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})}));Po.displayName="CommandInput";const To=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));To.displayName="CommandList";const Io=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("py-6 text-center text-sm text-muted-foreground",e),...t}));Io.displayName="CommandEmpty";const Ro=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("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}));Ro.displayName="CommandGroup";const Mo=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("-mx-1 h-px bg-border",e),...t}));Mo.displayName="CommandSeparator";const Lo=n.forwardRef(({className:e,disabled:t,onSelect:r,value:n,...i},s)=>a("div",{ref:s,className:Vi("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}));Lo.displayName="CommandItem";const zo=({className:e,...t})=>a("span",{className:Vi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});function Fo({className:e,...t}){return a("div",{className:Vi("animate-pulse rounded-md bg-muted",e),...t})}zo.displayName="CommandShortcut";const jo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Uo({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:_}){const[C,k]=s(!1),[S,D]=s(""),T=o(()=>i?Array.isArray(i)?i:[i]:[],[i]),I=o(()=>{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]),R=o(()=>{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]),M=o(()=>{if(!S)return R;const e=jo(S);return R.filter(a=>jo(a.label).includes(e))},[R,S]),L=o(()=>R.filter(e=>T.includes(e.value)),[R,T]),z=e=>{k(e),e?w?.():(D(""),_?.())},F=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(r?T.filter(a=>a!==e):"")},j=y?L.slice(0,y):L,U=y&&L.length>y?L.length-y:0;return t("div",{className:Vi("space-y-2",b),children:[m&&t(Zi,{children:[m,v&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(ko,{open:C,onOpenChange:z,modal:!1,children:[a(So,{asChild:!0,children:r?t("div",{role:"combobox","aria-expanded":C,"aria-disabled":g,tabIndex:g?-1:0,onKeyDown:e=>{g||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),z(!C))},className:Vi("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===L.length&&"text-muted-foreground"),children:[0===L.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(Zs,{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&&F(e.value,a)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:a=>F(e.value,a),children:a(A,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),U>0&&t(Zs,{variant:"outline",className:"gap-1",children:["+",U]})]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]}):t(Yi,{variant:"outline",role:"combobox","aria-expanded":C,disabled:g,className:Vi("w-full justify-between min-h-10 h-auto",0===L.length&&"text-muted-foreground"),children:[0===L.length?t("span",{className:"flex items-center gap-2",children:[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"}),L[0]?.label]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(Ao,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:I,collisionBoundary:I,children:t(Eo,{children:[t("div",{className:"relative",children:[a(Po,{placeholder:f,value:S,onChange:e=>D(e.target.value)}),S&&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:()=>D(""),children:a(A,{className:"h-3.5 w-3.5"})})]}),a(To,{children:0===n.length?a(Io,{children:h}):0===M.length?a(Io,{children:e.t("no_results")}):a(Ro,{children:M.map(e=>t(Lo,{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),k(!1)})(e.value),className:"cursor-pointer",children:[a(P,{className:Vi("mr-2 h-4 w-4",T.includes(e.value)?"opacity-100":"opacity-0")}),e.label]},e.value))})})]})})]})]})}function Oo({multiple:e=!1,options:r,items:n,value:i,onChange:s,onValueChange:o,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}){const{t:k}=nt(),S=r||n||[],A=o||s,E=c||k("select_placeholder","Selecione..."),D=p||k("no_results",k("no_results")),P=h||k("search_placeholder","Pesquisar...");if(v)return t("div",{className:Vi("space-y-2",x),children:[u&&t(Zi,{children:[u,g&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Fo,{className:"h-10 w-full"})]});const T="string"==typeof b?b:b instanceof Error?b.message:b?k("error_loading",k("error_loading")):void 0;return T?t("div",{className:Vi("space-y-2",x),children:[u&&t(Zi,{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(U,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:T})]})]}):a(Uo,{multiple:e,options:S,value:i||(e?[]:""),onChange:A,getOptionValue:l,getOptionLabel:d,placeholder:E,label:u,icon:m,emptyMessage:D,searchPlaceholder:P,disabled:f,required:g,className:x,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:_,onClose:C})}const Bo=n.forwardRef(({className:e,children:r,...n},i)=>t(ot.Root,{ref:i,className:Vi("relative overflow-hidden",e),...n,children:[a(ot.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),a($o,{}),a(ot.Corner,{})]}));Bo.displayName=ot.Root.displayName;const $o=n.forwardRef(({className:e,orientation:t="vertical",...r},n)=>a(ot.ScrollAreaScrollbar,{ref:n,orientation:t,className:Vi("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(ot.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));$o.displayName=ot.ScrollAreaScrollbar.displayName;const qo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function Vo(e,a){if(!a)return null;const t=qo(a),r=[];for(const n of e){const e=qo(n.label).includes(t),i=n.children?Vo(n.children,a):null,s=i&&i.length>0;(e||s)&&r.push({...n,children:e?n.children:s?i:n.children})}return r}function Wo(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=Wo(t.children,a);if(e)return e}}}function Ho({node:e,level:r,expanded:n,onToggleExpand:i,selectedValues:s,onSelect:o}){const l=e.children&&e.children.length>0,d=s.includes(e.value);return t("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":d,className:Vi("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(),o(e.value)},children:[a(P,{className:Vi("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:Vi("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?E:F,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Go({nodes:e,level:n,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:d}){return a(r,{children:e.map(e=>{const r=s.has(e.value);return t(i.Fragment,{children:[a(Ho,{node:e,level:n,expanded:r,onToggleExpand:o,selectedValues:l,onSelect:d}),r&&e.children&&e.children.length>0&&a(Go,{nodes:e.children,level:n+1,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:d})]},e.value)})})}function Ko({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}=nt(),[k,S]=s(!1),[D,P]=s(""),[T,I]=s(()=>_?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=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),F=o(()=>{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]),j=o(()=>Vo(r,D),[r,D])??r,B=o(()=>D?function(e,a){const t=new Set,r=qo(a);function n(e){if(!e.children||0===e.children.length)return qo(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||qo(e.label).includes(r)}for(const i of e)n(i);return t}(r,D):new Set,[r,D]),$=D?B:T,q=l(e=>{D||I(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[D]),V=o(()=>z.map(e=>({value:e,label:Wo(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?V.slice(0,x):V,Y=x&&V.length>x?V.length-x:0;if(g)return t("div",{className:Vi("space-y-2",b),children:[c&&t(Zi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Fo,{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:Vi("space-y-2",b),children:[c&&t(Zi,{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(U,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:Q})]})]}:{className:Vi("space-y-2",b),children:[c&&t(Zi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(ko,{open:k,onOpenChange:W,modal:!1,children:[a(So,{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:Vi("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===V.length&&"text-muted-foreground"),children:[0===V.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(Zs,{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(A,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),Y>0&&t(Zs,{variant:"outline",className:"gap-1",children:["+",Y]})]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]}):t(Yi,{variant:"outline",role:"combobox","aria-expanded":k,disabled:h,className:Vi("w-full justify-between min-h-10 h-auto font-normal",0===V.length&&"text-muted-foreground"),children:[0===V.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"}),V[0]?.label]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),t(Ao,{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(O,{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:D,onChange:e=>P(e.target.value)}),D&&a("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:a(A,{className:"h-3.5 w-3.5"})})]}),a(Bo,{className:"max-h-[300px]",children:a("div",{role:"tree",className:"p-1",children:0===j.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(Go,{nodes:j,level:0,expandedIds:$,onToggleExpand:q,selectedValues:z,onSelect:H})})})]})]})]})}class Yo{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 s=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),s=!1}const o=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),s=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:s,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:s,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()}}Yo.LARGE_PAYLOAD_THRESHOLD=1e3;const Qo="qualiex_access_token",Xo="qualiex_id_token",Jo="supabase_token",Zo="oauth_state",el="oauth_nonce",al="selected_alias",tl="manual_logout",rl="supabase_project_id",nl={setAccessToken:e=>localStorage.setItem(Qo,e),getAccessToken:()=>localStorage.getItem(Qo),setIdToken:e=>localStorage.setItem(Xo,e),getIdToken:()=>localStorage.getItem(Xo),getSupabaseToken:()=>localStorage.getItem(Jo),setOAuthState:e=>sessionStorage.setItem(Zo,e),getOAuthState:()=>sessionStorage.getItem(Zo),clearOAuthState:()=>sessionStorage.removeItem(Zo),setOAuthNonce:e=>sessionStorage.setItem(el,e),getOAuthNonce:()=>sessionStorage.getItem(el),clearOAuthNonce:()=>sessionStorage.removeItem(el),setSelectedAlias:e=>localStorage.setItem(al,e),getSelectedAlias:()=>localStorage.getItem(al),clearSelectedAlias:()=>localStorage.removeItem(al),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!nl.getAccessToken()||!nl.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(rl);return a&&a!==e?(nl.clearAll(),localStorage.setItem(rl,e),!0):(a||localStorage.setItem(rl,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Jo,e),nl._clearValidationCache()},areAllTokensValid:()=>{const e=nl.getAccessToken(),a=nl.getIdToken();if(!e||!a)return!1;try{const t=Yo.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=nl.getAccessToken(),t=nl.getIdToken(),r=nl.getSupabaseToken();return a&&nl.isTokenExpired(a)&&(localStorage.removeItem(Qo),e=!0),t&&nl.isTokenExpired(t)&&(localStorage.removeItem(Xo),e=!0),r&&nl.isTokenExpired(r)&&(localStorage.removeItem(Jo),e=!0),e},clearAll:()=>{localStorage.removeItem(Qo),localStorage.removeItem(Xo),localStorage.removeItem(Jo),localStorage.removeItem(al),localStorage.removeItem(tl),sessionStorage.removeItem(Zo),sessionStorage.removeItem(el),nl._clearValidationCache()},setManualLogout:()=>localStorage.setItem(tl,"true"),isManualLogout:()=>"true"===localStorage.getItem(tl),clearManualLogout:()=>localStorage.removeItem(tl),isTokenExpired:e=>{try{return Yo.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{nl._validationCache.isValid=!1,nl._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=nl.getSupabaseToken();if(!e)return!1;if(nl.isTokenExpired(e))return nl._clearValidationCache(),nl._handleExpiredToken(),!1;const a=Date.now();return a-nl._validationCache.timestamp<nl._validationCache.cacheValidityMs?nl._validationCache.isValid:(nl._validationCache.isValid=!0,nl._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>nl.isSupabaseTokenValid()?nl.getSupabaseToken():null,_handleExpiredToken:()=>{nl.clearAll()},extractTokenData:()=>{if(!nl.isSupabaseTokenValid())return null;const e=nl.getSupabaseToken();if(!e)return null;try{const a=Yo.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 nl._handleExpiredToken(),null}},getCompanyId:e=>{const a=nl.getAccessToken();if(a)try{const t=Yo.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=nl.extractTokenData();if(t?.companyId)return t.companyId;const r=nl.getIdToken();if(r)try{const a=Yo.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=[nl.getAccessToken(),nl.getIdToken()];for(const t of a)if(t)try{const a=Yo.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=nl.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=nl.getIdToken();if(!e)return[];try{const a=Yo.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 il=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=[]}},sl=import.meta.env.VITE_SUPABASE_URL,ol=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class ll{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:ol};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return lt(sl,ol,{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 ll.instance||(ll.instance=new ll),ll.instance}getClient(){const e=nl.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!Yo.isTokenExpired(e)}catch(a){return il.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function dl(){return ll.getInstance().getClient()}class cl{static async generateToken(e,a,t,r=!1){try{if(!r){const e=nl.getSupabaseToken();if(e&&nl.isSupabaseTokenValid())return e}const n=dl(),{data:i,error:s}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return s&&(s.message?.includes("401")||s.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(nl.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 ul{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=nl.getAccessToken(),t=nl.getSelectedAlias();if(!a||!t)return null;const r=await cl.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}ul.regenerationPromise=null,ul.onLogoutCallback=null;class ml{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(nl.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 pl{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 ul.attemptRegeneration()?(this.isRetrying=!1,!0):(ml.handleError(e),this.isRetrying=!1,!1)}catch(r){return ml.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=nl.getAccessToken();return e?nl.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."}}}pl.isRetrying=!1;const hl=new class{get baseUrl(){return Pr()}async makeApiCall(e,a,t){const r=pl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=nl.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status} ${s.statusText}`);throw e.status=s.status,e.statusCode=s.status,e}return await s.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return il.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(il.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a){const t={companyId:a,search:"",filterStatus:"active"};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a)??[]}catch(r){if(await pl.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return il.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return il.handleError(r instanceof Error?r.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 il.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e){const a=nl.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}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||""})):(il.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await pl.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 il.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return il.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})):(il.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await pl.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 il.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return il.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function fl(e,a){const t=a||Ir.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function gl(e,a){const t=a||Ir.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function vl(e,a){const t=a||Ir.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function bl(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||fl(e.idField),emailField:e.emailField||gl(e.idField),usernameField:e.usernameField||vl(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:fl(e),emailField:gl(e),usernameField:vl(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const xl=new Map;class yl{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=xl.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await hl.fetchUsers(e,a);return xl.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(!nl.areAllTokensValid())return e;const t=nl.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=bl(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const s=await this.fetchQualiexUsers(r,n),o=this.indexUsers(s);return e.map(e=>this.enrichEntity(e,i,o))}catch(t){return il.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const Nl=["responsible_name"],wl=e=>Nl.includes(e);function _l(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:s,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!nl.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return dl().schema(o).from(n)},u=(e,a,t,r)=>{let n=c().select(s||"*",{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 o=a.includes(".");return o||wl(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,i)=>{const s=bl(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(wl(a)||o||s){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},s=await p.getAll(e);if(!s?.data?.length)return s;const d=await yl.enrichWithUserData(s.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",s=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?s:-s}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",s=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?s:-s}))(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 yl.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},p={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:s,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...s}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:s}})(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,s,o),{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,s,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=bl(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,s,o);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await c().select(s||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=Wi(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={...Wi(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 Cl;const kl={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class Sl{static async initialize(){try{if(nl.checkProjectMismatch())return{...kl};if(!nl.hasAllTokens()||!nl.areAllTokensValid())return nl.clearExpiredTokens(),{...kl};const e=nl.getAccessToken(),a=nl.getIdToken();nl.clearManualLogout();const t=this.extractUserFromIdToken(a,e),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=nl.extractTokenData(),s=i?.alias;let o=null;if(s&&r.some(e=>e.alias===s))o=s;else{const e=nl.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);o=a?e:n||r[0]?.alias||null}if(!nl.isSupabaseTokenValid()&&o&&await ul.attemptRegeneration(),!nl.isSupabaseTokenValid())return{...kl};let l=null;if(o){const e=nl.getCompanyId(o),a=r.find(e=>e.alias===o);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:o,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{...kl}}}static async loginDev(){try{const e=dl(),{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==";nl.setOAuthState(e);const a=nl.generateOAuthNonce();nl.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(Cr.oauth.authUrl);r.searchParams.set("client_id",Cr.oauth.clientId),r.searchParams.set("response_type",Cr.oauth.responseType),r.searchParams.set("scope",Cr.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=nl.getAccessToken();e!==r&&nl.clearAll()}if(nl.hasAllTokens()){return nl.getValidSupabaseToken()||await ul.attemptRegeneration(!0),!0}const s=r,o=n;if(!s||!o)throw new Error("Tokens não encontrados na URL de callback");nl.setAccessToken(s),nl.setIdToken(o),nl.clearManualLogout();const l=this.extractAliasFromAccessToken(s);if(l)nl.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(o);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");nl.setSelectedAlias(e[0].alias)}if(!await ul.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return nl.clearOAuthState(),nl.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){nl.setManualLogout(),nl.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 Yo.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}}Cl=Sl,ul.setLogoutCallback(()=>{Cl.logout()});const Al=e=>e?.placeId||null,El=e=>e?.placeName||null,Dl=d(void 0),Pl=({children:e})=>{const[t,r]=s({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=dt()}catch{}const[i,d]=s(!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=nl.getAccessToken();if(!i)return;const s=await cl.generateToken(i,e.alias,void 0,!0);if(c.current!==a)return;if(!s)return;nl.setSupabaseToken(s),nl.setSelectedAlias(e.alias);const o=nl.extractTokenData(),l=o?.alias||e.alias,d=o?.companyId||nl.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 hl.fetchActiveUsersMap(l,d);if(c.current!==a)return;const r=e.get(t.user.id);if(r){const e=(e=>({placeId:Al(e),placeName:El(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 Sl.processCallback();if(e){const e=await Sl.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 Sl.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(nl.areAllTokensValid()){if(!nl.isSupabaseTokenValid())try{await ul.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 Sl.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&&(ml.handleError(a),h(!1))}})(),()=>{e=!1}},[p,h,b]);const w=o(()=>({...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(Dl.Provider,{value:w,children:e})},Tl=()=>{const e=c(Dl);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function Il({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:i}){const[d,c]=ht(),u=dt(),{alias:m,userId:p,isAuthenticated:h}=Tl(),{t:f}=nt(),g=l(a=>{const t=`${e}_${a}`,r=d.get(t);return r||(d.get(a)||"")},[d,e]),v=g("search"),b=g("sortField")||kr.sorting.defaultField,x=g("sortDirection")||kr.sorting.defaultDirection,y=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(kr.pagination.defaultPageSize)),w=v,_=o(()=>({search:w,sortField:b,sortDirection:x,page:y,limit:N,...n}),[w,b,x,y,N,n]),k=l(()=>a.getAll(_),[a,_]),S=ct({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=ut({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.created(t)),i?.()},onError:e=>{C.error(`${Mr.error.create(t)}: ${e.message}`)}}),E=ut({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.updated(t)),i?.()},onError:e=>{C.error(`${Mr.error.update(t)}: ${e.message}`)}}),D=ut({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(Mr.success.deleted(t))},onError:e=>{C.error(`${Mr.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]),T=l(e=>{P({search:e,page:1})},[P]),I=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]=s([]),j=l(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),U=l(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=l(()=>{F([])},[]),B=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),$=ut({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}`))}}),q=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||kr.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:q,handleSearch:T,handleSort:I,handlePageChange:R,handleItemsPerPageChange:M,clearFilters:L,refetch:S.refetch,selectedIds:z,selectItem:j,selectAll:U,clearSelection:O,isAllSelected:B,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function Rl(e){const a=_l({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)=>Il({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function Ml(e){const[a,t]=s(()=>"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 Ll(e=768){return Ml(`(max-width: ${e-1}px)`)}const zl=n.forwardRef(({className:e,...t},r)=>a("table",{ref:r,className:Vi("w-full caption-bottom text-[13px] table-fixed",e),...t}));zl.displayName="Table";const Fl=n.forwardRef(({className:e,...t},r)=>a("thead",{ref:r,className:Vi("[&_tr]:border-b sticky top-0 z-[1] bg-background",e),...t}));Fl.displayName="TableHeader";const jl=n.forwardRef(({className:e,...t},r)=>a("tbody",{ref:r,className:Vi("[&_tr:last-child]:border-0",e),...t}));jl.displayName="TableBody";const Ul=n.forwardRef(({className:e,...t},r)=>a("tfoot",{ref:r,className:Vi("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));Ul.displayName="TableFooter";const Ol=n.forwardRef(({className:e,...t},r)=>a("tr",{ref:r,className:Vi("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",e),...t}));Ol.displayName="TableRow";const Bl=n.forwardRef(({className:e,...t},r)=>a("th",{ref:r,className:Vi("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}));Bl.displayName="TableHead";const $l=n.forwardRef(({className:e,...t},r)=>a("td",{ref:r,className:Vi("px-4 py-2 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",e),...t}));$l.displayName="TableCell";const ql=n.forwardRef(({className:e,...t},r)=>a("caption",{ref:r,className:Vi("mt-4 text-sm text-muted-foreground",e),...t}));function Vl({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(Fo,{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(Fo,{className:"h-4 w-20"},t))})},t))})]})})}function Wl({count:e=3}){return a("div",{className:"space-y-4",children:Array.from({length:e}).map((e,r)=>t(es,{children:[t(as,{children:[a(Fo,{className:"h-4 w-3/4"}),a(Fo,{className:"h-3 w-1/2"})]}),a(ns,{children:t("div",{className:"space-y-2",children:[a(Fo,{className:"h-3 w-full"}),a(Fo,{className:"h-3 w-2/3"})]})})]},r))})}function Hl({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(Fo,{className:"h-4 w-24"}),a(Fo,{className:"h-10 w-full"})]},r)),t("div",{className:"flex justify-end space-x-2 pt-4",children:[a(Fo,{className:"h-10 w-20"}),a(Fo,{className:"h-10 w-20"})]})]})}function Gl(){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(Fo,{className:"h-8 w-8 rounded-full"}),a(Fo,{className:"h-6 w-32"})]}),t("div",{className:"flex items-center space-x-2",children:[a(Fo,{className:"h-8 w-8"}),a(Fo,{className:"h-8 w-24"})]})]})}function Kl(){return a("div",{className:"w-64 border-r bg-muted/10",children:t("div",{className:"p-4",children:[a(Fo,{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(Fo,{className:"h-4 w-4"}),a(Fo,{className:"h-4 w-20"})]},r))})]})})}ql.displayName="TableCaption";const Yl={default:B,search:O,error:U};function Ql({icon:e,title:r,description:n,action:i,className:s,variant:o="default"}){const{t:l}=nt(),d=!!e,c=Yl[o];return t("div",{className:Vi("flex flex-col items-center justify-center py-12 px-4 text-center",s),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(Yi,{onClick:i.onClick,variant:"outline",children:i.label})]})}function Xl({children:e,className:r}){const i=n.useRef(null),[s,o]=n.useState(!1);n.useEffect(()=>{const e=()=>{const e=i.current;e&&o(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 s?a(yo,{delayDuration:300,children:t(No,{children:[a(wo,{asChild:!0,children:l}),a(_o,{side:"top",className:"max-w-[400px] break-words",children:e})]})}):l}const Jl=n.forwardRef(({direction:e,onMouseDown:t,isDragging:r,className:n},i)=>{const s="horizontal"===e;return a("div",{ref:i,onMouseDown:t,className:Vi("absolute z-20 select-none touch-none","transition-colors duration-150",s&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!s&&["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:Vi("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",s?"h-6 w-0.5":"w-6 h-0.5")})})});Jl.displayName="TableResizeHandle";const Zl=yt.Root,ed=yt.Trigger,ad=yt.Group,td=yt.Portal,rd=yt.Sub,nd=yt.RadioGroup,id=n.forwardRef(({className:e,inset:r,children:n,...i},s)=>t(yt.SubTrigger,{ref:s,className:Vi("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(F,{className:"ml-auto h-4 w-4"})]}));id.displayName=yt.SubTrigger.displayName;const sd=n.forwardRef(({className:e,...t},r)=>a(yt.SubContent,{ref:r,className:Vi("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}));sd.displayName=yt.SubContent.displayName;const od=n.forwardRef(({className:e,...t},r)=>a(yt.Portal,{children:a(yt.Content,{ref:r,className:Vi("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})}));od.displayName=yt.Content.displayName;const ld=n.forwardRef(({className:e,inset:t,...r},n)=>a(yt.Item,{ref:n,className:Vi("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}));ld.displayName=yt.Item.displayName;const dd=n.forwardRef(({className:e,children:r,checked:n,...i},s)=>t(yt.CheckboxItem,{ref:s,className:Vi("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(yt.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),r]}));dd.displayName=yt.CheckboxItem.displayName;const cd=n.forwardRef(({className:e,children:r,...n},i)=>t(yt.RadioItem,{ref:i,className:Vi("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(yt.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));cd.displayName=yt.RadioItem.displayName;const ud=n.forwardRef(({className:e,inset:t,...r},n)=>a(yt.Label,{ref:n,className:Vi("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",e),...r}));ud.displayName=yt.Label.displayName;const md=n.forwardRef(({className:e,...t},r)=>a(yt.Separator,{ref:r,className:Vi("-mx-1 my-1 h-px bg-border",e),...t}));md.displayName=yt.Separator.displayName;const pd=({className:e,...t})=>a("span",{className:Vi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});pd.displayName="ContextMenuShortcut";const hd=({onEdit:e,onDelete:n,onToggleStatus:i,isActive:s=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const{t:c}=nt(),u=[];if(e){const a={icon:$,label:c("edit"),onClick:e};u.push(a)}if(l.forEach(e=>{u.push(e)}),i){const e={icon:s?q:V,label:s?"Inativar":"Ativar",onClick:i};u.push(e)}if(o&&n){const e={icon:W,label:c("ap_delete"),onClick:n,destructive:!0};u.push(e)}const m="dropdown"===d?ho:ld;return a(r,{children:u.map((e,r)=>t(m,{onClick:e.onClick,className:Vi("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))})},fd=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>t(no,{children:[a(io,{asChild:!0,children:a(Yi,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:a(S,{size:12})})}),a(po,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:a(hd,{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:s,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),gd=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>{const{t:l}=nt();return a(yo,{delayDuration:200,children:t("div",{className:"flex items-center justify-end gap-0.5",children:[e&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e()},children:a(H,{size:14})})}),a(_o,{children:l("edit")})]}),o.map((e,r)=>{const n=e.icon;return t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e.onClick()},children:a(n,{size:14})})}),a(_o,{children:e.label})]},r)}),i&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:a(s?G:K,{size:14})})}),a(_o,{children:s?"Inativar":"Ativar"})]}),r&&n&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:Vi("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:a(W,{size:14})})}),a(_o,{children:l("ap_delete")})]})]})})},vd=150;function bd({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=s(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??vd,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??vd,e),{})}),[o,d]=s(!1),[c,p]=s(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]??vd)},[r,n]);m(()=>{if(!o||!c)return;const r=e.find(e=>e.key===c),n=r?.minWidth??60,s=r?.maxWidth??500,l=e=>{const a=e.clientX-h.current,r=Math.max(n,Math.min(s,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)}},[o,c,e,a,t]),m(()=>(o?(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=""}),[o]);const v=l(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??vd,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:o,activeColumn:c,handleMouseDown:g,resetWidths:v}}const xd=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"}}),yd=n.forwardRef(({className:e,variant:t,size:r,...n},i)=>a(wt.Root,{ref:i,className:Vi(xd({variant:t,size:r,className:e})),...n}));yd.displayName=wt.Root.displayName;const Nd=n.createContext({size:"default",variant:"default"}),wd=n.forwardRef(({className:e,variant:t,size:r,children:n,...i},s)=>a(Nt.Root,{ref:s,className:Vi("flex items-center justify-center gap-1",e),...i,children:a(Nd.Provider,{value:{variant:t,size:r},children:n})}));wd.displayName=Nt.Root.displayName;const _d=n.forwardRef(({className:e,children:t,variant:r,size:i,...s},o)=>{const l=n.useContext(Nd);return a(Nt.Item,{ref:o,className:Vi(xd({variant:l.variant||r,size:l.size||i}),e),...s,children:t})});_d.displayName=Nt.Item.displayName;const Cd=p(function({onNew:e,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:s="",onSearchChange:o,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}=nt(),_=c>0,C=e&&n||h.length>0,k=f||b||y,S=i&&o;return C||S||k||d&&_?t("div",{className:Vi("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(Yi,{onClick:e,children:[a(Y,{size:16,className:"mr-2"}),r||"Novo"]}),h.map((e,r)=>{const n=e.icon;return t(Yi,{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(Zs,{variant:"secondary",className:"mr-1 tabular-nums",children:c}),t(yo,{delayDuration:200,children:[u.length>0?u.map((e,r)=>{const n=e.icon,i=e.disabled;return t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:Vi("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(_o,{children:e.label})]},r)}):t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:a(W,{size:16})})}),a(_o,{children:w("ap_delete")})]}),t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:a(A,{size:16})})}),a(_o,{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(O,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Xi,{type:"text",placeholder:l||"Pesquisar",value:s,onChange:e=>o?.(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(wd,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:x.map(e=>{const t=(e=>{switch(e){case"table":return J;case"list":return X;case"grid":return Q}})(e);return a(_d,{value:e,"aria-label":"Visualizar como "+("table"===e?"tabela":"list"===e?"lista":"grade"),children:a(t,{className:"h-4 w-4"})},e)})}),y]})]}):null}),kd=p(({checked:e,onCheckedChange:t})=>a(Qs,{checked:e,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function Sd(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 Ad({columns:e,storageKey:a,enabled:t=!0,defaultHiddenColumns:r}){const n=o(()=>e.map(e=>String(e.key)),[e]),i=o(()=>new Set(r??[]),[r]),[d,c]=s(()=>{if(!t)return i;if(!a)return i;const e=Sd(a);return e?.hiddenColumns??i}),[u,p]=s(()=>{if(!t||!a)return n;const e=Sd(a)?.columnOrder;return e&&e.length>0?e:n}),[h,f]=s(()=>t&&a?Sd(a)?.groupByColumns??[]:[]),[g,v]=s(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=o(()=>{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]),T=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,...s]=t,o=new Map;for(const l of a){const e=String(l[i]??"(vazio)");o.has(e)||o.set(e,[]),o.get(e).push(l)}return Array.from(o.entries()).map(([a,t])=>{const o=n?`${n}|${i}:${a}`:`${i}:${a}`,l=s.length>0?e(t,s,r+1,o):void 0;return{groupKey:o,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:T,collapsedGroups:g,toggleGroupCollapse:_}}function Ed({enabled:e=!1,onReorder:a}){const[t,r]=s(null),[n,i]=s(null),d=l(()=>{r(null),i(null)},[]),c=l((n,s)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),s&&a.dataTransfer.setData("application/column-key",s))},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 o(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:c}),[t,n,c])}function Dd({columns:e,columnOrder:r,isColumnHidden:n,toggleColumn:i,showAllColumns:o,reorderColumns:l,groupByColumn:d,setGroupByColumn:c,groupByColumns:m=[],addGroupByColumn:p,removeGroupByColumn:h,resetColumns:f}){const{t:g}=nt(),[v,b]=s(null),[x,y]=s(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(ko,{children:[a(So,{asChild:!0,children:a(Yi,{variant:"outline",size:"icon",className:"h-8 w-8",children:a(Z,{size:16})})}),t(Ao,{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(yo,{delayDuration:300,children:_.map((e,r)=>{const s=String(e.key),o=n(s),u=!1!==e.hideable,f=!0===e.groupable,w=m.includes(s)||d===s;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:Vi("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(ee,{size:14,className:"text-muted-foreground shrink-0"}),a(Qs,{checked:!o,onCheckedChange:()=>u&&i(s),disabled:!u,className:"shrink-0"}),a("span",{className:Vi("flex-1 truncate",o&&"text-muted-foreground"),children:e.header}),f&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:Vi("h-6 w-6 shrink-0",w&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),w?h?h(s):c?.(null):p?p(s):c?.(s)},children:a(ae,{size:14})})}),a(_o,{children:g(w?"remove_grouping":"group_by_column")})]})]},s)})})}),t("div",{className:"border-t px-3 py-2 space-y-1",children:[a(Yi,{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))):o,children:g(k?"deselect_all":"select_all_columns")}),f&&a(Yi,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function Pd({columns:e,groupByColumns:r,addGroupByColumn:n,removeGroupByColumn:o,reorderGroupByColumns:l}){const[d,c]=s(!1),[u,m]=s(null),[p,h]=s(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:Vi("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(ae,{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 s=u===r,d=p===r&&u!==r;return t(i.Fragment,{children:[r>0&&a("span",{className:"text-xs text-muted-foreground",children:"›"}),t(Zs,{variant:"secondary",className:Vi("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",s&&"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(),o(e)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:a(A,{size:12})})]})]},e)}):a("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const Td=({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:D=[],onBulkDelete:P,filters:T,viewMode:I,onViewModeChange:R,showViewToggle:M=!1,enableColumnResize:L=!0,resizeStorageKey:z,enableColumnManager:j=!0,columnManagerStorageKey:U,defaultHiddenColumns:O,enableGrouping:B=!1,enableExpandableRows:$=!1,renderExpandedContent:q,expandedRowIds:V,onToggleExpand:W,defaultExpandAll:H=!1,hideActionsColumn:G=!1})=>{const{t:K}=nt(),{setSearchVisible:Y}=Tl(),Q=Ll(),[X,J]=s(()=>H&&$?new Set(r.entities.map(e=>e.id)):new Set),Z=void 0!==V,ee=Z?new Set(V):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]),ne=void 0!==w?!w:_;m(()=>{if(!C)return Y(!0),()=>Y(!1)},[Y,C]);const ie=Ad({columns:n,storageKey:U,enabled:j,defaultHiddenColumns:O}),se=Ed({enabled:j,onReorder:ie.reorderColumns}),oe=j?ie.visibleColumns:n,{columnWidths:le,isDragging:de,activeColumn:ce,handleMouseDown:ue}=bd({columns:oe.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=o(()=>(()=>{if(L)return oe.map(e=>{const a=le[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=oe.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`}})})(),[oe,L,le]),pe=b||N.length>0||C||g||T||M||j,he=ne&&pe,fe=P||(()=>{r.bulkDelete?.(r.selectedIds)}),ge=e=>a($l,{className:"text-center",children:h?h(e):"inline"===v?a("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:a(gd,{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(fd,{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(od,{className:"w-[160px]",children:a(hd,{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=j?a(Dd,{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(Wl,{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(Cd,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:D,onBulkDelete:fe,onClearSelection:r.clearSelection,customActions:N,filters:T,viewMode:I,onViewModeChange:R,showViewToggle:M}),a("div",{className:"flex-1 overflow-auto space-y-4 p-4",children:r.entities.map(e=>t(Zl,{children:[a(ed,{asChild:!0,children:a(es,{className:Vi("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(ns,{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(kd,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),t("div",{className:"flex-1",children:[oe.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(fd,{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)+oe.length+(G?0:1),we=e=>{const n=$&&ee.has(e.id);return t(i.Fragment,{children:[t(Zl,{children:[a(ed,{asChild:!0,children:t(Ol,{className:Vi("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($l,{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?E:F,{size:16,className:"text-muted-foreground"})})}),g&&a($l,{onClick:e=>e.stopPropagation(),children:a(kd,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),oe.map(t=>a($l,{className:t.className,children:a(Xl,{children:t.render?t.render(e):String(e[t.key]??"")})},String(t.key))),!G&&ge(e)]})}),ve(e)]}),n&&q&&a(Ol,{className:"bg-muted/30 hover:bg-muted/30",children:a($l,{colSpan:Ne,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:q(e)})})})]},e.id)},_e=(e,r)=>{const{t:n}=nt();return e.map(e=>{const n=ie.collapsedGroups.has(e.groupKey),s=16*e.level,o=Math.max(30,70-15*e.level);return t(i.Fragment,{children:[a(Ol,{className:Vi("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>ie.toggleGroupCollapse(e.groupKey),children:a($l,{colSpan:r,className:"py-2 px-4",children:t("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${s}px`},children:[a(n?F:E,{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(Cd,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:D,onBulkDelete:fe,onClearSelection:r.clearSelection,customActions:N,filters:T,viewMode:I,onViewModeChange:R,showViewToggle:M}),r.isLoading?a(Vl,{rows:5,columns:oe.length}):t("div",{className:"flex flex-col h-full overflow-hidden",children:[B&&a(Pd,{columns:n,groupByColumns:ie.groupByColumns,addGroupByColumn:ie.addGroupByColumn,removeGroupByColumn:ie.removeGroupByColumn,reorderGroupByColumns:ie.reorderGroupByColumns}),a("div",{className:"flex-1 overflow-auto",children:t(zl,{className:"table-auto",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(Fl,{children:t(Ol,{children:[$&&a(Bl,{className:"w-[40px]"}),g&&a(Bl,{className:"w-[50px]",children:a(kd,{checked:r.isAllSelected,onCheckedChange:r.selectAll})}),oe.map((e,n)=>{const i=L&&!1!==e.resizable,s=ce===String(e.key),o=j?se.getDragProps(n,String(e.key)):{},l=se.dragFromIndex===n,d=se.dragOverIndex===n&&se.dragFromIndex!==n;return t(Bl,{className:Vi(e.className,!1!==e.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",j&&se.isDragging&&"cursor-grabbing",l&&"opacity-50",d&&"border-l-2 border-primary"),onClick:!1!==e.sortable?()=>r.handleSort(String(e.key)):void 0,...o,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(te,{size:14,className:"ml-1"}):a(re,{size:14,className:"ml-1"}))]}),i&&a(Jl,{direction:"horizontal",onMouseDown:a=>ue(String(e.key),a),isDragging:s})]},String(e.key));var c}),!G&&a(Bl,{className:"w-[50px] text-center",children:be||e.t("actions")})]})}),a(jl,{children:0===r.entities.length?a(Ol,{children:a($l,{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 Id(e,a,t,r){const[n,i]=s({}),[l,d]=s({}),c=o(()=>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),s={};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);s[e.name]=t}),n.forEach(e=>{const a=h(e,s);void 0!==a&&(s[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(s[e]=a[e])}),i(s),d({}),t&&t(s)},[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 Rd=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],Md=({value:e="#3b82f6",onChange:r,label:n,customColorLabel:i,presetColorsLabel:s})=>{const{t:o}=nt(),l=i??o("custom_color"),d=s??o("preset_colors");return t("div",{className:"space-y-2",children:[n&&a(Zi,{children:n}),t(ko,{children:[a(So,{asChild:!0,children:t(Yi,{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(Ao,{className:"w-64",children:t("div",{className:"space-y-3",children:[t("div",{children:[a(Zi,{htmlFor:"color-input",children:l}),a(Xi,{id:"color-input",type:"color",value:e,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),t("div",{children:[a(Zi,{children:d}),a("div",{className:"grid grid-cols-5 gap-2 mt-2",children:Rd.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))})]})]})})]})]})},Ld={Star:Ke,Heart:Ge,Home:He,User:We,Settings:Ve,Mail:qe,Phone:$e,Calendar:Be,MapPin:Oe,Camera:Ue,Image:je,Music:Fe,Video:ze,Book:Le,Bookmark:Me,Search:O,Filter:Re,Edit:$,Trash2:W,Plus:Y,Minus:Ie,Check:P,X:A,ChevronDown:E,ChevronUp:D,ChevronLeft:Te,ChevronRight:F,ArrowUp:te,ArrowDown:re,ArrowLeft:Pe,ArrowRight:De,Clock:Ee,Bell:Ae,AlertCircle:U,Info:Se,HelpCircle:ke,Download:Ce,Upload:_e,Share:we,Copy:Ne,Save:ye,FileText:xe,Folder:be,FolderOpen:ve,Archive:ge,Lock:fe,Unlock:he,Eye:pe,EyeOff:me,Shield:ue,Key:ce,Zap:de,Flame:le,Sparkles:oe,Award:se,Trophy:ie,Target:ne},zd=({value:e="Star",onChange:r,label:n,searchLabel:i="Pesquisar"})=>{const[o,l]=s(""),d=Object.entries(Ld).filter(([e])=>e.toLowerCase().includes(o.toLowerCase())),c=Ld[e]||Ke;return t("div",{className:"space-y-2",children:[n&&a(Zi,{children:n}),t(ko,{children:[a(So,{asChild:!0,children:t(Yi,{variant:"outline",className:"w-full justify-start text-left font-normal",children:[a(c,{className:"h-4 w-4 mr-2"}),e]})}),a(Ao,{className:"w-80",children:t("div",{className:"space-y-3",children:[t("div",{children:[a(Zi,{htmlFor:"icon-search",children:i}),a(Xi,{id:"icon-search",placeholder:i,value:o,onChange:e=>l(e.target.value)})]}),a(Bo,{className:"h-48",children:a("div",{className:"grid grid-cols-6 gap-2",children:d.map(([t,n])=>a("button",{className:"p-2 rounded border-2 hover:border-primary "+(e===t?"border-primary bg-primary/10":"border-border"),onClick:()=>r?.(t),title:t,children:a(n,{className:"h-4 w-4"})},t))})})]})})]})]})},Fd=n.forwardRef(({className:e,...t},r)=>a(_t.Root,{className:Vi("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(_t.Thumb,{className:Vi("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")})}));Fd.displayName=_t.Root.displayName;const jd=(e={})=>{const{user:a,alias:t}=Tl(),{enabled:r=!0}=e;return ct({queryKey:["qualiex-users",t],queryFn:()=>hl.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},Ud=({value:t,onChange:r,multiple:n=!1,label:i,required:s,placeholder:d,icon:c,maxDisplayedBadges:u,className:m,disabled:p,enabled:h,displayFormat:f="name",customDisplayFn:g,filterFn:v,sortOptions:b=!0,popoverContainer:x,onOpen:y,onClose:N})=>{const{t:w}=nt(),{data:_=[],isLoading:C,error:k}=jd({enabled:h}),S=o(()=>v?_.filter(v):_,[_,v]),A=o(()=>{const a=t?Array.isArray(t)?t:[t]:[];if(0===a.length)return S;const r=new Set(S.map(e=>e.userId||e.id||"")),n=a.filter(e=>e&&!r.has(e));if(0===n.length)return S;const i=n.map(a=>({userId:a,id:a,userName:e.t("inactive_user"),userEmail:""}));return[...S,...i]},[S,t]),E=l(e=>{if("custom"===f&&g)return g(e);const a=e.userName||"";switch(f){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[f,g]);return a(Oo,{multiple:n,value:t??(n?[]:""),onChange:r,options:A,isLoading:C,error:k,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:E,placeholder:d||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:w("no_results"),label:i,required:s,icon:c,maxDisplayedBadges:u,disabled:p,className:m,sortOptions:b,popoverContainer:x,onOpen:y,onClose:N})};function Od({title:e,sections:r,initialData:n,onSubmit:d,onCancel:c,open:m,submitButtonText:p,isLoading:h=!1,usersData:f}){const[g,v]=s(r?.[0]?.id||""),b=u(null),[x,y]=s(null),N=l(e=>{b.current=e,y(e)},[]),w=o(()=>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}=Id(w,n,void 0,m),A=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(_):e.disabled||!1})):[],[r,_]),E=o(()=>{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,s=r?`flex gap-3 w-full ${e.className||""}`:"space-y-3",o=r?Vi("space-y-2 w-full",e.wrapperClassName):Vi("space-y-2",e.className,e.wrapperClassName);return t("div",{className:o,children:[e.label,a("div",{className:s,children:e.fields?.map(e=>P(e))})]},e.name);case"user-select":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ud,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Xs,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(Os,{value:String(n),onValueChange:a=>{k(e.name,a),e.onValueChange&&e.onValueChange(a)},disabled:e.disabled,children:[a(qs,{className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,children:a($s,{placeholder:e.placeholder})}),a(Hs,{children:e.options?.map(e=>a(Ks,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Oo,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Xi,{id:e.name,type:"date",value:String(n),onChange:a=>k(e.name,a.target.value),placeholder:e.placeholder,disabled:e.disabled,className:Vi("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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Xi,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Md,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(zd,{value:n||e.defaultValue||"Star",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(Zi,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Xi,{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(Qs,{id:e.name,checked:!!n,onCheckedChange:a=>k(e.name,a),disabled:e.disabled}),t(Zi,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Fd,{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(Zi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Xi,{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)}},T=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]),I=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(Yi,{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:[T(),t("div",{className:"flex justify-end space-x-2 pt-4",children:[a(Yi,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),a(Yi,{type:"submit",disabled:h,children:p||"Salvar"})]})]})})]});return a(bs,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:t(Cs,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[t(ks,{showSeparator:!0,children:[a(Es,{children:e}),a(Ds,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),I]})})}function Bd({currentPage:e,totalPages:n,totalItems:i,itemsPerPage:s,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const{t:c}=nt();if(0===i)return null;const u=(e-1)*s+1,m=Math.min(e*s,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(Os,{value:String(s),onValueChange:e=>l(Number(e)),children:[a(qs,{className:"h-8 w-[70px]",children:a($s,{})}),t(Hs,{children:[a(Ks,{value:"10",children:"10"}),a(Ks,{value:"25",children:"25"}),a(Ks,{value:"50",children:"50"}),a(Ks,{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(Yi,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===e,className:"h-8 w-8 p-0",children:a(Ye,{size:16})}),a(Yi,{variant:"outline",size:"sm",onClick:()=>o(e-1),disabled:1===e,className:"h-8 w-8 p-0",children:a(Te,{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(Yi,{variant:"outline",size:"sm",onClick:()=>o(e+1),disabled:e===n,className:"h-8 w-8 p-0",children:a(F,{size:16})}),a(Yi,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:e===n,className:"h-8 w-8 p-0",children:a(Qe,{size:16})})]})]})}function $d({manager:e}){return a(Bd,{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 qd={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},Vd={start:"items-start",center:"items-center",end:"items-end",stretch:"items-stretch"},Wd={start:"justify-start",center:"justify-center",end:"justify-end",between:"justify-between",around:"justify-around",evenly:"justify-evenly"};function Hd({children:e,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:s=!1,className:o}){return a("div",{className:Vi("flex","column"===t?"flex-col":"flex-row",qd[r],Vd[n],Wd[i],s&&"flex-wrap",o),children:e})}function Gd({manager:e,filters:n,inline:i=!1}){const{t:s}=nt(),{isSearchVisible:o}=Tl(),l=e.searchTerm,d=t(r,{children:[n.some(e=>"search"===e.type)&&!o&&t("div",{className:"relative flex-1",children:[a(O,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(Xi,{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(Os,{value:e.value||"",onValueChange:a=>e.onChange?.(a),children:[a(qs,{className:"w-[180px]",children:a($s,{placeholder:e.placeholder})}),a(Hs,{children:e.options.map(e=>a(Ks,{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(Yi,{variant:"outline",onClick:e.clearFilters,className:"whitespace-nowrap",children:[a(A,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?a("div",{className:"flex items-center gap-2",children:d}):a(Hd,{direction:"column",gap:"md",className:"mb-6",children:a(Hd,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:d})})}function Kd({manager:e,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){e&&e.queryKey;const{setSearchVisible:d}=Tl(),[c,u]=ht(),[p,h]=s(!1),[f,g]=s(null),[v,b]=s({isOpen:!1,entityId:null,entityName:""}),[x,y]=s({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(Cd,{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(Gd,{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(Td,{manager:e,columns:r.columns,onEdit:N,onDelete:w,onToggleStatus:o,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($d,{manager:e})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&a(Od,{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(bs,{open:v.isOpen,onOpenChange:_,children:t(Cs,{size:"sm",variant:"destructive",children:[a(ks,{showSeparator:!0,children:a(Es,{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(As,{children:[a(Yi,{variant:"outline",onClick:_,children:"Cancelar"}),a(Yi,{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(bs,{open:x.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),children:t(Cs,{size:"sm",variant:"destructive",children:[a(ks,{showSeparator:!0,children:a(Es,{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(As,{children:[a(Yi,{variant:"outline",onClick:()=>y({isOpen:!1,count:0}),children:"Cancelar"}),a(Yi,{variant:"destructive",onClick:()=>{e.bulkDelete?.(e.selectedIds),y({isOpen:!1,count:0})},disabled:e.isBulkDeleting,children:e.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Yd(e){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:s,onToggleStatus:o}=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:s||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(Kd,{manager:l,config:d,formSections:n.formSections,onSave:i,onToggleStatus:o,defaultSort:n.defaultSort})}}function Qd(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 Xd(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:Zd(e),label:Zd(e),...Jd(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 Jd(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 Zd(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const ec=({children:n})=>{const{isAuthenticated:s,isLoading:o}=Tl();if(i.useEffect(()=>{if(o)return;if(s)return;if(nl.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=Er(),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 Sl.loginDev():Sl.loginProd()})()},[s,o]),o&&!s)return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(es,{className:"w-full max-w-md",children:[a(as,{className:"text-center",children:a(ts,{className:"text-xl font-semibold",children:"Carregando..."})}),t(ns,{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(!s){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(es,{className:"w-full max-w-md",children:[a(as,{className:"text-center",children:a(ts,{className:"text-xl font-semibold",children:"Processando..."})}),t(ns,{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(es,{className:"w-full max-w-md",children:[a(as,{className:"text-center",children:a(ts,{className:"text-xl font-semibold",children:"Iniciando..."})}),t(ns,{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:Er()?e.t("auto_login"):e.t("redirecting_auth")})]})]})})}return a(r,{children:n})};function ac(e={}){const{paramName:a="alias"}=e,t=ft(),{alias:r,companies:n}=Tl(),i=t[a]||null;return o(()=>{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 tc({children:e,paramName:n="alias"}){const i=gt(),o=vt(),d=ft(),{alias:c,isAuthenticated:p,isLoading:h,switchUnit:f}=Tl(),{urlAlias:g,isAliasMismatch:v,isValidAlias:b,isMissing:x,matchedCompany:y}=ac({paramName:n}),[N,w]=s(!1),_=u(!1),C=n in d,k=l(e=>{const a=d[n],{pathname:t,search:r,hash:i}=o;if(a){const n=t.split("/"),s=n.findIndex(e=>e===a);if(s>=0)return n[s]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[d,n,o]);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(ao,{size:"lg"}),a("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):a(r,{children:e})}function rc(){const{alias:e}=Tl(),{pathname:t,search:r,hash:n}=vt();return e?a(bt,{to:`/${e}${t}${r}${n}`,replace:!0}):null}const nc=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"}}),ic={info:Se,warning:Se,danger:Je,success:Xe},sc=n.forwardRef(({className:e,variant:r="info",showIcon:n=!0,children:i,...s},o)=>{const l=ic[r||"info"];return t("div",{ref:o,role:"alert",className:Vi(nc({variant:r}),e),...s,children:[n&&a(l,{className:"h-4 w-4"}),i]})});sc.displayName="Alert";const oc=n.forwardRef(({className:e,...t},r)=>a("h5",{ref:r,className:Vi("mb-1 font-medium leading-none tracking-tight",e),...t}));oc.displayName="AlertTitle";const lc=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("text-sm [&_p]:leading-relaxed",e),...t}));lc.displayName="AlertDescription";const dc=()=>{const{processCallback:e}=Tl(),n=gt(),[i,o]=s(null),[l,d]=s(!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 o("Falha na autenticação. Tente novamente.")}catch(a){localStorage.removeItem("auth_return_url"),o(a?.message||"Erro durante a autenticação. Tente novamente.")}})()},[e,n]);const c=async()=>{d(!0),o(null);try{await e()||o("Falha na autenticação. Tente novamente.")}catch(a){o(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(es,{className:"w-full max-w-md",children:[a(as,{className:"text-center",children:t(ts,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[a(U,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),t(ns,{className:"space-y-4",children:[a(sc,{variant:"danger",children:a(lc,{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(Yi,{onClick:c,disabled:l,className:"flex-1",children:t(r,l?{children:[a(ao,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[a(Ze,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),a(Yi,{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(es,{className:"w-full max-w-md",children:[a(as,{className:"text-center",children:a(ts,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),t(ns,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(ao,{size:"lg"})}),a("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},cc=()=>{const{t:e}=nt();return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(es,{className:"w-full max-w-md",children:[a(as,{className:"text-center",children:a(ts,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),t(ns,{className:"text-center space-y-4",children:[a("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),a(Yi,{onClick:async()=>{Er()?await Sl.loginDev():Sl.loginProd()},className:"w-full",size:"lg",children:Er()?e("dev_login"):e("login_with_qualiex")})]})]})})},uc=d(void 0);function mc({children:e,actions:t}){const{t:r}=nt(),[n,i]=s({}),[d,c]=s(t);m(()=>{c(t)},[t]);const u=l(()=>i({}),[]),p=o(()=>({metadata:n,setMetadata:i,clearMetadata:u,headerActions:d,setHeaderActions:c}),[n,u,d]);return a(uc.Provider,{value:p,children:e})}function pc(){const e=c(uc);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function hc(e){const{setMetadata:a,clearMetadata:t}=pc(),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 fc(e){return{queryClient:e.queryClient||new mt({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var gc={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_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",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..."},vc={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_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",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..."},bc={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_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",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 xc="true"===import.meta.env.VITE_I18N_DEBUG_MODE;function yc(a,t){e.addResourceBundle(a,"app",t,!0,!0)}xc&&e.use({type:"postProcessor",name:"debugKeys",process:(e,a)=>`🔑 ${Array.isArray(a)?a[0]:a}`}),e.use(it).init({resources:{"pt-BR":{core:gc},"en-US":{core:vc},"es-ES":{core:bc}},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:xc?["debugKeys"]:[]});const Nc=d(void 0),wc={locale:ki,timezone:Ai,datetimeFormat:Si},_c=async()=>{},Cc=({children:e})=>a(Nc.Provider,{value:{...wc,setLocale:_c,setTimezone:_c,setDatetimeFormat:_c,isLoading:!1},children:e}),kc=()=>{const e=c(Nc);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},Sc=d({moduleAlias:null});function Ac({moduleAlias:e=null,children:t}){return a(Sc.Provider,{value:{moduleAlias:e},children:t})}function Ec(){return c(Sc)}const Dc=Ct.Root,Pc=Ct.CollapsibleTrigger,Tc=Ct.CollapsibleContent;class Ic extends h{constructor(a){super(a),this.copyErrorDetails=()=>{const a=il.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;il.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const r=il.getErrors().slice(0,2);return a("div",{className:"flex items-center justify-center min-h-screen p-4",children:t(es,{className:"w-full max-w-2xl",children:[t(as,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(Je,{className:"h-12 w-12 text-destructive"})}),a(ts,{children:e.t("something_went_wrong")})]}),t(ns,{className:"space-y-4",children:[a("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),t(Dc,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[a(Pc,{asChild:!0,children:t(Yi,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[a(E,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),t(Tc,{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(Bo,{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(Yi,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[a(Ne,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),a(Yi,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const Rc=kt.Root,Mc=n.forwardRef(({className:e,...t},r)=>a(kt.List,{ref:r,className:Vi("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),...t}));Mc.displayName=kt.List.displayName;const Lc=n.forwardRef(({className:e,...t},r)=>a(kt.Trigger,{ref:r,className:Vi("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}));Lc.displayName=kt.Trigger.displayName;const zc=n.forwardRef(({className:e,...t},r)=>a(kt.Content,{ref:r,className:Vi("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 Fc({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 jc({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"})]})}function Uc({educaUrl:e="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n,alias:i}){const{t:s}=nt(),o=qi(e||n||"https://educacao.sabergestao.com.br/{alias}/fe",i);return t("div",{className:"flex-shrink-0 pt-4",children:[a(ss,{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:o,target:"_blank",rel:"noopener noreferrer",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(ea,{className:"h-3.5 w-3.5"})]})]}),a(Fc,{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",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",a(ea,{className:"h-3.5 w-3.5"})]})]}),a(jc,{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",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(ea,{className:"h-3.5 w-3.5"})]})]}),a(aa,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}zc.displayName=kt.Content.displayName;const Oc=[{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 Bc({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:Vi("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 $c(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 qc({modules:e,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const o=function(){const[e,a]=s(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=$c(c,o),h=$c(u,o),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(Bc,{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(Bc,{module:e,onClick:()=>f(e,!1)},e.name))})]})]})}function Vc({onModuleClick:e,contractedModules:r,onModuleInterest:n,nonContractedUrl:i="https://qualiex.com/",educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:d,alias:c}){const[u,m]=s("qualiex"),p=a=>{e?.(a)},h=e=>{window.open(i,"_blank","noopener,noreferrer"),n?.(e)};return t("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[t(Rc,{value:u,onValueChange:m,className:"flex-1 flex flex-col min-h-0",children:[a(Mc,{className:"w-fit shrink-0",children:Oc.map(e=>t(Lc,{value:e.id,children:[e.label,t("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),Oc.map(e=>a(zc,{value:e.id,className:"flex-1 mt-4 overflow-auto pr-2",children:a(qc,{modules:e.modules,onModuleClick:p,contractedModules:"qualiex"===e.id?r:void 0,onModuleInterest:h})},e.id))]}),a(Uc,{educaUrl:o,saberGestaoUrl:l,wikiUrl:d,alias:c})]})}const Wc={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},Hc=6e5;function Gc(e){const{moduleAlias:a}=Ec(),{alias:t,user:r,isAuthenticated:n}=Tl(),i=e??a,s=r?.id??null,d=n&&!!t&&!!s,{data:c=[],isLoading:u}=ct({queryKey:["qualiex-associations",s,t],queryFn:()=>hl.fetchUserAssociations(s,t),enabled:d,staleTime:Hc,gcTime:12e5}),m=o(()=>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=Wc[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:o(()=>!i||p(i),[i,p]),isLoading:d&&u,role:o(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:p}}function Kc(e){const{association:a}=Gc();return o(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=Oc.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=Wc[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function Yc({open:e,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:d}){const{alias:c}=Tl(),u=Kc(i);return a(bs,{open:e,onOpenChange:r,children:t(Cs,{size:"lg",className:"overflow-hidden flex flex-col",children:[a(ks,{className:"sr-only",children:a(Es,{children:"Módulos"})}),a(Vc,{onModuleClick:e=>{n?n(e):e.url&&$i(qi(e.url,c||void 0))},contractedModules:u,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:d,alias:c||void 0})]})})}function Qc({open:r,onOpenChange:n,onModuleClick:i,contractedModules:s,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}){const{t:N}=nt(),w=o(()=>{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(bs,{open:r,onOpenChange:b?void 0:n,children:t(Cs,{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(Es,{children:N("no_access_page")}),a(Ds,{children:"Selecione um módulo para continuar navegando!"})]}),t("div",{className:"flex items-center gap-2 shrink-0",children:[w.length>1&&t(no,{children:[a(io,{asChild:!0,children:t(Yi,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[a(ta,{className:"h-4 w-4 shrink-0"}),a("span",{className:"truncate text-xs",children:c||"Unidade"}),a(E,{className:"h-3 w-3 shrink-0"})]})}),a(po,{align:"end",className:"max-h-[300px] overflow-auto",children:w.map(e=>t(ho,{onClick:()=>p?.(e),className:e.alias===m?"bg-muted":"",children:[a(ta,{className:"mr-2 h-4 w-4 shrink-0"}),a("span",{className:"truncate",children:e.name}),e.alias===m&&a(Zs,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},e.alias))})]}),t(no,{children:[a(io,{asChild:!0,children:t(Yi,{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(We,{className:"h-3.5 w-3.5 text-primary-foreground"})}),a(E,{className:"h-3 w-3"})]})}),t(po,{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(bo,{}),t(ho,{onClick:h,children:[a(ra,{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(Uc,{educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m})]}):a(Vc,{onModuleClick:i,contractedModules:s,onModuleInterest:l,educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m})]})})}function Xc(e,a){const{t:t}=nt();return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function Jc({children:e,contractedModules:t,onModuleClick:n,onModuleInterest:i,educaUrl:s="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:d="https://sabergestao.com.br/",wikiUrl:c,bypassPaths:u,accessDeniedRoutes:m}){const{t:p}=nt(),{hasAccess:h,isLoading:f,association:g}=Gc(),{user:v,alias:b,companies:x,isAuthenticated:y,isLoading:N,logout:w,switchUnit:_}=Tl(),C=Kc(t),k=o(()=>x?.length?b&&x.find(e=>e.alias===b)||x[0]:null,[x,b]),S=o(()=>x?.length?x.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[x]),A=l(e=>{const a=x?.find(a=>a.alias===e.alias);if(!a)return;const{pathname:t,search:r,hash:n}=window.location;if(b){const e=t.split("/"),i=e.indexOf(b);if(i>=0)return e[i]=a.alias,void(window.location.href=e.join("/")+r+n)}_(a)},[b,_,x]),E=l(e=>{n?n(e):e.url&&$i(qi(e.url,b||void 0))},[n,b]),D=o(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>Xc(e,[a]));return a?m[a]:void 0},[m]);return N||!y||u?.length&&Xc(window.location.pathname,u)?a(r,{children:e}):f?a("div",{className:"flex items-center justify-center min-h-screen",children:a(ao,{size:"lg"})}):h?a(r,{children:e}):a(Qc,{open:!0,onModuleClick:E,contractedModules:C,onModuleInterest:i,userName:v?.name,unitName:k?.name,units:S,currentAlias:b||void 0,onUnitChange:A,onLogout:w,educaUrl:s,saberGestaoUrl:d,wikiUrl:c,blocking:!0,children:D})}function Zc({title:e,description:r,image:n,icon:i,ctaLabel:s,onCtaClick:o,children:l}){const{t:d}=nt(),c=s??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}):o?t(Yi,{onClick:o,size:"lg",className:"gap-2",children:[a(oe,{className:"h-4 w-4"}),c]}):null]})}let eu=!1;function au(){if(eu||"undefined"==typeof document)return;eu=!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";if(!document.querySelector(`link[href="${e}"]`)){const a=document.createElement("link");a.rel="stylesheet",a.href=e,document.head.appendChild(a)}}function tu({children:t,queryClient:r,moduleAlias:n,moduleAccessGuardProps:s,appTranslations:o}){au();const[l]=i.useState(()=>new mt({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),d=r??l;return i.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))yc(e,a)},[o]),a(Ic,{children:a(st,{i18n:e,children:a(pt,{client:d,children:a(Pl,{children:a(Cc,{children:a(Ac,{moduleAlias:n,children:a(Jc,{...s,children:t})})})})})})})}const ru=St.Root,nu=n.forwardRef(({className:e,...t},r)=>a(St.Item,{ref:r,className:Vi("border-b",e),...t}));nu.displayName="AccordionItem";const iu=n.forwardRef(({className:e,children:r,...n},i)=>a(St.Header,{className:"flex",children:t(St.Trigger,{ref:i,className:Vi("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(E,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));iu.displayName=St.Trigger.displayName;const su=n.forwardRef(({className:e,children:t,...r},n)=>a(St.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:Vi("pb-4 pt-0",e),children:t})}));su.displayName=St.Content.displayName;const ou=n.forwardRef(({className:e,...t},r)=>a(At.Root,{ref:r,className:Vi("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ou.displayName=At.Root.displayName;const lu=n.forwardRef(({className:e,...t},r)=>a(At.Image,{ref:r,className:Vi("aspect-square h-full w-full",e),...t}));lu.displayName=At.Image.displayName;const du=n.forwardRef(({className:e,...t},r)=>a(At.Fallback,{ref:r,className:Vi("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));du.displayName=At.Fallback.displayName;const cu=n.forwardRef(({...e},t)=>a("nav",{ref:t,"aria-label":"breadcrumb",...e}));cu.displayName="Breadcrumb";const uu=n.forwardRef(({className:e,...t},r)=>a("ol",{ref:r,className:Vi("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",e),...t}));uu.displayName="BreadcrumbList";const mu=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Vi("inline-flex items-center gap-1.5",e),...t}));mu.displayName="BreadcrumbItem";const pu=n.forwardRef(({asChild:e,className:t,...r},n)=>a(e?g:"a",{ref:n,className:Vi("transition-colors hover:text-foreground",t),...r}));pu.displayName="BreadcrumbLink";const hu=n.forwardRef(({className:e,...t},r)=>a("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Vi("font-normal text-foreground",e),...t}));hu.displayName="BreadcrumbPage";const fu=({children:e,className:t,...r})=>a("li",{role:"presentation","aria-hidden":"true",className:Vi("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:e??a(F,{})});fu.displayName="BreadcrumbSeparator";const gu=({className:e,...r})=>t("span",{role:"presentation","aria-hidden":"true",className:Vi("flex h-9 w-9 items-center justify-center",e),...r,children:[a(na,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Mais"})]});gu.displayName="BreadcrumbEllipsis";const vu=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"}}),bu=n.forwardRef(({className:e,orientation:t,...r},n)=>a("div",{ref:n,className:Vi(vu({orientation:t}),e),...r}));function xu({className:e,classNames:t,showOutsideDays:r=!0,...n}){return a(Et,{showOutsideDays:r,className:Vi("p-3 pointer-events-auto",e),locale:Ni,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:Vi(Ki({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Vi(Ki({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:Vi(Ki({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?Te:F,{className:"h-4 w-4"})},...n})}bu.displayName="ButtonGroup",xu.displayName="Calendar";const yu={Root:function({children:e,className:t}){return a("div",{className:Vi("space-y-4",t),children:e})},Item:function({children:e,onClick:t,className:r}){return a(es,{className:Vi("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:a(ns,{className:"p-4",children:e})})},Field:function({label:e,value:r,className:n}){return t("div",{className:Vi("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 Nu({date:e,onDateChange:r,placeholder:n,disabled:i=!1,className:s,disabledDates:o}){const{t:l}=nt(),d=n??l("select_date");return t(ko,{children:[a(So,{asChild:!0,children:t(Yi,{variant:"outline",disabled:i,className:Vi("w-full justify-start text-left font-normal",!e&&"text-muted-foreground",s),children:[a(Be,{className:"mr-2 h-4 w-4"}),e?_(e,"d 'de' MMMM 'de' yyyy",{locale:Ni}):a("span",{children:d})]})}),a(Ao,{className:"w-auto p-0",align:"start",children:a(xu,{mode:"single",selected:e,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const wu=({shouldScaleBackground:e=!0,...t})=>a(Dt.Root,{shouldScaleBackground:e,...t});wu.displayName="Drawer";const _u=Dt.Trigger,Cu=Dt.Portal,ku=Dt.Close,Su=n.forwardRef(({className:e,...t},r)=>a(Dt.Overlay,{ref:r,className:Vi("fixed inset-0 z-50 bg-black/80",e),...t}));Su.displayName=Dt.Overlay.displayName;const Au=n.forwardRef(({className:e,children:r,...n},i)=>t(Cu,{children:[a(Su,{}),t(Dt.Content,{ref:i,className:Vi("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]})]}));Au.displayName="DrawerContent";const Eu=({className:e,...t})=>a("div",{className:Vi("grid gap-1.5 p-4 text-center sm:text-left",e),...t});Eu.displayName="DrawerHeader";const Du=({className:e,...t})=>a("div",{className:Vi("mt-auto flex flex-col gap-2 p-4",e),...t});Du.displayName="DrawerFooter";const Pu=n.forwardRef(({className:e,...t},r)=>a(Dt.Title,{ref:r,className:Vi("text-lg font-semibold leading-none tracking-tight",e),...t}));Pu.displayName=Dt.Title.displayName;const Tu=n.forwardRef(({className:e,...t},r)=>a(Dt.Description,{ref:r,className:Vi("text-sm text-muted-foreground",e),...t}));Tu.displayName=Dt.Description.displayName;const Iu={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))]"},Ru={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function Mu({children:e,cols:t="auto-fit",gap:r="md",className:n}){return a("div",{className:Vi("grid",Iu[t],Ru[r],n),children:e})}const Lu=Pt.Root,zu=Pt.Trigger,Fu=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,...n},i)=>a(Pt.Content,{ref:i,align:t,sideOffset:r,className:Vi("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}));Fu.displayName=Pt.Content.displayName;const ju=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-slot":"input-group",className:Vi("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}));ju.displayName="InputGroup";const Uu=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"}}),Ou=n.forwardRef(({className:e,align:t,...r},n)=>a("div",{ref:n,"data-slot":"input-group-addon",className:Vi(Uu({align:t}),e),...r}));Ou.displayName="InputGroupAddon";const Bu=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"}}),$u=n.forwardRef(({className:e,size:t,variant:r="ghost",...n},i)=>a(Yi,{ref:i,"data-slot":"input-group-button",variant:r,className:Vi(Bu({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",e),...n}));$u.displayName="InputGroupButton";const qu=n.forwardRef(({className:e,...t},r)=>a(Xi,{ref:r,"data-slot":"input-group-control",className:Vi("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));qu.displayName="InputGroupInput";const Vu=n.forwardRef(({className:e,...t},r)=>a(Xs,{ref:r,"data-slot":"input-group-control",className:Vi("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));Vu.displayName="InputGroupTextarea";const Wu=n.forwardRef(({className:e,...t},r)=>a("h1",{ref:r,className:Vi("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",e),...t}));Wu.displayName="H1";const Hu=n.forwardRef(({className:e,...t},r)=>a("h2",{ref:r,className:Vi("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",e),...t}));Hu.displayName="H2";const Gu=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Vi("scroll-m-20 text-2xl font-semibold tracking-tight",e),...t}));Gu.displayName="H3";const Ku=n.forwardRef(({className:e,...t},r)=>a("h4",{ref:r,className:Vi("scroll-m-20 text-xl font-semibold tracking-tight",e),...t}));Ku.displayName="H4";const Yu=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Vi("leading-7 [&:not(:first-child)]:mt-6",e),...t}));Yu.displayName="P";const Qu=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Vi("text-xl text-muted-foreground",e),...t}));Qu.displayName="Lead";const Xu=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Vi("text-lg font-semibold",e),...t}));Xu.displayName="Large";const Ju=n.forwardRef(({className:e,...t},r)=>a("small",{ref:r,className:Vi("text-sm font-medium leading-none",e),...t}));Ju.displayName="Small";const Zu=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Vi("text-sm text-muted-foreground",e),...t}));Zu.displayName="Muted";const em=n.forwardRef(({className:e,...t},r)=>a("code",{ref:r,className:Vi("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",e),...t}));em.displayName="InlineCode";const am=n.forwardRef(({className:e,...t},r)=>a("blockquote",{ref:r,className:Vi("mt-6 border-l-2 pl-6 italic",e),...t}));am.displayName="Blockquote";const tm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Vi("my-6 ml-6 list-disc [&>li]:mt-2",e),...t}));tm.displayName="List";const rm=n.forwardRef(({className:e,children:r,...n},i)=>t(Tt.Root,{ref:i,className:Vi("relative z-10 flex max-w-max flex-1 items-center justify-center",e),...n,children:[r,a(cm,{})]}));rm.displayName=Tt.Root.displayName;const nm=n.forwardRef(({className:e,...t},r)=>a(Tt.List,{ref:r,className:Vi("group flex flex-1 list-none items-center justify-center space-x-1",e),...t}));nm.displayName=Tt.List.displayName;const im=Tt.Item,sm=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"),om=n.forwardRef(({className:e,children:r,...n},i)=>t(Tt.Trigger,{ref:i,className:Vi(sm(),"group",e),...n,children:[r," ",a(E,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));om.displayName=Tt.Trigger.displayName;const lm=n.forwardRef(({className:e,...t},r)=>a(Tt.Content,{ref:r,className:Vi("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}));lm.displayName=Tt.Content.displayName;const dm=Tt.Link,cm=n.forwardRef(({className:e,...t},r)=>a("div",{className:Vi("absolute left-0 top-full flex justify-center"),children:a(Tt.Viewport,{className:Vi("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})}));cm.displayName=Tt.Viewport.displayName;const um=n.forwardRef(({className:e,...t},r)=>a(Tt.Indicator,{ref:r,className:Vi("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 mm({items:e,maxItems:n=3,className:i}){const s=e.length>n?[e[0],...e.slice(-(n-1))]:e,o=e.length>n;return a(cu,{className:i,children:a(uu,{children:s.map((e,n)=>{const i=o&&1===n;return t(mu,{children:[!(0===n)&&a(fu,{}),i&&t(r,{children:[a(gu,{}),a(fu,{})]}),e.isCurrentPage?a(hu,{children:e.label}):a(pu,{asChild:!0,children:a(xt,{to:e.href||"/",children:e.label})})]},e.label)})})})}function pm(){const e=vt();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,s=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:s,href:i?void 0:r,isCurrentPage:i})}),t})()}um.displayName=Tt.Indicator.displayName;const hm=({className:e,...t})=>a("nav",{role:"navigation","aria-label":"pagination",className:Vi("mx-auto flex w-full justify-center",e),...t});hm.displayName="Pagination";const fm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Vi("flex flex-row items-center gap-1",e),...t}));fm.displayName="PaginationContent";const gm=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Vi("",e),...t}));gm.displayName="PaginationItem";const vm=({className:e,isActive:t,size:r="icon",...n})=>a("a",{"aria-current":t?"page":void 0,className:Vi(Ki({variant:t?"outline":"ghost",size:r}),e),...n});vm.displayName="PaginationLink";const bm=({className:r,...n})=>t(vm,{"aria-label":e.t("go_to_previous_page"),size:"default",className:Vi("gap-1 pl-2.5",r),...n,children:[a(Te,{className:"h-4 w-4"}),a("span",{children:"Previous"})]});bm.displayName="PaginationPrevious";const xm=({className:r,...n})=>t(vm,{"aria-label":e.t("go_to_next_page"),size:"default",className:Vi("gap-1 pr-2.5",r),...n,children:[a("span",{children:"Next"}),a(F,{className:"h-4 w-4"})]});xm.displayName="PaginationNext";const ym=({className:e,...r})=>t("span",{"aria-hidden":!0,className:Vi("flex h-9 w-9 items-center justify-center",e),...r,children:[a(na,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"More pages"})]});ym.displayName="PaginationEllipsis";const Nm=n.forwardRef(({className:e,value:t,...r},n)=>a(It.Root,{ref:n,className:Vi("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...r,children:a(It.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Nm.displayName=It.Root.displayName;const wm=n.forwardRef(({className:e,...t},r)=>a(Rt.Root,{className:Vi("grid gap-2",e),...t,ref:r}));wm.displayName=Rt.Root.displayName;const _m=n.forwardRef(({className:e,...t},r)=>a(Rt.Item,{ref:r,className:Vi("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(Rt.Indicator,{className:"flex items-center justify-center",children:a(j,{className:"h-2.5 w-2.5 fill-current text-current"})})}));_m.displayName=Rt.Item.displayName;const Cm=({className:e,...t})=>a(Mt.PanelGroup,{className:Vi("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),km=Mt.Panel,Sm=({withHandle:e,className:t,...r})=>a(Mt.PanelResizeHandle,{className:Vi("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(ee,{className:"h-2.5 w-2.5"})})}),Am=Wa.Root,Em=Wa.Trigger,Dm=Wa.Close,Pm=Wa.Portal,Tm=n.forwardRef(({className:e,...t},r)=>a(Wa.Overlay,{className:Vi("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}));Tm.displayName=Wa.Overlay.displayName;const Im=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"}}),Rm=n.forwardRef(({side:e="right",className:r,children:n,...i},s)=>t(Pm,{children:[a(Tm,{}),t(Wa.Content,{ref:s,className:Vi(Im({side:e}),r),...i,children:[n,t(Wa.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(A,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]})]}));Rm.displayName=Wa.Content.displayName;const Mm=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Vi("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(ss,{className:"mt-2"})]});Mm.displayName="SheetHeader";const Lm=({className:e,...t})=>a("div",{className:Vi("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",e),...t});Lm.displayName="SheetBody";const zm=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(ss,{className:"mb-4"}),a("div",{className:Vi("flex flex-row justify-end gap-2",e),...n,children:r})]});zm.displayName="SheetFooter";const Fm=n.forwardRef(({className:e,...t},r)=>a(Wa.Title,{ref:r,className:Vi("text-lg font-semibold text-foreground",e),...t}));Fm.displayName=Wa.Title.displayName;const jm=n.forwardRef(({className:e,...t},r)=>a(Wa.Description,{ref:r,className:Vi("text-sm text-muted-foreground",e),...t}));jm.displayName=Wa.Description.displayName;const Um="sidebar:state",Om=n.createContext(null);function Bm(){const e=n.useContext(Om);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const $m=n.forwardRef(({defaultOpen:e=!0,open:t,onOpenChange:r,className:i,style:s,children:o,...l},d)=>{const c=Ll(),[u,m]=n.useState(!1),[p,h]=n.useState(()=>{if("undefined"!=typeof window){const a=localStorage.getItem(Um);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(Um,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(Om.Provider,{value:x,children:a(yo,{delayDuration:0,children:a("div",{className:Vi("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",...s},ref:d,...l,children:o})})})});$m.displayName="SidebarProvider";const qm=n.forwardRef(({side:e="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:s,...o},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=Bm();return"none"===n?a("div",{className:Vi("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...o,children:s}):d?a(Am,{open:u,onOpenChange:m,...o,children:t(Rm,{"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(Fm,{className:"sr-only",children:"Menu de Navegação"}),a("div",{className:"flex h-full w-full flex-col",children:s})]})}):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:Vi("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:Vi("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),...o,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:s})})]})});qm.displayName="Sidebar";const Vm=n.forwardRef(({className:e,onClick:r,...n},i)=>{const{toggleSidebar:s}=Bm();return t(Yi,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Vi("h-7 w-7",e),onClick:e=>{r?.(e),s()},...n,children:[a(ia,{}),a("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Vm.displayName="SidebarTrigger";const Wm=n.forwardRef(({className:e,...t},r)=>{const{toggleSidebar:n}=Bm();return a("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Vi("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})});Wm.displayName="SidebarRail";const Hm=n.forwardRef(({className:e,...t},r)=>a("main",{ref:r,className:Vi("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}));Hm.displayName="SidebarInset";const Gm=n.forwardRef(({className:e,...t},r)=>a(Xi,{ref:r,"data-sidebar":"input",className:Vi("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",e),...t}));Gm.displayName="SidebarInput";const Km=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"header",className:Vi("flex flex-col gap-2 p-2",e),...t}));Km.displayName="SidebarHeader";const Ym=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"footer",className:Vi("flex flex-col gap-2 p-2",e),...t}));Ym.displayName="SidebarFooter";const Qm=n.forwardRef(({className:e,...t},r)=>a(ss,{ref:r,"data-sidebar":"separator",className:Vi("mx-2 w-auto bg-sidebar-border",e),...t}));Qm.displayName="SidebarSeparator";const Xm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"content",className:Vi("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t}));Xm.displayName="SidebarContent";const Jm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group",className:Vi("relative flex w-full min-w-0 flex-col p-2",e),...t}));Jm.displayName="SidebarGroup";const Zm=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"div",{ref:n,"data-sidebar":"group-label",className:Vi("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}));Zm.displayName="SidebarGroupLabel";const ep=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"button",{ref:n,"data-sidebar":"group-action",className:Vi("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}));ep.displayName="SidebarGroupAction";const ap=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group-content",className:Vi("w-full text-sm",e),...t}));ap.displayName="SidebarGroupContent";const tp=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu",className:Vi("flex w-full min-w-0 flex-col gap-1",e),...t}));tp.displayName="SidebarMenu";const rp=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,"data-sidebar":"menu-item",className:Vi("group/menu-item relative",e),...t}));rp.displayName="SidebarMenuItem";const np=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"}}),ip=n.forwardRef(({asChild:e=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:s,className:o,...l},d)=>{const c=e?g:"button",{isMobile:u,state:m}=Bm(),p=a(c,{ref:d,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Vi(np({variant:n,size:i}),o),...l});return s?("string"==typeof s&&(s={children:s}),t(No,{children:[a(wo,{asChild:!0,children:p}),a(_o,{side:"right",align:"center",hidden:"collapsed"!==m||u,...s})]})):p});ip.displayName="SidebarMenuButton";const sp=n.forwardRef(({className:e,asChild:t=!1,showOnHover:r=!1,...n},i)=>a(t?g:"button",{ref:i,"data-sidebar":"menu-action",className:Vi("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}));sp.displayName="SidebarMenuAction";const op=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"menu-badge",className:Vi("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}));op.displayName="SidebarMenuBadge";const lp=n.forwardRef(({className:e,showIcon:r=!1,...i},s)=>{const o=n.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return t("div",{ref:s,"data-sidebar":"menu-skeleton",className:Vi("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":o}})]})});lp.displayName="SidebarMenuSkeleton";const dp=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu-sub",className:Vi("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}));dp.displayName="SidebarMenuSub";const cp=n.forwardRef(({...e},t)=>a("li",{ref:t,...e}));cp.displayName="SidebarMenuSubItem";const up=n.forwardRef(({asChild:e=!1,size:t="md",isActive:r,className:n,...i},s)=>a(e?g:"a",{ref:s,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Vi("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}));up.displayName="SidebarMenuSubButton";const mp=n.forwardRef(({className:e,value:r,defaultValue:n,...i},s)=>{const o=r||n||[0];return t(Lt.Root,{ref:s,value:r,defaultValue:n,className:Vi("relative flex w-full touch-none select-none items-center",e),...i,children:[a(Lt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:a(Lt.Range,{className:"absolute h-full bg-primary"})}),o.map((e,t)=>a(Lt.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 pp({children:e,className:t}){return a("div",{className:Vi("flex flex-col h-full",t),children:a(Bo,{className:"flex-1",children:a("div",{className:"space-y-6 p-6",children:e})})})}function hp({title:e,description:r,actions:n,className:i}){return t("div",{className:Vi("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(ss,{})]})}function fp({children:e,className:t}){return a("div",{className:Vi("space-y-6",t),children:e})}mp.displayName=Lt.Root.displayName;const gp=zt.Menu,vp=zt.Group,bp=zt.Portal,xp=zt.Sub,yp=zt.RadioGroup,Np=n.forwardRef(({className:e,...t},r)=>a(zt.Root,{ref:r,className:Vi("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",e),...t}));Np.displayName=zt.Root.displayName;const wp=n.forwardRef(({className:e,...t},r)=>a(zt.Trigger,{ref:r,className:Vi("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}));wp.displayName=zt.Trigger.displayName;const _p=n.forwardRef(({className:e,inset:r,children:n,...i},s)=>t(zt.SubTrigger,{ref:s,className:Vi("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(F,{className:"ml-auto h-4 w-4"})]}));_p.displayName=zt.SubTrigger.displayName;const Cp=n.forwardRef(({className:e,...t},r)=>a(zt.SubContent,{ref:r,className:Vi("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}));Cp.displayName=zt.SubContent.displayName;const kp=n.forwardRef(({className:e,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},s)=>a(zt.Portal,{children:a(zt.Content,{ref:s,align:t,alignOffset:r,sideOffset:n,className:Vi("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})}));kp.displayName=zt.Content.displayName;const Sp=n.forwardRef(({className:e,inset:t,...r},n)=>a(zt.Item,{ref:n,className:Vi("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}));Sp.displayName=zt.Item.displayName;const Ap=n.forwardRef(({className:e,children:r,checked:n,...i},s)=>t(zt.CheckboxItem,{ref:s,className:Vi("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(zt.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),r]}));Ap.displayName=zt.CheckboxItem.displayName;const Ep=n.forwardRef(({className:e,children:r,...n},i)=>t(zt.RadioItem,{ref:i,className:Vi("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(zt.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));Ep.displayName=zt.RadioItem.displayName;const Dp=n.forwardRef(({className:e,inset:t,...r},n)=>a(zt.Label,{ref:n,className:Vi("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));Dp.displayName=zt.Label.displayName;const Pp=n.forwardRef(({className:e,...t},r)=>a(zt.Separator,{ref:r,className:Vi("-mx-1 my-1 h-px bg-muted",e),...t}));Pp.displayName=zt.Separator.displayName;const Tp=({className:e,...t})=>a("span",{className:Vi("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});Tp.displayname="MenubarShortcut";const Ip={light:"",dark:".dark"},Rp=n.createContext(null);function Mp(){const e=n.useContext(Rp);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const Lp=n.forwardRef(({id:e,className:r,children:i,config:s,...o},l)=>{const d=n.useId(),c=`chart-${e||d.replace(/:/g,"")}`;return a(Rp.Provider,{value:{config:s},children:t("div",{"data-chart":c,ref:l,className:Vi("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),...o,children:[a(zp,{id:c,config:s}),a(Ft.ResponsiveContainer,{children:i})]})})});Lp.displayName="Chart";const zp=({id:e,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?a("style",{dangerouslySetInnerHTML:{__html:Object.entries(Ip).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},Fp=Ft.Tooltip,jp=n.forwardRef(({active:e,payload:i,className:s,indicator:o="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}=Mp(),x=n.useMemo(()=>{if(l||!i?.length)return null;const[e]=i,t=Bp(b,e,`${g||e?.dataKey||e?.name||"value"}`),r=g||"string"!=typeof c?t?.label:b[c]?.label||c;return u?a("div",{className:Vi("font-medium",m),children:u(r,i)}):r?a("div",{className:Vi("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"!==o;return t("div",{ref:v,className:Vi("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",s),children:[y?null:x,a("div",{className:"grid gap-1.5",children:i.map((e,n)=>{const i=`${f||e.name||e.dataKey||"value"}`,s=Bp(b,e,i),l=h||e.payload?.fill||e.color;return a("div",{className:Vi("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:p&&void 0!==e?.value&&e.name?p(e.value,e.name,e,n,e.payload):t(r,{children:[s?.icon?a(s.icon,{}):!d&&a("div",{className:Vi("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":y&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),t("div",{className:Vi("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:s?.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)})})]})});jp.displayName="ChartTooltip";const Up=Ft.Legend,Op=n.forwardRef(({className:e,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:s},o)=>{const{config:l}=Mp();return n?.length?a("div",{ref:o,className:Vi("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",e),children:n.map(e=>{const n=`${s||e.dataKey||"value"}`,i=Bp(l,e,n);return t("div",{className:Vi("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 Bp(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]}Op.displayName="ChartLegend";const $p=({onClick:e,isActive:t,disabled:r,children:n,title:i})=>a("button",{type:"button",onClick:e,disabled:r,title:i,className:Vi("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}),qp=()=>a("div",{className:"w-px h-5 bg-border mx-1"}),Vp=({value:r,onChange:i,disabled:o,placeholder:d=e.t("write_content_here"),minHeight:c="300px",showModeToggle:u=!0,showVariableHint:m=!0,className:p})=>{const{t:h}=nt(),[f,g]=s("visual"),v=er({extensions:[tr.configure({heading:{levels:[1,2,3]}}),rr,nr.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),ir,sr,or.configure({multicolor:!0})],content:r||"",editable:!o,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:Vi("space-y-2",p),children:[u&&t("div",{className:"flex justify-between items-center",children:[t("div",{className:"flex gap-1",children:[t(Yi,{type:"button",size:"sm",variant:"visual"===f?"default":"outline",onClick:()=>g("visual"),disabled:o,children:[a(sa,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),t(Yi,{type:"button",size:"sm",variant:"code"===f?"default":"outline",onClick:()=>g("code"),disabled:o,children:[a(oa,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),t(Yi,{type:"button",size:"sm",variant:"preview"===f?"default":"outline",onClick:()=>g("preview"),disabled:o,children:[a(pe,{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($p,{onClick:()=>v.chain().focus().toggleHeading({level:1}).run(),isActive:v.isActive("heading",{level:1}),disabled:o,title:e.t("heading_1"),children:a(la,{className:"h-4 w-4"})}),a($p,{onClick:()=>v.chain().focus().toggleHeading({level:2}).run(),isActive:v.isActive("heading",{level:2}),disabled:o,title:e.t("heading_2"),children:a(da,{className:"h-4 w-4"})}),a($p,{onClick:()=>v.chain().focus().toggleHeading({level:3}).run(),isActive:v.isActive("heading",{level:3}),disabled:o,title:e.t("heading_3"),children:a(ca,{className:"h-4 w-4"})}),a(qp,{}),a($p,{onClick:()=>v.chain().focus().toggleBold().run(),isActive:v.isActive("bold"),disabled:o,title:e.t("bold"),children:a(ua,{className:"h-4 w-4"})}),a($p,{onClick:()=>v.chain().focus().toggleItalic().run(),isActive:v.isActive("italic"),disabled:o,title:e.t("italic"),children:a(ma,{className:"h-4 w-4"})}),a($p,{onClick:()=>v.chain().focus().toggleUnderline().run(),isActive:v.isActive("underline"),disabled:o,title:"Sublinhado",children:a(pa,{className:"h-4 w-4"})}),a($p,{onClick:()=>v.chain().focus().toggleStrike().run(),isActive:v.isActive("strike"),disabled:o,title:"Riscado",children:a(ha,{className:"h-4 w-4"})}),a(qp,{}),a($p,{onClick:()=>v.chain().focus().toggleBulletList().run(),isActive:v.isActive("bulletList"),disabled:o,title:"Lista",children:a(X,{className:"h-4 w-4"})}),a($p,{onClick:()=>v.chain().focus().toggleOrderedList().run(),isActive:v.isActive("orderedList"),disabled:o,title:h("ordered_list"),children:a(fa,{className:"h-4 w-4"})}),a(qp,{}),a($p,{onClick:()=>v.chain().focus().toggleHighlight().run(),isActive:v.isActive("highlight"),disabled:o,title:"Destacar",children:a(ga,{className:"h-4 w-4"})}),a($p,{onClick:b,isActive:v.isActive("link"),disabled:o,title:"Link",children:a(va,{className:"h-4 w-4"})}),a(qp,{}),a($p,{onClick:()=>v.chain().focus().unsetAllMarks().clearNodes().run(),disabled:o,title:h("clear_formatting"),children:a(ba,{className:"h-4 w-4"})}),a(qp,{}),a($p,{onClick:()=>v.chain().focus().undo().run(),disabled:o||!v.can().undo(),title:"Desfazer",children:a(xa,{className:"h-4 w-4"})}),a($p,{onClick:()=>v.chain().focus().redo().run(),disabled:o||!v.can().redo(),title:"Refazer",children:a(ya,{className:"h-4 w-4"})})]}),a(ar,{editor:v,className:Vi("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:o,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 Wp({image:e,title:t,className:r}){return a("div",{className:Vi("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(Na,{className:"w-16 h-16 text-muted-foreground"})})})}function Hp({steps:e,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:s}){const{t:o}=nt(),l=e.length,d=(r+1)/l*100;return t("div",{className:Vi("flex items-center gap-3",s),children:[t(no,{children:[a(io,{asChild:!0,children:t(Yi,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",l,a(E,{className:"h-3 w-3 ml-1"})]})}),a(po,{align:"start",children:e.map((e,a)=>t(ho,{onClick:()=>n(a),className:Vi(a===r&&"bg-accent"),children:[a+1,". ",e.title]},e.id))})]}),a(Nm,{value:d,className:"w-32 h-2"})]})}function Gp({currentStepIndex:e,totalSteps:r,onBack:n,onNext:i,onComplete:s,backButtonText:o,continueButtonText:l,finishButtonText:d,className:c}){const{t:u}=nt(),m=0===e,p=e===r-1;return t("div",{className:Vi("flex items-center gap-2",c),children:[!m&&t(Yi,{variant:"outline",onClick:n,size:"sm",children:[a(Pe,{className:"h-4 w-4 mr-2"}),o]}),t(Yi,{onClick:p?s:i,size:"sm",children:[p?d:l,!p&&a(De,{className:"h-4 w-4 ml-2"})]})]})}const Kp=n.forwardRef(({open:r,onOpenChange:i,steps:s,onComplete:o,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=s[w],k=s.length;return C?a(bs,{open:r,onOpenChange:i,children:t(Cs,{ref:b,size:p,variant:"informative",className:Vi("p-0 gap-0 overflow-hidden",v),children:[t(Ns,{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(A,{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(Wp,{image:C.image,title:C.title}),a(Es,{className:"text-xl font-semibold",children:C.title}),a(Ds,{className:"text-muted-foreground",children:C.description})]})}),t("div",{className:"flex-shrink-0",children:[a(ss,{}),t("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?a(Hp,{steps:s,currentStepIndex:w,onStepSelect:e=>{_(e)},stepLabel:m}):a("div",{}),a(Gp,{currentStepIndex:w,totalSteps:k,onBack:()=>{w>0&&_(w-1)},onNext:()=>{w<k-1&&_(w+1)},onComplete:()=>{o?.(),i(!1)},backButtonText:c,continueButtonText:d,finishButtonText:u})]})]})]})}):null});function Yp({label:e,onClick:r,icon:n,actions:i=[],variant:s="default",size:o="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const{t:m}=nt(),p=l||d;if(!(i.length>0))return t(Yi,{variant:s,size:o,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:Vi("inline-flex rounded-md shadow-sm",u),children:[t(Yi,{variant:s,size:o,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(no,{children:[a(io,{asChild:!0,children:a(Yi,{variant:s,size:o,disabled:p,className:Vi("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":m("more_options"),children:a(E,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),a(po,{align:c,className:"min-w-[160px]",children:i.map(e=>{const r=e.icon;return t(ho,{onClick:e.onClick,disabled:e.disabled,className:Vi("destructive"===e.variant&&"text-destructive focus:text-destructive"),children:[r&&a(r,{className:"mr-2 h-4 w-4"}),e.label]},e.id)})})]})]})}var Qp,Xp;Kp.displayName="OnboardingDialog",(Xp=Qp||(Qp={})).CSV="csv",Xp.PDF="pdf",Xp.XLSX="xlsx",Xp.PNG="png",Xp.JPEG="jpeg",Xp.SVG="svg";const Jp=[{value:Qp.CSV,label:"CSV",icon:a(xe,{className:"h-5 w-5"})},{value:Qp.PDF,label:"PDF",icon:a(xe,{className:"h-5 w-5"})},{value:Qp.XLSX,label:"XLSX",icon:a(wa,{className:"h-5 w-5"})}],Zp=[{value:Qp.PNG,label:"PNG",icon:a(je,{className:"h-5 w-5"})},{value:Qp.JPEG,label:"JPEG",icon:a(_a,{className:"h-5 w-5"})},{value:Qp.SVG,label:"SVG",icon:a(_a,{className:"h-5 w-5"})},{value:Qp.PDF,label:"PDF",icon:a(xe,{className:"h-5 w-5"})}];function eh({open:e,onOpenChange:r,onExport:n,mode:i="table",options:o,title:l,description:d,cancelLabel:c="Cancelar",exportLabel:u="Exportar"}){const{t:m}=nt(),[p,h]=s(""),f=o??("chart"===i?Zp:Jp),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(bs,{open:e,onOpenChange:b,children:t(Cs,{className:"sm:max-w-md",variant:"form",isDirty:!!p,children:[a(ks,{children:a(Es,{children:g})}),t("div",{className:"py-4",children:[a("p",{className:"text-sm text-muted-foreground mb-4",children:v}),a(wm,{value:p,onValueChange:h,className:"gap-3",children:f.map(e=>t("div",{className:"flex items-center space-x-3",children:[a(_m,{value:e.value,id:`export-${e.value}`}),t(Zi,{htmlFor:`export-${e.value}`,className:Vi("flex items-center gap-2 cursor-pointer font-normal",p===e.value&&"font-medium"),children:[e.icon,e.label]})]},e.value))})]}),t(As,{children:[a(Yi,{variant:"outline",onClick:()=>b(!1),children:c}),a(Yi,{onClick:()=>{p&&(n(p),r(!1),h(""))},disabled:!p,children:u})]})]})})}const ah=f(({value:e,onChange:r,onTimeChange:i,label:s,error:o,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:Vi("grid gap-1.5",c),children:[s&&a(Zi,{htmlFor:h,children:s}),t("div",{className:"relative",children:[a(Xi,{ref:p,id:h,type:"time",value:e??"",onChange:f,onKeyDown:g,min:"00:00",max:"23:59",step:60,className:Vi("pr-9",o&&"border-destructive focus-visible:ring-destructive"),...m}),a(Ee,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),o&&a("p",{className:"text-sm text-destructive",children:o})]})});function th({open:r,onOpenChange:n,onConfirm:i,onGenerateCode:o,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]=s(""),[_,C]=s(!1),[k,S]=s(!1),[A,E]=s(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(o){S(!0),E(null);try{await o()}catch{E(e.t("esign_resend_error"))}finally{S(!1)}}},[o]),T=e=>{e||(w(""),E(null)),n(e)},I=b?fe:Ca,R=b?"Senha":e.t("verification_code"),M=b?e.t("enter_password"):e.t("enter_code");return a(bs,{open:r,onOpenChange:T,children:t(Cs,{className:"sm:max-w-md",variant:"form",isDirty:!!N,children:[a(ks,{children:t(Es,{className:"flex items-center gap-2",children:[a(I,{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(qe,{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(Zi,{htmlFor:"signature-input",children:R}),a(Xi,{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:Vi(A&&"border-destructive focus-visible:ring-destructive")}),A&&a("p",{className:"text-sm text-destructive",children:A})]}),!b&&t(Yi,{variant:"ghost",size:"sm",onClick:P,disabled:k,className:"text-primary",children:[a(Ze,{className:Vi("h-4 w-4 mr-1",k&&"animate-spin")}),g]})]}),t(As,{children:[a(Yi,{variant:"outline",onClick:()=>T(!1),disabled:_,children:f}),a(Yi,{onClick:D,disabled:!N.trim()||_,children:_?"Validando...":h})]})]})})}function rh({currentStep:e,totalSteps:r,onStepChange:i,stepLabels:s,canGoToStep:o,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)&&(!!o&&!o(a));return t("div",{className:Vi("flex items-center gap-3",l),children:[t(no,{children:[a(io,{asChild:!0,children:t(Yi,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",e,"/",r,a(E,{className:"h-3 w-3 ml-1"})]})}),a(po,{align:"start",children:c.map(r=>t(ho,{onClick:()=>{var a;(a=r)<e?i(a):o&&!o(a)||i(a)},disabled:u(r),className:Vi("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,"."]}),s?.[r-1]||`Etapa ${r}`,r===e&&a(P,{className:"h-4 w-4 ml-auto"})]},r))})]}),a(Nm,{value:e/r*100,className:Vi("h-2",d)})]})}function nh({open:r,onOpenChange:n,currentStep:i,onStepChange:s,steps:o,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}=nt(),E=o.length,D=i>=E,T=i<=1;return a(bs,{open:r,onOpenChange:n,children:t(Cs,{size:b,variant:g,isDirty:v,unsavedChangesTitle:x,unsavedChangesDescription:y,cancelText:N,leaveWithoutSavingText:w,className:Vi("!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:o.map((e,r)=>{const n=r+1,o=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?s(e):l&&!l(e)||s(e))})(n),disabled:!c,className:Vi("flex items-center gap-3 py-2.5 px-3 rounded-md text-left transition-colors text-sm",o&&"bg-primary-foreground/20 font-semibold",!o&&c&&"hover:bg-primary-foreground/10 cursor-pointer",!c&&"opacity-40 cursor-not-allowed"),children:[a("span",{className:Vi("flex items-center justify-center h-7 w-7 rounded-full text-xs font-bold flex-shrink-0 transition-colors",o&&"bg-primary-foreground text-primary",d&&!o&&"bg-primary-foreground/30 text-primary-foreground",!o&&!d&&"border-2 border-primary-foreground/40 text-primary-foreground/60"),children:d&&!o?a(P,{className:"h-3.5 w-3.5"}):n}),a("span",{className:Vi("truncate",o&&"text-primary-foreground",!o&&"text-primary-foreground/70"),children:e})]},n)})})]}),t("div",{className:"flex flex-col flex-1 min-w-0",children:[t(ks,{className:"p-6 pb-0",children:[t("p",{className:"text-xs text-muted-foreground sm:hidden mb-1",children:["Etapa ",i," de ",E]}),a(Es,{children:c}),u&&a("p",{className:"text-sm text-muted-foreground mt-1",children:u})]}),a(Ss,{className:"px-6",children:d}),!k&&a(As,{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:[!T&&a(Yi,{variant:"outline",onClick:()=>s(i-1),children:f}),a(Yi,D?{onClick:m,disabled:C,children:p}:{onClick:()=>s(i+1),disabled:C,children:h})]})]})})]})]})})}function ih(e){const a=nl.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 sh(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await pl.handleApiError({status:401})){const n={...a,headers:ih(t)};r=await fetch(e,n)}}return r}function oh(e){const[a,t]=s([]),[r,n]=s(0),[i,o]=s(!1);m(()=>{if(!e)return;let a=!1;const r=`${Pr().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){o(!0);try{const i=ih(e),s=await sh(r,{method:"GET",headers:i},e);if(!s.ok)return;const o=await s.json();!a&&o.data?.[0]&&(t(o.data[0].updates??[]),n(o.data[0].valueBadge??0))}catch(i){}finally{a||o(!1)}}(),()=>{a=!0}},[e]);const d=l(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${Pr().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=ih(e),r=JSON.stringify({id:t,idUpdateType:3});await sh(i,{method:"POST",headers:a,body:r},e)}catch(s){}},[e,r,a]);return{updates:a,badgeCount:r,loading:i,markAsVisualized:d}}ah.displayName="Timepicker";const lh=i.forwardRef(({updates:r,badgeCount:n,onOpen:i,onViewAll:s},o)=>{const l=void 0===r,d=Tl(),c=d?.alias??null,u=oh(l?c:null),m=l?u.updates??[]:r,p=l?u.badgeCount??0:n??0,h=i??(l?u.markAsVisualized:void 0),f=s??(l&&c?()=>{const e=`https://apps4.qualiex.com/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return t(ko,{children:[a(So,{asChild:!0,children:t(Yi,{ref:o,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(ka,{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(Ao,{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(ka,{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(Yi,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:f,children:["Ver todas as atualizações",a(De,{className:"h-[18px] w-[18px]"})]})})]})]})});var dh,ch,uh,mh;lh.displayName="UpdatesNotification",(ch=dh||(dh={}))[ch.none=0]="none",ch[ch.image=1]="image",ch[ch.video=2]="video",ch[ch.audio=3]="audio",ch[ch.wopi=4]="wopi",ch[ch.onlineEditor=5]="onlineEditor",ch[ch.report=6]="report",(mh=uh||(uh={}))[mh.SimplePrint=0]="SimplePrint",mh[mh.ManagedCopy=1]="ManagedCopy",mh[mh.NonManagedCopy=2]="NonManagedCopy";const ph={".jpg":dh.image,".jpeg":dh.image,".png":dh.image,".bmp":dh.image,".gif":dh.image,".svg":dh.image,".webp":dh.image,".wav":dh.audio,".mp3":dh.audio,".mp4":dh.video,".webm":dh.video,".ogg":dh.video,".pdf":dh.wopi,".ods":dh.wopi,".xls":dh.wopi,".xlsb":dh.wopi,".xlsm":dh.wopi,".xlsx":dh.wopi,".doc":dh.wopi,".docm":dh.wopi,".docx":dh.wopi,".dot":dh.wopi,".dotm":dh.wopi,".dotx":dh.wopi,".odt":dh.wopi,".odp":dh.wopi,".pot":dh.wopi,".potm":dh.wopi,".potx":dh.wopi,".pps":dh.wopi,".ppsm":dh.wopi,".ppsx":dh.wopi,".ppt":dh.wopi,".pptm":dh.wopi,".pptx":dh.wopi,".gdocs":dh.onlineEditor,".gsheets":dh.onlineEditor};function hh(e){const{t:a}=nt();return e?ph[e.toLowerCase()]??dh.none:dh.none}function fh(e){const{t:a}=nt();return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"}const gh={".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 vh(e){const{t:a}=nt();return gh[e?.toLowerCase()]||""}function bh(e){const{t:a}=nt(),{viewerUrl:t,wopiUrl:r,fileId:n,token:i,extension:s,language:o="pt-br"}=e,l=vh(s);if(!l)return null;return`${t}${l}ui=${o}&rs=${o}&access_token=${i}&WOPISrc=${encodeURIComponent(`${r}${n}`)}`}function xh({open:e,onOpenChange:n,template:i,viewerType:s,isLoading:o=!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}=nt(),S=u(null),E=s??hh(i.extension),D=p||N||v,P=i.code?`${i.code} – ${i.name}`:i.name,T=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(bs,{open:e,onOpenChange:n,children:t(Cs,{className:Vi("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(E===dh.wopi||E===dh.report)&&"w-[90vw]",C),children:[t("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[a("h2",o?{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:[!o&&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(Sa,{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:yh(w)}),a("span",{children:"segundos"})]}):t(Yi,{variant:"default",size:"sm",disabled:D,onClick:()=>y?.(),className:"mr-2.5",children:[a(Ca,{className:"h-4 w-4 mr-1"}),N?"Confirmando...":k("terms_confirm_reading")]})}),E!==dh.none&&h&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>g?.(f),children:a(Ke,{className:Vi("h-4 w-4",f&&"fill-accent text-accent")})})}),a(_o,{children:f?"Desfavoritar":"Favoritar"})]}),E!==dh.none&&d&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>c?.(),children:a(Ce,{className:"h-4 w-4"})})}),a(_o,{children:"Download"})]})]}),t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>n(!1),children:a(A,{className:"h-4 w-4"})})}),a(_o,{children:"Fechar"})]})]})]}),a("div",{className:Vi("flex flex-col items-center justify-center min-h-[160px] w-full",o&&"relative -top-5",E===dh.none&&"min-h-[124px]",E===dh.image&&"max-h-[85vh]",(E===dh.wopi||E===dh.report)&&"min-w-[77vw] min-h-[80vh]"),children:o?a(ao,{className:"h-14 w-14"}):t(r,{children:[(E===dh.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?"})]}),E===dh.image&&a("img",{loading:"eager",src:i.url,alt:i.name,className:"max-w-full max-h-[85vh] object-contain"}),E===dh.video&&a("video",{controls:!0,autoPlay:!0,src:i.url,className:"w-full h-full"}),E===dh.audio&&a("audio",{controls:!0,autoPlay:!0,src:i.url}),(E===dh.wopi||E===dh.report)&&t("div",{className:"relative w-full h-[79.5vh]",children:[a(ao,{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:T,className:"border-none w-full h-full z-[1] relative",title:i.name})]})]})}),!o&&E===dh.none&&t("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[a(Yi,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),d&&a(Yi,{variant:"default",onClick:()=>c?.(),children:"Download"})]})]})})}function yh(e){const{t:a}=nt(),t=e%60;return`${Math.floor(e/60)}min ${t<10?"0":""}${t}`}function Nh({open:e,onOpenChange:r,identifier:n,fileName:i,mode:o="edit",type:d="document",onClose:c,className:u}){const[p,h]=s(!0),f=function(e,a="edit",t="document"){return`https://docs.google.com/${t}/d/${e}/${a}?usp=drivesdk?embedded=true&rm=demo`}(n,o,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(bs,{open:e,onOpenChange:r,children:t(Cs,{className:Vi("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(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:g,children:a(A,{className:"h-4 w-4"})})}),a(_o,{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(ao,{className:"h-14 w-14"}):t("div",{className:"relative w-full h-[79.5vh]",children:[a(ao,{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 wh({open:e,onOpenChange:r,url:n,title:i,className:s,minHeight:o="250px"}){const{t:d}=nt(),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(bs,{open:e,onOpenChange:r,children:t(Cs,{className:Vi("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",s),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(No,{children:[a(wo,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c,children:a(A,{className:"h-4 w-4"})})}),a(_o,{children:"Fechar"})]})]}),a("iframe",{src:n,className:"border-none w-full",style:{minHeight:o},title:i||d("embedded_content")})]})})}function _h({term:n,open:i,onClose:o,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]=s(!1),g=l(()=>{d(n.id)},[d,n.id]);return t(r,{children:[a(bs,{open:i&&!h,onOpenChange:e=>!e&&o(),children:t(Cs,{className:"sm:max-w-md",children:[a(ks,{children:t(Es,{className:"flex items-center gap-2",children:[a(Ca,{className:"h-5 w-5 text-primary"}),c]})}),t("div",{className:"space-y-4",children:[n.description&&a(Bo,{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(Yi,{variant:"link",className:"px-0 text-primary",onClick:()=>f(!0),children:[a(ea,{className:"mr-1 h-4 w-4"}),p]})]}),t(As,{className:"gap-2 sm:gap-0",children:[a(Yi,{variant:"ghost",onClick:o,children:u}),a(Yi,{onClick:g,children:m})]})]})}),h&&a(Ch,{term:n,open:h,onClose:()=>f(!1),viewOnly:!0})]})}function Ch({term:r,open:n,onClose:i,onSign:s,viewOnly:d=!1,title:c=e.t("terms_of_use"),signLabel:u=e.t("terms_read_agree")}){const m=o(()=>r.file?function(e,a=""){const{t:t}=nt(),r=atob(e),n=[];for(let s=0;s<r.length;s+=512){const e=r.slice(s,s+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():s?.(r.id)},[r,s,p]),f=!d&&!r.hasUserSignature&&s;return a(bs,{open:n,onOpenChange:e=>!e&&p(),children:t(Cs,{className:Vi("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(xe,{className:"h-5 w-5 text-primary"}),c]}),t("div",{className:"flex items-center gap-2",children:[f&&a(Yi,{size:"sm",onClick:h,children:u}),a(Yi,{variant:"ghost",size:"icon",onClick:p,children:a(A,{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 kh(e){const{t:a}=nt();return e.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join("")}function Sh(e){const{t:a}=nt();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Ah({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]=s(!1),[_,C]=s(""),[k,S]=s(void 0),A=o(()=>new Set(i),[i]),E=o(()=>{let e=r;if(k&&(e=e.filter(e=>e.groupIds?.includes(k))),_){const a=Sh(_);e=e.filter(e=>Sh(e.name).includes(a)||Sh(e.email??"").includes(a))}return e},[r,k,_]),D=o(()=>N?E:r.filter(e=>A.has(e.id)),[N,E,r,A]),P=i.length,T=o(()=>E.length>0&&E.every(e=>A.has(e.id)),[E,A]),I=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:Vi("rounded-md border bg-muted/30",y),children:[(!c||P>0)&&t("div",{className:Vi("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(Os,{value:k??"__all__",onValueChange:e=>S("__all__"===e?void 0:e),children:[a(qs,{className:"w-[200px] h-9 text-sm",children:a($s,{placeholder:e.t("approval_user_group")})}),t(Hs,{children:[a(Ks,{value:"__all__",children:e.t("team_all_groups")}),n.map(e=>a(Ks,{value:e.id,children:e.name},e.id))]})]}),t("div",{className:"relative flex-1",children:[a(O,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Xi,{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(Aa,{className:"h-4 w-4 mr-2"}),v]}),N&&E.length>0&&t("div",{className:"flex items-center gap-2 mb-2",children:[a(Qs,{checked:T,onCheckedChange:e=>R(!!e)}),a("span",{className:"text-sm",children:g})]}),D.length>0&&a(Bo,{style:{maxHeight:u},className:"pr-2",children:a("div",{className:"space-y-0.5",children:D.map(e=>t("div",{className:Vi("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?()=>I(e.id):void 0,children:[N&&a(Qs,{checked:A.has(e.id),onCheckedChange:()=>I(e.id),onClick:e=>e.stopPropagation()}),t(ou,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(lu,{src:e.avatar,alt:e.name}),a(du,{className:"text-xs",children:kh(e.name)})]}),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))})}),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 Eh(e){const{t:a}=nt();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Dh(e){const{t:a}=nt(),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 Ph({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]=s(n[0]?.id??""),[k,S]=s(""),[D,T]=s([]),[I,R]=s(!1),M=o(()=>Dh(i[_]),[i,_]),L=o(()=>function(e){const{t:a}=nt(),t=new Set;if(!e)return t;for(const r of e)r.inheritedIds?.forEach(e=>t.add(e));return t}(i[_]),[i,_]),z=o(()=>r.filter(e=>M.has(e.id)),[r,M]),F=o(()=>{const e=Eh(k);return r.filter(a=>!M.has(a.id)&&!(e&&!Eh(a.name).includes(e)))},[r,M,k]),j=o(()=>{const e={};for(const a of n)e[a.id]=Dh(i[a.id]).size;return e},[n,i]),U=l(e=>{C(e),T([]),S("")},[]),B=l(e=>{T(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),$=l(()=>{if(0===D.length)return;const e=[...i[_]??[]];for(const a of D){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}),T([]),S(""),R(!1)},[D,i,_,r,d]),q=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:Vi("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:Vi("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(Os,{value:_,onValueChange:U,children:[a(qs,{className:"h-9 text-sm",children:a($s,{})}),a(Hs,{children:n.map(e=>a(Ks,{value:e.id,children:t("span",{className:"flex items-center gap-2",children:[e.icon,e.name,j[e.id]>0&&a(Zs,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:j[e.id]})]})},e.id))})]})]}),!c&&t("div",{className:"flex gap-2",children:[t(ko,{open:I,onOpenChange:R,children:[a(So,{asChild:!0,children:t(Yi,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[D.length>0?`${D.length} selecionado${D.length>1?"s":""}`:v,a(E,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t(Ao,{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(O,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Xi,{className:"pl-8 h-8 text-sm",placeholder:g,value:k,onChange:e=>S(e.target.value)})]})}),a(Bo,{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=D.includes(e.id);return t("div",{className:Vi("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",r&&"bg-accent/50"),onClick:()=>B(e.id),children:[a("div",{className:Vi("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",r&&"bg-primary text-primary-foreground"),children:r&&a(P,{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(Yi,{size:"sm",className:"h-9 gap-1",disabled:0===D.length,onClick:$,children:[a(Y,{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:Vi("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(Zs,{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:()=>q(e.id),children:a(A,{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 Th,Ih;(Ih=Th||(Th={}))[Ih.WaitingProcessing=1]="WaitingProcessing",Ih[Ih.Processing=2]="Processing",Ih[Ih.Completed=3]="Completed",Ih[Ih.Error=4]="Error",Ih[Ih.Expired=5]="Expired";const Rh={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 Mh(e){const{t:a}=nt();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function Lh(e){const{t:a}=nt();return e.toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}function zh({requests:e,isLoading:n=!1,onGetReportUrl:i,formatDate:d=Lh,labels:c,className:u}){const{t:m}=nt(),p={...Rh,...c},[h,f]=s(""),[g,v]=s(!1),[b,x]=s(""),[y,N]=s(""),[w,_]=s(null),C=o(()=>{if(!h)return e;const a=Mh(h);return e.filter(e=>Mh(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:Vi("space-y-3",u),children:Array.from({length:5}).map((e,t)=>a(Fo,{className:"h-12 w-full"},t))}):t(r,{children:[t("div",{className:Vi("space-y-3",u),children:[t("div",{className:"relative max-w-sm",children:[a(O,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Xi,{className:"pl-8 h-9 text-sm",placeholder:p.searchPlaceholder,value:h,onChange:e=>f(e.target.value)})]}),a(Bo,{className:"rounded-md border",children:t(zl,{children:[a(Fl,{children:t(Ol,{children:[a(Bl,{className:"min-w-[140px]",children:p.report}),a(Bl,{className:"min-w-[150px]",children:p.status}),a(Bl,{className:"min-w-[160px]",children:p.requestDate}),a(Bl,{className:"min-w-[160px]",children:p.lastUpdate}),a(Bl,{className:"min-w-[160px]",children:p.expirationDate}),a(Bl,{className:"min-w-[140px]"})]})}),a(jl,{children:0===C.length?a(Ol,{children:a($l,{colSpan:6,className:"text-center text-muted-foreground py-8",children:p.noResults})}):C.map(e=>{const r=function(e){const{t:a}=nt();return new Date>new Date(e.expirationDate)&&e.statusId===Th.Completed?Th.Expired:e.statusId}(e),n=function(e,t){const{t:r}=nt();switch(e){case Th.WaitingProcessing:return{label:t.statusWaiting,icon:a(Pa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case Th.Processing:return{label:t.statusProcessing,icon:a(Ze,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case Th.Completed:return{label:t.statusCompleted,icon:a(Da,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case Th.Error:return{label:t.statusError,icon:a(U,{className:"h-3.5 w-3.5"}),variant:"danger"};case Th.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===Th.Completed,s=r===Th.Expired;return t(Ol,{children:[a($l,{className:"font-medium",children:e.reportName}),a($l,{children:t(Zs,{variant:n.variant,className:Vi("gap-1",n.className),children:[n.icon,n.label]})}),a($l,{className:"text-sm",children:d(new Date(e.requestDate))}),a($l,{className:"text-sm",children:d(new Date(e.lastUpdate))}),a($l,{className:Vi("text-sm",s&&"text-destructive"),children:d(new Date(e.expirationDate))}),a($l,{children:t(Yi,{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(pe,{className:"h-4 w-4"}),p.viewReport]})})]},e.id)})})]})})]}),a(wh,{open:g,onOpenChange:v,url:b,title:y})]})}function Fh({reportApiUrl:e,parameters:t={},minHeight:r="80vh",...n}){const i=o(()=>{const a=`${e}/api/reports/v1/Viewer/InitViewer`,r=new URLSearchParams(t).toString();return r?`${a}?${r}`:a},[e,t]);return a(wh,{...n,url:i,minHeight:r})}var jh,Uh,Oh,Bh,$h,qh,Vh,Wh,Hh,Gh,Kh,Yh,Qh,Xh,Jh,Zh,ef,af,tf,rf,nf,sf,of,lf,df,cf,uf,mf,pf,hf,ff,gf,vf,bf,xf,yf,Nf,wf,_f,Cf,kf,Sf,Af,Ef,Df,Pf,Tf,If,Rf,Mf,Lf;(Uh=jh||(jh={})).Count="valuecount",Uh.Sum="sum",Uh.Average="average",Uh.DistinctCount="valuecount_distict",Uh.Max="max",Uh.Min="min",(Oh||(Oh={})).ViewAllAnalysis="nes3j6wn",($h=Bh||(Bh={})).RegisterDashboards="EeKs7CYA",$h.RemoveDashboards="3GKZYOQ9",$h.ViewAllDashboards="wYBdQNvZ",$h.EditDashboards="bMFcbwv4",(Vh=qh||(qh={}))[Vh.Default=1]="Default",Vh[Vh.Compact=2]="Compact",(Hh=Wh||(Wh={}))[Hh.FiveSeconds=1]="FiveSeconds",Hh[Hh.TenSeconds=2]="TenSeconds",Hh[Hh.FifteenSeconds=3]="FifteenSeconds",Hh[Hh.ThirtySeconds=4]="ThirtySeconds",Hh[Hh.OneMinute=5]="OneMinute",Hh[Hh.ThreeMinutes=6]="ThreeMinutes",Hh[Hh.FiveMinutes=7]="FiveMinutes",Hh[Hh.TenMinutes=8]="TenMinutes",(Kh=Gh||(Gh={}))[Kh.Day=1]="Day",Kh[Kh.Month=2]="Month",Kh[Kh.Year=3]="Year",(Qh=Yh||(Yh={}))[Qh.Ascending=1]="Ascending",Qh[Qh.Descending=2]="Descending",(Jh=Xh||(Xh={}))[Jh.Label=1]="Label",Jh[Jh.Value=2]="Value",(ef=Zh||(Zh={}))[ef.LastSevenDays=1]="LastSevenDays",ef[ef.LastWeek=2]="LastWeek",ef[ef.LastMonth=3]="LastMonth",ef[ef.PreviousQuarter=4]="PreviousQuarter",ef[ef.PreviousSemester=5]="PreviousSemester",ef[ef.LastYear=6]="LastYear",ef[ef.SpecificPeriod=7]="SpecificPeriod",ef[ef.CurrentMonth=8]="CurrentMonth",ef[ef.CurrentSemester=9]="CurrentSemester",ef[ef.CurrentWeek=10]="CurrentWeek",ef[ef.CurrentYear=11]="CurrentYear",(tf=af||(af={}))[tf.Text=1]="Text",tf[tf.Area=2]="Area",tf[tf.Bar=3]="Bar",tf[tf.Column=4]="Column",tf[tf.StackedColumn=5]="StackedColumn",tf[tf.Line=6]="Line",tf[tf.List=7]="List",tf[tf.Numeric=8]="Numeric",tf[tf.Pareto=9]="Pareto",tf[tf.Pie=10]="Pie",tf[tf.RiskMatrix=11]="RiskMatrix",tf[tf.Burndown=12]="Burndown",tf[tf.PerformanceColumns=13]="PerformanceColumns",tf[tf.EvolutionLine=14]="EvolutionLine",(nf=rf||(rf={}))[nf.NotUpdate=1]="NotUpdate",nf[nf.FiveMinutes=2]="FiveMinutes",nf[nf.TenMinutes=3]="TenMinutes",nf[nf.FifteenMinutes=4]="FifteenMinutes",nf[nf.ThirtyMinutes=5]="ThirtyMinutes",nf[nf.OneHour=6]="OneHour",(of=sf||(sf={}))[of.NormalPage=1]="NormalPage",of[of.Carousel=2]="Carousel",(df=lf||(lf={}))[df.General=0]="General",df[df.Share=1]="Share",(uf=cf||(cf={}))[uf.NotShared=1]="NotShared",uf[uf.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",uf[uf.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(pf=mf||(mf={})).PtBr="pt-br",pf.EnUs="en",pf.EsEs="es",(ff=hf||(hf={}))[ff.Quantity=0]="Quantity",ff[ff.AllRisksList=1]="AllRisksList",(vf=gf||(gf={}))[vf.Five=5]="Five",vf[vf.Ten=10]="Ten",vf[vf.Fifteen=15]="Fifteen",vf[vf.Twenty=20]="Twenty",vf[vf.All=0]="All",vf[vf.Custom=-1]="Custom",(xf=bf||(bf={}))[xf.AlphabeticalAsc=1]="AlphabeticalAsc",xf[xf.AlphabeticalDesc=2]="AlphabeticalDesc",xf[xf.CountAsc=3]="CountAsc",xf[xf.CountDesc=4]="CountDesc",xf[xf.DateAsc=5]="DateAsc",xf[xf.DateDesc=6]="DateDesc",(Nf=yf||(yf={}))[Nf.Loading=0]="Loading",Nf[Nf.Loaded=1]="Loaded",Nf[Nf.Error=3]="Error",Nf[Nf.NoData=4]="NoData",Nf[Nf.Unavailable=5]="Unavailable",(_f=wf||(wf={}))[_f.Quantity=1]="Quantity",_f[_f.Percentage=2]="Percentage",_f[_f.QuantityPercentage=3]="QuantityPercentage",(kf=Cf||(Cf={}))[kf.Program=1]="Program",kf[kf.Project=2]="Project",kf[kf.Action=3]="Action",kf[kf.PerformanceProject=4]="PerformanceProject",kf[kf.PerformanceAction=5]="PerformanceAction",(Af=Sf||(Sf={})).OccurrenceActionPlans="xebGnSSq",Af.OccurrenceGeneral="UFws4AvH",Af.PlansActionPlans="Kux6CcVC",Af.PlansProgramProjects="UWjrp6Dw",Af.PlansIdeas="3g7vNm2w",Af.RisksGeneral="PZ4b6FhP",Af.RisksActionPlans="xZErDg57",Af.RisksAnalysis="UxsioMbH",Af.RisksIncidences="gNt5IJ2F",Af.MetrologyGeneral="4MfEPbRY",Af.MetrologyActivities="hdFM9XQW",Af.MetrologyServiceOrders="cIrVPdMv",Af.DecisionsGeneral="CopsnHDB",Af.DecisionsItems="qLFAayjx",Af.DecisionsActionPlans="RiQFpxdb",Af.FlowGeneral="AFV98JoG",Af.AuditGeneral="gON8LJPi",Af.AuditPlans="SsCNVOvr",Af.AuditPlansItems="OpPkCCFm",Af.AuditActionPlans="P1oGePhh",Af.CommonGeneral="VVfEzgMQ",Af.ActionPlans="C6Z4MgGa",Af.SuppliersEvaluations="fSCeS4mH",Af.SuppliersGeneral="8qPThkrD",Af.SuppliersEvaluationsCriteria="RiSIStdY",Af.SuppliersDocuments="Riua4jMa",Af.SuppliersMaterialsServices="UpEkatXH",Af.DocumentsGeneral="FRhhEX2J",Af.DocumentsPhysicalCopies="PZLtJ23h",Af.DocumentsObsolete="XDjbga14",Af.FmeaGeneral="aPwf4uPr",Af.FmeaActionPlans="vQ8PMrVX",(Df=Ef||(Ef={}))[Df.NotShared=1]="NotShared",Df[Df.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",Df[Df.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(Tf=Pf||(Pf={}))[Tf.All=1]="All",Tf[Tf.OnlyMine=2]="OnlyMine",Tf[Tf.Favorites=3]="Favorites",(Rf=If||(If={}))[Rf.Current=1]="Current",Rf[Rf.Inherent=2]="Inherent",(Lf=Mf||(Mf={}))[Lf.Default=1]="Default",Lf[Lf.Pastel=2]="Pastel",Lf[Lf.Vibrant=3]="Vibrant",Lf[Lf.Earth=4]="Earth",Lf[Lf.Ocean=5]="Ocean",Lf[Lf.Floral=6]="Floral",Lf[Lf.Night=7]="Night",Lf[Lf.Winter=8]="Winter",Lf[Lf.Spring=9]="Spring",Lf[Lf.Summer=10]="Summer",Lf[Lf.Fall=11]="Fall",Lf[Lf.Gray=12]="Gray",Lf[Lf.Brown=13]="Brown",Lf[Lf.Blue=14]="Blue",Lf[Lf.Yellow=15]="Yellow",Lf[Lf.Green=16]="Green",Lf[Lf.Purple=17]="Purple",Lf[Lf.Orange=18]="Orange",Lf[Lf.Pink=19]="Pink",Lf[Lf.Red=20]="Red";const zf={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},Ff={advancedFilter:"analysisDashboardsListFilter"},jf=["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"],Uf=["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 Of(e){return e?.sort((e,a)=>{if(!e?.items?.length||!a?.items?.length)return 0;return Bf(e.items[0]?.keyDate)-Bf(a.items[0]?.keyDate)})}function Bf(e){if(!e)return 0;const[a,t]=e.split("/"),r=zf[a?.toLowerCase()]??0;return 12*(parseInt(t)||0)+r}function $f(e){return null==e?.value||""===e.value.trim()}function qf(e){const a=e.split("/"),t=a[a.length-1];return`${a.slice(0,-1).join("/")}/${encodeURIComponent(t.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function Vf(e){for(const a of Uf)if(e[a])return e[a];return null}function Wf(e){return e?Hf(e).join("&"):null}function Hf(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(...Hf({[t]:e}))}):"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||a.push(`${t}=${r}`))}return a}const Gf=/^-?\d+(,\d{3})*(\.\d+)?$/;function Kf(e){return!!Gf.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))}function Yf(e){const a=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(a)}const Qf=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});function Xf(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 Jf=new Set([af.Text]),Zf=new Set([af.Text,af.Numeric,af.RiskMatrix,af.Burndown,af.PerformanceColumns]),eg=new Set([af.Text,af.RiskMatrix,af.Burndown,af.PerformanceColumns]);function ag({config:e,viewOnly:n=!1,complement:i,complementPosition:d="before-options",queryUrlBuilder:c,onRefresh:u,onExport:m,onToggleOnlyMine:p,className:h}){const{t:f}=nt(),[g,v]=s(e.onlyMine??!1),b=Jf.has(e.typeId),x=!Zf.has(e.typeId),y=!eg.has(e.typeId),N=o(()=>{if(!e.jsonRules||e.typeId===af.PerformanceColumns)return!1;try{const a=JSON.parse(e.jsonRules);return a?.rules?.rules?.length>0}catch{return!1}},[e.jsonRules,e.typeId]),w=o(()=>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:Vi("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(No,{children:[a(wo,{asChild:!0,children:a("span",{className:"block truncate",children:e.title})}),a(_o,{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(no,{children:[a(io,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",className:"h-6 w-6",children:a(Ta,{className:"h-3.5 w-3.5"})})}),t(po,{align:"end",className:"w-48",children:[e.canUpdate&&t(ho,{onClick:()=>e.onEdit?.(e.id),children:[a(H,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!b&&t(ho,{onClick:u,children:[a(Ze,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),x&&t(ho,{disabled:e.noData,onClick:m,children:[a(Ce,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!b&&t(ho,{disabled:!e.openQueryEnabled,onClick:()=>window.open(w,"_blank"),children:[a(ea,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),y&&t(r,{children:[a(bo,{}),t(ho,{onClick:_,children:[g&&a(P,{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(bo,{}),t(ho,{onClick:()=>e.onDuplicate?.(e.id),children:[a(Ne,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),t(ho,{className:"text-destructive",onClick:()=>e.onRemove?.(e.id),children:[a(W,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===d&&i]})]})}function tg({config:e,queryUrl:r,className:n}){return t("div",{className:Vi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[a(Je,{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 rg({panelType:e,className:r}){const n=e===af.Burndown;return t("div",{className:Vi("flex flex-1 flex-col items-center justify-center gap-2 p-4",r),children:[a(ao,{className:"h-10 w-10 text-muted-foreground/40"}),n&&a("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function ng({hasRemovedColumn:r=!1,className:n}){return t("div",{className:Vi("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 ig({onRemove:e,className:r}){return t("div",{className:Vi("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[a(Je,{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 sg={[jh.Count]:e.t("dashboard_distinct_count").replace("distinta","").trim()||"Count",[jh.Sum]:"Sum",[jh.Average]:e.t("dashboard_average"),[jh.DistinctCount]:e.t("dashboard_distinct_count"),[jh.Max]:e.t("dashboard_max_value"),[jh.Min]:e.t("dashboard_min_value")};function og({config:e,state:r,value:n,label:i,viewOnly:s=!1,onClick:o,onRefresh:l,queryUrl:d,queryUrlBuilder:c,className:u}){const{t:m}=nt(),p=i??sg[e.aggregationType??""]??"",h=function(e,a){if(null==e)return"—";const t=jf.includes(a.field),r=a.aggregationType===jh.Count||a.aggregationType===jh.DistinctCount;return t&&!r?Qf.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:Vi("flex h-full flex-col",u),children:[a(ag,{config:e,viewOnly:s,onRefresh:l,queryUrlBuilder:c}),r===yf.Loading&&a(rg,{}),r===yf.Loaded&&t("div",{className:Vi("flex flex-1 flex-col items-center justify-center",o&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:o,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===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),r===yf.Error&&a(tg,{config:e,queryUrl:d}),r===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}function lg({config:e,state:r,htmlContent:n,viewOnly:i=!1,onRefresh:s,queryUrl:o,queryUrlBuilder:l,className:d}){const c=n??e.textTypeString??"";return t("div",{className:Vi("flex h-full flex-col",d),children:[a(ag,{config:e,viewOnly:i,onRefresh:s,queryUrlBuilder:l}),r===yf.Loading&&a(rg,{}),r===yf.Loaded&&a("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:c}}),r===yf.Error&&a(tg,{config:e,queryUrl:o})]})}function dg({config:e,state:r,data:n=[],columns:i=[],viewOnly:s=!1,onRowClick:d,onRefresh:c,onExport:u,queryUrl:m,queryUrlBuilder:p,enableRowLinks:h=!0,className:f}){const g=o(()=>i.filter(e=>!1!==e.visible),[i]),v=l(e=>{if(d)d(e);else if(h){const a=Vf(e);a&&window.open(qf(a),"_blank")}},[d,h]);return t("div",{className:Vi("flex h-full flex-col",f),children:[a(ag,{config:e,viewOnly:s,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===yf.Loading&&a(rg,{}),r===yf.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&&!!Vf(e);return a("tr",{className:Vi("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):cg(e[t.columnName],t)},t.columnName))},t)})})]})}),r===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),r===yf.Error&&a(tg,{config:e,queryUrl:m}),r===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}function cg(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 ug=["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 mg({config:e,variant:r,state:n,data:i=[],series:s,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:ug,x=o(()=>s?.length?s:[{dataKey:"value",name:e.title}],[s,e.title]),y="bar"===r,N="stacked-column"===r,w=o(()=>{if(c)return e=>c.replace("{value}",e.toLocaleString("pt-BR"))},[c]);return t("div",{className:Vi("flex h-full flex-col",v),children:[a(ag,{config:e,viewOnly:u,onRefresh:p,onExport:h,queryUrlBuilder:g}),n===yf.Loading&&a(rg,{}),n===yf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(jt,{width:"100%",height:"100%",children:pg({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===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),n===yf.Error&&a(tg,{config:e,queryUrl:f}),n===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}function pg({variant:e,data:r,series:n,colors:i,categoryKey:s,isHorizontalBar:o,isStacked:l,yAxisTickFormatter:d,tooltipFormatter:c,onPointClick:u}){const m={tick:{fontSize:11},tickLine:!1,axisLine:!1},p=a(Ut,{dataKey:o?void 0:s,type:o?"number":"category",...m,angle:o?0:-45,textAnchor:o?"middle":"end",height:o?void 0:60,tickFormatter:o?d:void 0}),h=a(Ot,{dataKey:o?s:void 0,type:o?"category":"number",...m,width:o?100:60,tickFormatter:o?void 0:d}),f=a(Bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),g=a($t,{formatter:c,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),v=n.length>1?a(qt,{wrapperStyle:{fontSize:"11px"}}):null,b=u?(e,a)=>u(r[a],a):void 0;return"bar"===e||"column"===e||"stacked-column"===e?t(Vt,{data:r,layout:o?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(Wt,{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(Ht,{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(Gt,{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(Kt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(Yt,{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 hg=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function fg({config:e,state:r,data:n=[],colors:i,viewOnly:s=!1,onSliceClick:l,onRefresh:d,onExport:c,queryUrl:u,queryUrlBuilder:m,className:p}){const h=i?.length?i:e.hexColors?.length?e.hexColors:hg,f=o(()=>n.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[n]),g=o(()=>f.reduce((e,a)=>e+(a.value??0),0),[f]);return t("div",{className:Vi("flex h-full flex-col",p),children:[a(ag,{config:e,viewOnly:s,onRefresh:d,onExport:c,queryUrlBuilder:m}),r===yf.Loading&&a(rg,{}),r===yf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(jt,{width:"100%",height:"100%",children:t(Qt,{children:[a(Xt,{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(Jt,{fill:h[t%h.length]},t))}),a($t,{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(qt,{wrapperStyle:{fontSize:"11px"}})]})})}),r===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),r===yf.Error&&a(tg,{config:e,queryUrl:u}),r===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}function gg({config:e,state:r,data:n=[],barColor:i,lineColor:s="#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=o(()=>{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:Vi("flex h-full flex-col",h),children:[a(ag,{config:e,viewOnly:l,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===yf.Loading&&a(rg,{}),r===yf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(jt,{width:"100%",height:"100%",children:t(Zt,{data:v,margin:{top:5,right:30,left:0,bottom:5},children:[a(Bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Ut,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),a(Ot,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),a(Ot,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),a($t,{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(qt,{wrapperStyle:{fontSize:"11px"}}),a(Wt,{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(Yt,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:s,strokeWidth:2,dot:{r:3,fill:s}})]})})}),r===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),r===yf.Error&&a(tg,{config:e,queryUrl:m}),r===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}function vg({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:s,executedColor:o="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:d=!1,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){const{t:h}=nt(),f=i??h("dashboard_work_done"),g=s??h("dashboard_work_planned");return t("div",{className:Vi("flex h-full flex-col",p),children:[a(ag,{config:e,viewOnly:d,onRefresh:c,queryUrlBuilder:m}),r===yf.Loading&&a(rg,{panelType:af.Burndown}),r===yf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(jt,{width:"100%",height:"100%",children:t(Ht,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(Bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Ut,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),a(Ot,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),a($t,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(qt,{wrapperStyle:{fontSize:"11px"}}),a(Gt,{type:"monotone",dataKey:"executedPercentage",name:f,stroke:o,fill:o,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),a(Gt,{type:"monotone",dataKey:"plannedPercentage",name:g,stroke:l,fill:l,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),r===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),r===yf.Error&&a(tg,{config:e,queryUrl:u}),r===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}function bg({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:s,executedColor:o="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}=nt(),g=i??f("dashboard_work_done"),v=s??f("dashboard_work_planned");return t("div",{className:Vi("flex h-full flex-col",h),children:[a(ag,{config:e,viewOnly:d,onRefresh:u,queryUrlBuilder:p}),r===yf.Loading&&a(rg,{}),r===yf.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(jt,{width:"100%",height:"100%",children:t(Vt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(Bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(Ut,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),a(Ot,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),a($t,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(qt,{wrapperStyle:{fontSize:"11px"}}),a(Wt,{dataKey:"executedWork",name:g,fill:o,radius:[2,2,0,0],onClick:c?(e,a)=>c(n[a],a):void 0,cursor:c?"pointer":void 0}),a(Wt,{dataKey:"plannedWork",name:v,fill:l,radius:[2,2,0,0]})]})})}),r===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),r===yf.Error&&a(tg,{config:e,queryUrl:m}),r===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}function xg({config:e,state:r,rule:n,risks:i=[],matrixViewType:s=hf.Quantity,viewOnly:l=!1,onCellClick:d,onRiskClick:c,onRefresh:u,queryUrl:m,queryUrlBuilder:p,className:h}){const f=o(()=>[...n?.parametersY??[]].sort((e,a)=>a.position-e.position),[n?.parametersY]),g=n?.parametersX??[],v=o(()=>{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:Vi("flex h-full flex-col",h),children:[a(ag,{config:e,viewOnly:l,onRefresh:u,queryUrlBuilder:p}),r===yf.Loading&&a(rg,{}),r===yf.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,o)=>{const l=((e,a)=>v[`${a.position}-${e.position}`]??[])(i,e),u=((e,a)=>n?.colorMatrix?.[a]?.[e]??"hsl(var(--muted))")(o,r);return t("div",{className:Vi("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:[s===hf.Quantity&&l.length>0&&t("span",{className:"text-xs font-semibold",children:[l.length," risco",1!==l.length?"s":""]}),s===hf.AllRisksList&&l.map(e=>t(No,{children:[a(wo,{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(_o,{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===yf.NoData&&a(ng,{hasRemovedColumn:e.hasRemovedColumn}),r===yf.Error&&a(tg,{config:e,queryUrl:m}),r===yf.Unavailable&&a(ig,{onRemove:()=>e.onRemove?.(e.id)})]})}const yg=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[yg.Translate.toString(e),yg.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:a,duration:t,easing:r}=e;return a+" "+t+"ms "+r}}});function Ng(e){switch(e){case af.Bar:case af.Column:case af.Pie:case af.List:case af.Line:case af.Area:case af.Text:case af.StackedColumn:return{x:4,y:2};case af.Pareto:case af.RiskMatrix:case af.Burndown:case af.PerformanceColumns:return{x:8,y:2};case af.Numeric:return{x:1,y:1};default:return{x:2,y:2}}}function wg(e){switch(Number(e)){case af.Area:case af.Bar:case af.Column:case af.Line:case af.Numeric:case af.Pie:case af.Text:return{x:1,y:1};default:return{x:2,y:2}}}function _g({panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:s,children:l}){const{attributes:d,listeners:c,setNodeRef:u,transform:m,transition:p,isDragging:h}=fr({id:e.id,disabled:!s}),f=o(()=>({gridColumn:`${e.col+1} / span ${e.sizeX}`,gridRow:`${e.row+1} / span ${e.sizeY}`,minHeight:e.sizeY*n+(e.sizeY-1)*i+"px",transform:yg.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:Vi("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:Vi("dashboard-panel-drag-handle",s&&"cursor-grab active:cursor-grabbing"),...s?c:{}}),a("div",{className:"h-full",children:l})]})}function Cg({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]=s(e);o(()=>{f(e)},[e]);const g=lr(dr(cr,{activationConstraint:{distance:8}})),v=o(()=>0===h.length?1:Math.max(...h.map(e=>e.row+e.sizeY)),[h]),b=o(()=>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],s={...i[r]},o={...i[n]},l=s.col,d=s.row;s.col=o.col,s.row=o.row,o.col=l,o.row=d,i[r]=s,i[n]=o,f(i),m?.(i)},[h,m]),y=o(()=>({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:Vi("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(ur,{sensors:g,collisionDetection:mr,onDragEnd:x,children:a(pr,{items:b,strategy:hr,children:a("div",{style:y,className:Vi("relative w-full",c&&"bg-muted/30",p),children:h.map(e=>a(_g,{panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:d,children:u(e.id)},e.id))})})})}const kg={[af.Bar]:"bar",[af.Column]:"column",[af.StackedColumn]:"stacked-column",[af.Area]:"area",[af.Line]:"line",[af.EvolutionLine]:"evolution-line"};function Sg({config:e,state:r,data:n,numericValue:i,listColumns:s,cartesianData:o,cartesianSeries:l,burndownData:d,performanceData:c,matrixRule:u,matrixRisks:m,onPanelClick:p}){const h=kg[e.typeId];if(h)return a(mg,{config:e,variant:h,state:r,data:o,series:l});switch(e.typeId){case af.Numeric:return a(og,{config:e,state:r,value:i});case af.Text:return a(lg,{config:e,state:r});case af.List:return a(dg,{config:e,state:r,data:n,columns:s??[]});case af.Pie:return a(fg,{config:e,state:r,data:n});case af.Pareto:return a(gg,{config:e,state:r,data:n});case af.Burndown:return a(vg,{config:e,state:r,data:d});case af.PerformanceColumns:return a(bg,{config:e,state:r,data:c});case af.RiskMatrix:return a(xg,{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 Ag({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}=nt(),[A,E]=s(!1),D=e.idViewType===sf.Carousel,P=o(()=>r,[r,D,i]),T=o(()=>P.map(e=>{const a=wg(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]),I=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=I(r),i=m?.(e)??{state:yf.Loaded};return t("div",{className:"flex flex-col h-full",children:[a(ag,{config:n,onRefresh:()=>{}}),a("div",{className:"flex-1 min-h-0 p-2",children:a(Sg,{config:n,...i})})]})},[P,I,m,d,x,y,N]);return t("div",{className:Vi("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:Vi("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:Vi("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:Vi("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:Vi("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(Cg,{panels:T,allowDragging:d,showGridLines:d,renderPanel:M,onLayoutChange:w})})]})}function Eg(e,a=mf.PtBr){const{t:t}=nt();switch(a){case mf.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case mf.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function Dg(e){const{t:a}=nt();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const Pg=[{value:Pf.All,label:"Todos"},{value:Pf.OnlyMine,label:e.t("dashboard_my")},{value:Pf.Favorites,label:"Favoritos"}];function Tg({dashboards:e,limit:n,isLoading:i=!1,language:d=mf.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}=nt(),[S,A]=s(""),[E,D]=s(Pf.All),[P,T]=s(null),I=l(e=>{A(e),N?.(e)},[N]),R=l(e=>{D(e),w?.(e)},[w]),M=o(()=>{let a=e;if(S){const e=S.toLowerCase();a=a.filter(a=>a.code?.toLowerCase().includes(e)||Eg(a,d).toLowerCase().includes(e)||a.responsibleName?.toLowerCase().includes(e))}switch(E){case Pf.OnlyMine:break;case Pf.Favorites:a=a.filter(e=>e.isFavorite)}return a},[e,S,E,d]);return t("div",{className:Vi("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=>I(e.target.value),className:Vi("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:Vi("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:Pg.map(e=>a("button",{onClick:()=>R(e.value),disabled:i,className:Vi("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:Vi("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:Vi("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:Eg(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:Dg(e.lastModified)}),a("td",{className:"px-3 py-2",children:a("span",{className:Vi("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(),T(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:()=>T(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(),T(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(),T(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(),T(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(),T(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(),T(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 Ig=[{value:rf.NotUpdate,label:e.t("dashboard_no_refresh")},{value:rf.FiveMinutes,label:"5 minutos"},{value:rf.TenMinutes,label:"10 minutos"},{value:rf.FifteenMinutes,label:"15 minutos"},{value:rf.ThirtyMinutes,label:"30 minutos"},{value:rf.OneHour,label:"1 hora"}],Rg=[{value:sf.NormalPage,label:e.t("dashboard_normal_page")},{value:sf.Carousel,label:"Carrossel"}],Mg=[{value:Wh.FiveSeconds,label:"5 segundos"},{value:Wh.TenSeconds,label:"10 segundos"},{value:Wh.FifteenSeconds,label:"15 segundos"},{value:Wh.ThirtySeconds,label:"30 segundos"},{value:Wh.OneMinute,label:"1 minuto"},{value:Wh.ThreeMinutes,label:"3 minutos"},{value:Wh.FiveMinutes,label:"5 minutos"},{value:Wh.TenMinutes,label:"10 minutos"}],Lg=[{value:cf.NotShared,label:e.t("dashboard_not_shared"),description:e.t("dashboard_only_responsible")},{value:cf.SharedWithAllCollaborators,label:e.t("dashboard_shared_unit"),description:e.t("dashboard_all_access")},{value:cf.SharedWithUsersGroupsPlacesCollaborators,label:e.t("dashboard_select_groups"),description:e.t("dashboard_select_groups")}],zg=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function Fg({dashboard:e,initialTab:r=lf.General,isSaving:n=!1,isQualitfy:i=!1,users:d=[],groups:c=[],places:u=[],collaborators:m=[],onSave:p,onCancel:h,className:f}){const{t:g}=nt(),v=!!e,[b,x]=s(r),[y,N]=s({"pt-br":!!e?.titlePtBr||!v,en:!!e?.titleEnUs,es:!!e?.titleEsEs}),[w,_]=s(e?.titlePtBr??""),[C,k]=s(e?.titleEnUs??""),[S,A]=s(e?.titleEsEs??""),[E,D]=s(e?.responsibleId??""),[P,T]=s(e?.isActive??!0),[I,R]=s(e?.idUpdateTime??rf.NotUpdate),[M,L]=s(e?.idViewType??sf.NormalPage),[z,F]=s(e?.idPageTime??Wh.FifteenSeconds),[j,U]=s(e?.idShare??cf.NotShared),[O,B]=s(e?.groups??[]),[$,q]=s(e?.places??[]),[V,W]=s(e?.collaborators??[]),H=M===sf.Carousel,G=y["pt-br"]||y.en||y.es,K=o(()=>!!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:I,idViewType:M,idPageTime:H?z:null,idShare:j,groups:j===cf.SharedWithUsersGroupsPlacesCollaborators?O:[],places:j===cf.SharedWithUsersGroupsPlacesCollaborators?$:[],collaborators:j===cf.SharedWithUsersGroupsPlacesCollaborators?V:[]})},[K,n,p,y,w,C,S,E,P,I,M,z,H,j,O,$,V]);return t("div",{className:Vi("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:Vi("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(lf.General),className:Vi("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===lf.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),a("button",{onClick:()=>x(lf.Share),className:Vi("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===lf.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===lf.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:zg.map(e=>a("button",{onClick:()=>Y(e.key),className:Vi("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:Vi("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:Vi("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:Vi("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:Vi("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:I,onChange:e=>R(Number(e.target.value)),disabled:i,className:Vi("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:Ig.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:()=>T(!P),disabled:e?.isGeneralViewUse,className:Vi("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:Vi("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:Vi("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:Rg.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:Vi("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:Mg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]})]})]}),b===lf.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:Lg.map(r=>t("label",{className:Vi("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",j===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:j===r.value,onChange:()=>U(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))}),j===cf.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:Vi("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);q(a)},className:Vi("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 (",V.length,")"]}),a("select",{multiple:!0,value:V,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);W(a)},className:Vi("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 jg({dashboards:e,limit:r,generalView:n,language:i=mf.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:T,onShare:I,onAddPanel:R,onEditPanel:M,onRemovePanel:L,onDuplicatePanel:z,onLayoutChange:F,onSearch:j,onQuickFilterChange:U,onSetGeneralView:O,viewState:B,onViewStateChange:$,listToolbarExtra:q,viewToolbarActions:V,className:W}){const[H,G]=s({mode:"list"}),K=B??H,Y=l(e=>{$?$(e):G(e)},[$]),Q=o(()=>"view"===K.mode||"edit"===K.mode||"share"===K.mode?e.find(e=>e.id===K.dashboardId)??null:null,[e,K]),[X,J]=s(!1),[Z,ee]=s(g[0]?.id);m(()=>{g.length>0&&!Z&&ee(g[0]?.id)},[g,Z]),m(()=>{if("view"!==K.mode||!Q||Q.idViewType!==sf.Carousel||g.length<=1)return;const e=function(e){switch(e){case Wh.FiveSeconds:return 5e3;case Wh.TenSeconds:return 1e4;case Wh.FifteenSeconds:return 15e3;case Wh.ThirtySeconds:return 3e4;case Wh.OneMinute:return 6e4;case Wh.ThreeMinutes:return 18e4;case Wh.FiveMinutes:return 3e5;case Wh.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]),se=l(e=>{"edit"===K.mode||"share"===K.mode?D?.(K.dashboardId,e):E?.(e)},[K,E,D]),oe=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:Vi("flex flex-col h-full",W),children:["list"===K.mode&&a(Tg,{dashboards:e,limit:r,isLoading:d,language:i,canAdd:c,canEdit:u,canRemove:p,onOpen:ae,onEdit:ne,onShare:ie,onDuplicate:T,onRemove:P,onAdd:re,onToggleFavorite:A,onRefresh:S,onSearch:j,onQuickFilterChange:U,toolbarExtra:q,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(Ag,{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:V,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(Fg,{users:b,groups:x,places:y,collaborators:N,isSaving:w,onSave:se,onCancel:oe,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:oe,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(Fg,{dashboard:Q,initialTab:"share"===K.mode?lf.Share:lf.General,users:b,groups:x,places:y,collaborators:N,isSaving:w,isQualitfy:!!Q.isStandard&&!h,onSave:se,onCancel:oe,className:"flex-1"})]})]})}const Ug=({manager:n,columns:i,onEdit:s,onView:o,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:T,gridCardRenderer:I,showViewToggle:R=!1})=>{const{setSearchVisible:M}=Tl(),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)}),j=D||"grid",U="list"===j,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"}[U?1:A],B=L&&z?a(Cd,{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:j,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(Wl,{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:Vi("grid gap-4",O),children:n.entities.map(e=>{const m=(e=>{const{t:a}=nt();return U&&T?T(e):!U&&I?I(e):E?E(e):null})(e);return t(Zl,{children:[a(ed,{asChild:!0,children:m?a("div",{className:"cursor-pointer",onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):s?.(e)},children:m}):a(es,{className:Vi("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",p&&n.selectedIds.includes(e.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):s?.(e)},children:t(ns,{className:Vi("p-4",U&&"flex items-center gap-4 w-full"),children:[p&&a("div",{className:Vi(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:a(kd,{checked:n.selectedIds.includes(e.id),onCheckedChange:()=>n.selectItem(e.id)})}),U?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)))}),(s||o||c)&&a("div",{onClick:e=>e.stopPropagation(),children:c?c(e):a(fd,{onEdit:s?()=>s(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(kd,{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:Vi("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))),(s||o||c)&&a("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(e):a(fd,{onEdit:s?()=>s(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,customActions:u?u(e):[]})})]})]})]})})}),a(od,{className:"w-[160px]",children:a(hd,{onEdit:s?()=>s(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 Og({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:D,onToggleExpand:P,defaultExpandAll:T=!1}){const{t:I}=nt(),R=h||I("no_items_found",I("no_items_found_empty")),[M,L]=s(()=>T?new Set(e.map(e=>e.id)):new Set),z=void 0!==D,j=z?new Set(D):M,U=l(e=>{z&&P?P(e):L(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[z,P]),{columnWidths:O,isDragging:B,activeColumn:$,handleMouseDown:q}=bd({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}),V=Ed({enabled:_&&!!C,onReorder:C??(()=>{})}),W=o(()=>{if(N)return r.map(e=>`${O[String(e.key)]??e.width??e.minWidth??150}px`);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,O]);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(Fo,{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:R})})});const H=(g?1:0)+(S?1:0)+r.length+(m?1:0);return a("div",{className:"flex-1 overflow-auto "+(B?"select-none":""),children:t(zl,{className:f,children:[a(Fl,{className:"sticky top-0 bg-background z-10",children:t(Ol,{children:[S&&a(Bl,{className:"w-[40px]"}),g&&a(Bl,{className:"w-[40px]",children:a(Qs,{checked:y,onCheckedChange:x,"aria-label":I("select_all","Selecionar todos")})}),r.map((e,r)=>{const i=N&&!1!==e.resizable,s=$===String(e.key),o=_&&!!C,l=o?V.getDragProps(r):{},u=V.dragFromIndex===r,m=V.dragOverIndex===r&&V.dragFromIndex!==r;return t(Bl,{className:Vi(e.className,"relative transition-opacity",e.sortable&&"cursor-pointer",o&&V.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:W[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?te:re,{size:14,className:"ml-1"}))]}):a("span",{className:"font-medium",children:e.header}),i&&a(Jl,{direction:"horizontal",onMouseDown:a=>q(String(e.key),a),isDragging:s})]},String(e.key));var p}),m&&a(Bl,{className:"w-[80px] text-right",children:I("actions","Ações")})]})}),a(jl,{children:e.map(e=>{const n=S&&j.has(e.id);return t(i.Fragment,{children:[t(Ol,{onClick:()=>u?.(e),className:(u?"cursor-pointer":"")+" relative",children:[S&&a($l,{className:"w-[40px] px-2",children:a("button",{onClick:a=>{a.stopPropagation(),U(e.id)},className:"p-1 rounded-sm hover:bg-muted transition-colors","aria-label":n?I("collapse_row","Recolher linha"):I("expand_row","Expandir linha"),children:a(n?E:F,{size:16,className:"text-muted-foreground"})})}),g&&a($l,{children:a(Qs,{checked:v.includes(e.id),onCheckedChange:()=>b?.(e.id),onClick:e=>e.stopPropagation(),"aria-label":`${I("select_all","Selecionar todos")} ${e.id}`})}),r.map(t=>a($l,{className:t.className,children:a(Xl,{children:t.render?t.render(e):String(e[t.key]??"-")})},String(t.key))),m&&a($l,{className:"text-right",onClick:e=>e.stopPropagation(),children:m(e)})]}),n&&A&&a(Ol,{className:"bg-muted/30 hover:bg-muted/30",children:a($l,{colSpan:H,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:A(e)})})})]},e.id)})})]})})}function Bg({onEdit:e,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:s=!0,canDelete:l=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=nt(),p=o(()=>{const a=[];return e&&s&&a.push({key:"edit",icon:$,label:m("edit","Editar"),onClick:e,variant:"default"}),n&&a.push({key:"toggle-status",icon:i?q:V,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:W,label:m("remove","Remover"),onClick:r,variant:"destructive"}),a},[e,r,n,i,s,l,d,m]);return 0===p.length?null:"dropdown"===c?a(yo,{delayDuration:200,children:t(no,{children:[a(io,{asChild:!0,children:a(Yi,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:a(S,{size:"compact"===u?14:16})})}),a(po,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(e=>e.disabled?t(Co,{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(ho,{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(Yi,{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 $g({searchValue:e="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:s=!0,layout:o="horizontal"}){const{t:l}=nt(),d=e||n.length>0;return t("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&t("div",{className:"relative flex-1 min-w-[200px]",children:[a(O,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Xi,{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"===o?"w-full":"",children:e},t)),s&&d&&i&&t(Yi,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[a(A,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function qg(e,a){const{t:t}=nt(),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 Vg({children:e,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:s,onDropCell:o,className:l}){return a($l,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},className:l,children:e})}function Wg({item:e,level:n,columns:i,nameKey:s,iconComponent:o,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,D=v===e.id||h?.has(e.id)&&v&&h?.has(v),P=b===e.id&&v!==e.id,T=h?.has(e.id)??!1,I={itemId:e.id,enableDrag:g,onDragStartCell:x,onDragEndCell:y,onDragOverCell:N,onDropCell:w};return t(r,{children:[t(Ol,{className:Vi(c&&"cursor-pointer",A&&"group",D&&"opacity-40",P&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:c?()=>c(e):void 0,children:[a(Vg,{...I,children:t("div",{className:"flex items-center gap-2",style:{paddingLeft:`${S}px`},children:[p&&a(Qs,{checked:T,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?E:F,{className:"h-4 w-4"})}):a("div",{className:"w-6 shrink-0"}),o??a(We,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"truncate",children:String(e[s]??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],s=r.render?r.render(e,n):null!=i?String(i):"—";return a(Vg,{...I,className:Vi("text-center",r.className),children:r.hoverContent?t(Lu,{openDelay:200,children:[a(zu,{asChild:!0,children:a("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:s})}),a(Fu,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:r.hoverContent(e)})]}):s},String(r.key))}),u&&a(Vg,{...I,className:"text-right",children:a("div",{onClick:e=>e.stopPropagation(),className:Vi("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(Wg,{item:e,level:n+1,columns:i,nameKey:s,iconComponent:o,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 Hg({onDrop:r,isDragOver:n,onDragOver:i,onDragLeave:s,label:o}){return t("div",{className:Vi("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:s,onDrop:r,children:[a(Ia,{className:"h-4 w-4"}),o??e.t("leadership_make_root_short")]})}function Gg({data:r,columns:n,nameKey:o,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:T=200}){const[I,R]=s(null),[M,L]=s(null),[z,F]=s(!1),[j,U]=s(1),O=u(null),B=u([]),$=u(null),q=i.useMemo(()=>new Set(w??[]),[w]),V=i.useMemo(()=>{if(!I||!r)return new Set;const e=B.current.length>0?B.current:[I],a=function(e,a){const{t:t}=nt(),r=new Set;for(const n of a)qg(e,n).forEach(e=>r.add(e));return r}(r,e);return e.forEach(e=>a.add(e)),a},[I,r]),W=u(V);W.current=V;const H=l(()=>{O.current=null,B.current=[],$.current=null,R(null),L(null),F(!1),U(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=q.has(e)&&q.size>1?Array.from(q):[e];O.current=e,B.current=t,$.current=null,R(e),U(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[q]),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(We,{className:"h-10 w-10 text-muted-foreground/50"}),a("p",{className:"text-sm text-muted-foreground",children:x})]});const ae=null!==I;return t("div",{className:Vi("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(Hg,{onDrop:X,isDragOver:z,onDragOver:J,onDragLeave:()=>F(!1),label:D}),t(zl,{children:[a(Fl,{children:t(Ol,{children:[a(Bl,{className:"text-left",style:{minWidth:T},children:t("div",{className:"flex items-center gap-2",children:[N&&a(Qs,{checked:k??!1,onCheckedChange:()=>C?.()}),d]})}),n.map(e=>a(Bl,{className:Vi("text-center",e.className),style:e.width?{width:e.width}:void 0,children:e.header},String(e.key))),f&&a(Bl,{className:"text-right",style:{width:P},children:g})]})}),a(jl,{children:r.map(e=>a(Wg,{item:e,level:0,columns:n,nameKey:o,iconComponent:c,expandedIds:m,onToggleExpand:p,onRowClick:h,renderActions:f,rowActionsVariant:v,enableSelection:N,selectedIds:q,onSelectItem:_,enableRowDrag:S,draggedId:I,dragOverId:M,onDragStartCell:K,onDragEndCell:H,onDragOverCell:Y,onDropCell:Q,dragCount:j},e.id))})]})]})}function Kg(e){const a=gt();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 Yg(e,a){const t=Kg({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Qg=[{value:"pt-BR",label:"Português (Brasil)"},{value:"en-US",label:"English (US)"},{value:"es-ES",label:"Español"}],Xg=({open:e,onOpenChange:r,user:n,userPhotoUrl:i,userInitials:o})=>{const{t:l,i18n:d}=nt(),c=u(null),[m,p]=s(null),[h,f]=s(d.language||"pt-BR"),g=m||i,v=e=>{e||(p(null),f(d.language||"pt-BR")),r(e)};return a(bs,{open:e,onOpenChange:v,children:t(Cs,{className:"sm:max-w-md",children:[a(ks,{children:a(Es,{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",children:t(ou,{className:"w-16 h-16",children:[g&&a(lu,{src:g,alt:n.name||""}),a(du,{className:"bg-primary text-primary-foreground font-semibold text-lg",children:o})]})}),t("div",{children:[t(Yi,{variant:"outline",size:"sm",onClick:()=>c.current?.click(),children:[a(Ue,{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(Zi,{children:l("language","Idioma")}),t(Os,{value:h,onValueChange:f,children:[a(qs,{children:a($s,{})}),a(Hs,{children:Qg.map(e=>a(Ks,{value:e.value,children:e.label},e.value))})]})]})]}),t(As,{children:[a(Yi,{variant:"outline",onClick:()=>v(!1),children:l("cancel","Cancelar")}),a(Yi,{onClick:()=>{h!==d.language&&d.changeLanguage(h),r(!1)},children:l("save","Salvar")})]})]})})},Jg="true"===import.meta.env.VITE_SHOW_EDIT_PROFILE,Zg=i.memo(({variant:e="card",className:n="",selectedUnit:l,onUnitChange:d})=>{const{t:c}=nt(),{user:u,companies:m,alias:p,isAuthenticated:h,logout:f,switchUnit:g}=Tl(),{role:v}=Gc(),b=v?.name||null,x=m?.[0]||null,y=p?m?.find(e=>e.alias===p):x,N=m||[],w=l||y||x||x,_=o(()=>{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=o(()=>{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,D]=s(!1);if(!h||!u)return null;return"dropdown"===e?t(r,{children:[t(no,{children:[a(io,{asChild:!0,children:a(Yi,{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(ou,{className:"w-8 h-8 border border-primary-foreground/30",children:[_&&a(lu,{src:_,alt:u.name||c("user_photo")}),a(du,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:C||a(We,{className:"h-4 w-4"})})]}),a(E,{className:"h-4 w-4"})]})})}),t(po,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[t(lo,{children:[t(uo,{children:[a(Ze,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),a(mo,{children:S.map(e=>t(ho,{onClick:()=>k(e),className:e.alias===w?.alias?"bg-muted":"",children:[a(ta,{className:"mr-2 h-4 w-4"}),e.name,e.alias===w?.alias&&a(Zs,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},e.alias))})]}),Jg&&t(r,{children:[a(bo,{}),t(ho,{onClick:()=>D(!0),children:[a(Ra,{className:"mr-2 h-4 w-4"}),c("edit_profile","Editar Perfil")]})]}),a(bo,{}),t(ho,{onClick:f,children:[a(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}),Jg&&a(Xg,{open:A,onOpenChange:D,user:u,userPhotoUrl:_,userInitials:C})]}):t(es,{className:n,children:[a(as,{children:a(ts,{className:"text-lg",children:c("user_info")})}),t(ns,{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(ou,{className:"w-10 h-10",children:[_&&a(lu,{src:_,alt:u.name||c("user_photo")}),a(du,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:C||a(We,{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(ta,{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(Zs,{variant:e.alias===w?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>k(e),children:e.name},e.alias)),S.length>3&&t(Zs,{variant:"outline",className:"text-xs",children:["+",S.length-3]})]})]})]}),{}),a(ss,{}),t(Yi,{variant:"outline",onClick:f,size:"sm",className:"w-full",children:[a(ra,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),ev=d({});function av({children:e,config:t}){const r=o(()=>{const e=_r(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return a(ev.Provider,{value:r,children:e})}function tv(){return c(ev)}function rv(){const e=vt(),{navigation:a}=tv();return nv(a,e.pathname)}function nv(e,a){if(!e)return"Página";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||"Página"}function iv(e,a){const[t,r]=s(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 sv({appName:e}){const[n,i]=s(!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:Fr.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(E,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return t(r,{children:[s," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(E,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(e)})})]}),a(Yc,{open:n,onOpenChange:i})]})}const ov=p(function({actions:r}){const n=vt(),i=gt(),{navigation:o,appName:d}=tv(),c=nv(o,n.pathname),{metadata:u,headerActions:p}=pc(),{setOpenMobile:h}=Bm(),{companies:f,alias:g,isSearchVisible:v,clearSearch:b,refreshData:x,switchUnit:y}=Tl(),N=g?f?.find(e=>e.alias===g)||f?.[0]||null:f?.[0]||null,[w,_]=ht(),C=l(e=>{const{pathname:a,search:t,hash:r}=n;if(g){const n=a.split("/"),s=n.indexOf(g);if(s>=0)return n[s]=e.alias,void i(n.join("/")+t+r)}y(e)},[g,n,i,y]),[k,S]=s(()=>w.get("search")||""),[E,D]=iv(k,Sr.debounceDelay);m(()=>{if(!v)return;const e=new URLSearchParams(w);E?(e.set("search",E),e.set("page","1")):e.delete("search"),_(e)},[E,_,v]);const P=o?.find(e=>e.path===n.pathname)||o?.find(e=>n.pathname.startsWith(e.path+"/")),T=u.title||c,I=u.subtitle||P?.complementaryText||e.t("item_details");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(Yi,{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(Ma,{size:20})}),a("div",{className:"hidden md:flex items-center flex-shrink-0",children:a(sv,{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(F,{className:"h-3 w-3"}),e.href?a(xt,{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:T})}),I&&a("div",{className:"text-sm text-primary-foreground/70 truncate",children:I})]}),v&&t("div",{className:"flex items-center gap-2 flex-1 max-w-2xl",children:[t("div",{className:"relative flex-1",children:[a(O,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(Xi,{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(Yi,{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(A,{size:14})})]}),a(Yi,{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(Ze,{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(Yi,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>$i(import.meta.env.VITE_WIKI_URL,e),title:e.t("open_wiki"),children:"Wiki"}),a(lh,{}),a("div",{className:"text-sm",children:a(Zg,{variant:"dropdown",selectedUnit:N,onUnitChange:C})})]})]})})}),lv=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>ct({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function dv({config:e,isCollapsed:n=!1,isDisabled:i=!1,className:s}){const{t:o}=nt(),{actions:l,triggerLabel:d="Criar",triggerIcon:c=Y,variant:u="button"}=e;if(!l||0===l.length)return null;if("split-button"===u){const e=l[0],r=e.icon||c,o=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(Yi,{onClick:e.onClick,disabled:i||e.disabled,className:Vi("justify-center px-2 w-full",s),variant:"outline",size:"default",children:a(r,{className:"h-4 w-4 shrink-0"})});return t(No,{children:[a(wo,{asChild:!0,children:n}),a(_o,{side:"right",children:a("p",{children:e.label})})]})}return a(Yp,{label:e.label,onClick:e.onClick,icon:r,actions:o,variant:"outline",disabled:i||e.disabled,className:Vi("w-full",s),menuAlign:"start"})}const m=(e,i,s=!1)=>t(r,{children:[e,!n&&i&&a("span",{className:"truncate",children:i}),!n&&s&&a(E,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(l.length>1)){const e=l[0],r=e.icon||c,o=i||e.disabled,d=a(Yi,{onClick:e.onClick,disabled:o,className:Vi("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:m(a(r,{className:"h-4 w-4 shrink-0"}),e.label)});return n?t(No,{children:[a(wo,{asChild:!0,children:d}),a(_o,{side:"right",children:a("p",{children:e.label})})]}):d}const p=a(Yi,{disabled:i,className:Vi("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:m(a(c,{className:"h-4 w-4 shrink-0"}),d,!0)});return t(no,{children:[a(io,{asChild:!0,children:n?t(No,{children:[a(wo,{asChild:!0,children:p}),a(_o,{side:"right",children:a("p",{children:d})})]}):p}),a(po,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:l.map(e=>{const r=e.icon;return t(ho,{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 cv="forlogic-sidebar-pinned",uv=()=>{try{const e=localStorage.getItem(cv);return!!e&&JSON.parse(e)}catch{return!1}};function mv({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[d,c]=s(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[p,h]=s(!1),f=u(null);m(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${d}px`):e.style.setProperty("--sidebar-width","290px"))},[d,o]);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)},s=()=>{h(!1),c(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",s),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",s)}},[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 pv=d(void 0);function hv({children:e}){const[t,r]=s(new Set),[n,i]=s(!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=o(()=>t.size>0||n,[t,n]),p=o(()=>({openModals:t,hasOpenModal:m,registerModal:d,unregisterModal:c,setHasOpenModal:u}),[t,m,d,c,u]);return a(pv.Provider,{value:p,children:e})}function fv(){const e=c(pv);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function gv(){const{hasOpenModal:e}=fv();return e}function vv({config:e,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{t:d}=nt(),{open:c,setOpen:u,setOpenMobile:p}=Bm(),h=vt(),{alias:f,user:g}=Tl(),{appName:v}=tv(),{hasOpenModal:b}=fv(),[x,y]=s(uv),N=Ll(),w=!!N||c,_=l(()=>{N&&p(!1)},[N,p]),C=n?mv({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:c}):null;m(()=>{u(!!x)},[x,u]);const k=e=>h.pathname===e||h.pathname.startsWith(e+"/");return t(qm,{collapsible:"icon",className:Vi("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(yo,{children:a(dv,{config:e.moduleActions,isCollapsed:!w,isDisabled:b})})}),a(Xm,{className:Vi(e?.moduleActions&&e.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||a(Jm,{className:"p-0",children:a(ap,{children:a(tp,{className:"gap-1",children:a(yo,{children:e?.navigation?.map((e,r)=>{if("separator"===e.type)return a(Qm,{className:"my-2"},`sep-${r}`);const n=({item:e,index:r})=>{const i=`${e.path}-${r}-${f??"noalias"}-${g?.id??"nouser"}`,{data:s=!0,isLoading:o}=lv({key:i,enabled:Boolean(e.permissionCheck&&f&&g?.id),checkFn:e.permissionCheck||(()=>Promise.resolve(!0))}),l=e.permissionCheck&&!s,c=o?T:l?fe:e.icon;l?d("restricted_access"):e.complementaryText;return e.children&&e.children.length>0?w?a(Dc,{defaultOpen:!0,className:"group/collapsible",children:t(rp,{children:[a(Pc,{asChild:!0,children:a(ip,{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(F,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),a(Tc,{children:a(dp,{children:e.children.map((e,t)=>a(n,{item:e,index:t},e.path))})})]})},e.path):a(rp,{children:t(No,{children:[a(wo,{asChild:!0,children:a("div",{className:Vi("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(_o,{side:"right",children:a("p",{children:e.label})})]})},e.path):a(rp,{children:l||o?t(No,{children:[a(wo,{asChild:!0,children:w?a(ip,{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 "+(o?"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 "+(o?"animate-spin":"")})})}),a(_o,{side:"right",children:a("p",{children:o?"Verificando acesso...":d("restricted_access")})})]}):w?a(ip,{asChild:!0,isActive:k(e.path),size:"default",children:t(xt,{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(No,{children:[a(wo,{asChild:!0,children:a(xt,{to:e.path,onClick:_,className:Vi("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(_o,{side:"right",children:a("p",{children:e.label})})]})},e.path)};return a(n,{item:e,index:r},e.path)})})})})})}),!N&&a("div",{className:Vi("mt-auto pb-4 pt-2 flex",c?"justify-end":"justify-center"),children:t(No,{children:[a(wo,{asChild:!0,children:a("button",{onClick:()=>{const e=!x;y(e),(e=>{try{localStorage.setItem(cv,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?Te:F,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),a(_o,{side:"right",children:a("p",{children:c?"Recolher":"Expandir"})})]})}),n&&C&&w&&a("div",{ref:C.dragRef,onMouseDown:C.handleMouseDown,className:Vi("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 bv=p(function({children:e,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const s=o(()=>r||a(vv,{config:n}),[r,n]),d=o(()=>({"--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(av,{config:n,children:a(mc,{children:a($m,{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(ov,{})}),t("div",{className:"sidebar-container flex flex-1 overflow-hidden",children:[s,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 xv({open:e,appName:n}){const[i,o]=s(!1);return t(r,{children:[a(Km,{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:()=>o(!0),children:a("img",{src:Fr.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:()=>o(!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(E,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return t(r,{children:[s," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(E,{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:()=>o(!0),children:a("img",{src:Fr.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),a(Yc,{open:i,onOpenChange:o})]})}function yv({title:e,subtitle:r,children:n,className:i,hasHeader:s=!0}){const o=e||r;return t("div",{className:Vi("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",i),children:[s&&o&&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:Vi("p-6",!s&&o&&"pt-4"),children:n})]})}function Nv({breadcrumbs:e,children:r,className:i}){return t("div",{className:Vi("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[e&&e.length>0&&a(cu,{className:"mb-4",children:a(uu,{children:e.map((r,i)=>{const s=i===e.length-1;return t(n.Fragment,{children:[i>0&&a(fu,{}),a(mu,{children:s||!r.href?a(hu,{children:r.label}):r.asChild&&r.children?a(pu,{asChild:!0,children:r.children}):a(pu,{asChild:!0,children:a(xt,{to:r.href||"/",children:r.label})})})]},`${r.label}-${i}`)})})}),a("div",{className:"space-y-6",children:r})]})}const wv=(e={})=>{const{enabled:a=!0}=e,{alias:t}=Tl();return ct({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=dl(),{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(!ml.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function _v({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:o=!0}){const[d,c]=s(()=>{if(!o||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[p,h]=s(!1),[f,g]=s(null),v=u(0),b=u(0),x=l(e=>d[e]??a,[d,a]),y=l((e,t)=>{o&&(t.preventDefault(),t.stopPropagation(),h(!0),g(e),v.current=t.clientY,b.current=d[e]??a)},[o,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 Cv(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:i}=e,[d,c]=s(t),[u,m]=s(r),[p,h]=s(!1),[f,g]=s(!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]),_=o(()=>w(),[w,u]),C=o(()=>!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]),T=l(e=>{e<0||e>=v||p||(e<=d||e===d+1)&&c(e)},[d,v,p]),I=l(e=>{h(e)},[]);return{currentStep:d,currentStepConfig:y,data:u,isFirstStep:b,isLastStep:x,isLoading:p,isCompleting:f,next:D,back:P,goTo:T,canProceed:_,canGoBack:C,setData:k,updateField:S,reset:A,complete:E,setLoading:I,progress:N,stepIndex:d,totalSteps:v}}function kv(...e){return Object.assign({},...e)}const Sv=()=>{const{locale:e,timezone:a}=kc(),t=Si;return{formatDatetime:r=>Ui(r,t,a,e),formatDate:t=>Oi(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class Av{static async sendEmail(e){const a=dl(),{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 Ev=Av;function Dv({open:e,onOpenChange:r,placeId:n,placeName:i,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const{t:m}=nt(),[p,h]=s([]),[f,g]=s(!1),[v,b]=s(""),{data:x=[],isLoading:y}=jd({enabled:e}),N=o(()=>{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(bs,{open:e,onOpenChange:r,children:t(Cs,{className:"max-w-2xl",variant:"form",children:[a(ks,{showSeparator:!0,children:t(Es,{className:"flex items-center gap-2",children:[a(Aa,{className:"h-5 w-5"}),"Gerenciar Acessos - ",i]})}),t(Ss,{children:[t("div",{className:"relative mb-4",children:[a(O,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Xi,{placeholder:"Pesquisar...",value:v,onChange:e=>b(e.target.value),className:"pl-9"})]}),a(Bo,{className:"h-[400px] pr-4",children:y?a("div",{className:"space-y-2",children:[...Array(5)].map((e,t)=>a(Fo,{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(Aa,{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:Vi("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(Qs,{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(La,{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(As,{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(Yi,{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(La,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&t(Yi,{onClick:async()=>{if(d&&0!==p.length){g(!0);try{await d(p,n),h([])}finally{g(!1)}}},disabled:f,children:[a(za,{className:"h-4 w-4 mr-2"}),"Tornar ",p.length>1?"Membros":"Membro"]})]})]})})}function Pv({place:e,level:r=0,manageAccessConfig:n}){const{t:i}=nt(),[o,l]=s(!1),[d,c]=s(!1),u=e.subPlaces&&e.subPlaces.length>0,m=e.isActive??!0,p=e.usersCount??0;return t("div",{children:[t(Dc,{open:o,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(Pc,{className:"flex items-center gap-2 flex-1",children:[a(F,{className:Vi("h-4 w-4 transition-transform shrink-0",o&&"rotate-90")}),a(ta,{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(ta,{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(Aa,{className:"h-3.5 w-3.5 text-muted-foreground"}),a("span",{className:"text-sm text-muted-foreground",children:p})]}),a(Zs,{variant:m?"default":"secondary",className:"text-xs",children:m?"Ativo":"Inativo"}),n&&a(Bg,{customActions:[{label:i("manage_access"),icon:Ve,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),u&&a(Tc,{children:e.subPlaces.map(e=>a(Pv,{place:e,level:r+1,manageAccessConfig:n},e.id))})]}),0===r&&a(ss,{}),n&&a(Dv,{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 Tv({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(Pv,{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(ta,{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 Iv=new class{get baseUrl(){return Pr()}async makeApiCall(e,a,t){const r=pl.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=nl.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status}`);throw e.status=s.status,e}return s.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 pl.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 il.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return il.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function Rv(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 Mv(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 Lv(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function zv(){const{alias:a,isAuthenticated:t}=Tl(),r=nl.getAccessToken(),{data:n=[]}=jd({enabled:!0});return ct({queryKey:["leadership",a],queryFn:async()=>{if(!r||!a)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=dl(),{data:i,error:s}=await t.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",a);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!i||0===i.length)return[];const o={};n.forEach(e=>{o[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:o[a.id_user]?.name||e.t("inactive_user"),email:o[a.id_user]?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[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=o[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=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),Mv(l)},enabled:!!r&&!!a&&t&&n.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const Fv="common";function jv(){const{alias:e}=Tl(),a=dt(),t=dl(),{t:r}=nt();return ut({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 qv(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(Fv).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 Uv(){const{alias:e}=Tl(),a=dt(),t=dl(),{t:r}=nt();return ut({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(Fv).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 qv(t,e,d.id_user,a.id_leader)}const s=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await t.schema(Fv).from("leaders").insert(s).select();if(l)throw l;return o},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 Ov(){const{alias:e}=Tl(),a=dt(),t=dl(),{t:r}=nt();return ut({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(Fv).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 qv(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:s}=await t.schema(Fv).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(s)throw s;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 Bv(){const{alias:e}=Tl(),a=dt(),t=dl(),{t:r}=nt();return ut({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(Fv).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 $v(){const{alias:e}=Tl(),a=dt(),t=dl(),{t:r}=nt();return ut({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),s=await Promise.all([t.schema(Fv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(Fv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=s;if(l)throw l;if(c)throw c;const u=o||[],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 qv(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 qv(t,e,y.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(t.schema(Fv).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(Fv).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(Fv).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 qv(a,t,r,n,i){const{data:s,error:o}=await a.schema(Fv).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(o)throw o;const l=i?s.filter(e=>e.id!==i):s,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 Vv=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,s=r.path.join(".");if(!t[s])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[s]={message:o.message,type:o.code}}else t[s]={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[s].types,d=l&&l[r.code];t[s]=Xa(s,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},Wv=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,s){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&vr({},i),{errors:{},values:t.raw?r:e}})}catch(l){return s(l)}return o&&o.then?o.then(void 0,s):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:br(Vv(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(s){return Promise.reject(s)}}};const Hv=gr.object({id_leader:gr.string().nullable(),id_users:gr.array(gr.string()).min(1,e.t("leadership_select_subordinates"))}),Gv=gr.object({id_leader:gr.string().nullable(),id_users:gr.array(gr.string())});function Kv({value:r,onChange:n,excludeUserIds:i=[],error:o}){const{data:l=[],isLoading:d}=jd(),[c,p]=s(""),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||"",s=a.userName||a.userEmail||"";return i.localeCompare(s)});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(Xi,{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(Qs,{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(Zi,{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)"]}),o&&a("p",{className:"text-sm text-destructive",children:o})]})}function Yv({leader:n,prefilledLeaderId:i,onSuccess:o}){const{t:l}=nt(),{alias:d}=Tl(),c=!!n,u=n?.id.startsWith("virtual-"),p=Uv(),h=jv(),f=Ov(),g=$v(),v=Bv(),{data:b=[]}=zv(),{data:x=[]}=jd(),[y,N]=s(""),w=Lv(b).map(e=>e.id_user),_=c?Lv(b).filter(e=>e.id_leader===n.id_user).map(e=>e.id_user):[],C=Ja({resolver:Wv(c?Gv:Hv),defaultValues:{id_leader:i||(c?n?.id_leader:null)||null,id_users:c?_:[]}});m(()=>{if(n){const e=Lv(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})}o?.()}catch(a){}}),className:"space-y-4",children:[c&&t("div",{children:[a(Zi,{children:e.t("leader")}),a(Xi,{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(Zi,{children:l("leadership_immediate_superior")}),t(Os,{value:S||"none",onValueChange:e=>C.setValue("id_leader","none"===e?null:e),children:[a(qs,{children:a($s,{placeholder:"Selecione..."})}),t(Hs,{children:[a("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:a(Xi,{placeholder:"Buscar superior...",value:y,onChange:e=>N(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),t(Bo,{className:"h-[200px]",children:[a(Ks,{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(Ks,{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(Zi,{children:"Subordinados *"}),a(Kv,{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(Yi,{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(os,{children:[a(ls,{asChild:!0,children:a(Yi,{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(W,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),t(us,{children:[t(ms,{children:[a(hs,{children:l("confirm_removal")}),a(fs,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),t(ps,{children:[a(vs,{children:l("cancel")}),a(gs,{onClick:async()=>{if(n)try{await v.mutateAsync(n.id),o?.()}catch(e){}},children:l("remove")})]})]})]})]})]})}function Qv({open:e,onOpenChange:r,leader:n,prefilledLeaderId:i,title:s}){return a(bs,{open:e,onOpenChange:r,children:t(Cs,{variant:"form",className:"sm:max-w-[500px]",children:[a(ks,{showSeparator:!0,children:a(Es,{children:s})}),a(Ss,{children:a(Yv,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const Xv="leadership-expanded-nodes",Jv=(e,a)=>{const{t:t}=nt();try{localStorage.setItem(`${Xv}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Zv({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}=Tl(),{data:g,isLoading:v,error:b,refetch:x}=zv(),y=Ov(),N=jv(),[w,_]=s(()=>f?(e=>{try{const a=localStorage.getItem(`${Xv}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(f):new Set),[C,k]=s([]),[S,A]=s(new Set),[D,P]=s(!0),[T,I]=s(!1),[R,M]=s(),[L,z]=s(null),j=o(()=>g?Lv(g):[],[g]),U=o(()=>j.map(e=>e.id),[j]),O=U.length>0&&C.length===U.length,B=j.filter(e=>e.children.length>0).every(e=>w.has(e.id));m(()=>{if(g&&g.length>0&&f){if(!localStorage.getItem(`${Xv}-${f}`)){const e=g.map(e=>e.id),a=new Set(e);_(a),Jv(f,a)}}},[g,f]);const $=l(e=>{_(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),f&&Jv(f,t),t})},[f]),q=l(()=>{if(B){const e=new Set;_(e),f&&Jv(f,e)}else{const e=new Set(j.filter(e=>e.children.length>0).map(e=>e.id));_(e),f&&Jv(f,e)}},[B,j,f]),V=l(e=>{k(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),W=l(()=>{k(O?[]:U)},[O,U]),G=l(e=>{A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),K=l(e=>j.find(a=>a.id===e),[j]),Q=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 s=a?K(a):null;y.mutate({id:r.id,id_leader:s?.id_user||null})},[d,n,i,K,y,N]),X=l((e,a)=>{c?c(e,a):(e.forEach(e=>Q(e,a)),k([]))},[c,Q]),J=l(e=>{M(e),z(null),I(!0)},[]),Z=l(()=>{M(void 0),z(null),I(!0)},[]),ee=l(()=>{I(!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=o(()=>[{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(We,{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(qe,{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(Yi,{onClick:()=>x(),children:e.t("try_again")})]})});const ne=j.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(Yi,{size:"sm",onClick:Z,children:[a(Y,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(Yi,{size:"sm",variant:"outline",onClick:q,children:t(r,B?{children:[a(E,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[a(F,{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(Aa,{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(Gg,{data:g||[],columns:re,nameKey:"name",nameHeader:p,expandedIds:w,onToggleExpand:$,iconComponent:a(Aa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:V,onSelectAll:W,isAllSelected:O,onMoveNode:Q,onMoveNodes:X,rootDropLabel:h,emptyMessage:e.t("leadership_no_hierarchy"),renderActions:e=>a(Yi,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>J(e),children:a(H,{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(D?E:F,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a(za,{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"})]}),D&&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:Vi("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(Qs,{checked:S.has(e.id),onCheckedChange:()=>G(e.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),a("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),a(We,{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(Qv,{open:T,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 eb(e){const[a,t]=s(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:i,onSuccess:o,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"}),o?.(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 ab(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 tb(e,a){const t=ab(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function rb(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function nb(e,a){const t=rb(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function ib(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function sb(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function ob(e,a,t){switch(a||sb(e)){case"youtube":return tb(e,t);case"vimeo":return nb(e,t);default:return e}}function lb({value:n,onChange:i,onSubmit:l,onCancel:d,uploadFunction:c,deleteFunction:m,uploadOptions:p}){const{t:h}=nt(),[f,g]=s(n||{inputType:"url",controls:!0}),v=u(null),b=u(null),{upload:x,uploading:y}=eb({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["video/*"],maxSize:104857600}}),{upload:N,uploading:w}=eb({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["image/*"],maxSize:5242880}}),_=o(()=>sb(f.videoUrl||ib(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(Zi,{children:h("input_type")}),t(Os,{value:f.inputType||"url",onValueChange:e=>k("inputType",e),children:[a(qs,{children:a($s,{})}),t(Hs,{children:[a(Ks,{value:"url",children:"URL"}),a(Ks,{value:"upload",children:h("file_upload")}),a(Ks,{value:"embed",children:h("embed_code")})]})]})]}),"upload"===f.inputType&&c&&t("div",{className:"space-y-2",children:[a(Zi,{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(Yi,{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(_e,{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(Zi,{children:h("embed_code")}),a(Xs,{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(Zi,{children:"Thumbnail"}),t("div",{className:"flex gap-2",children:[a(Xi,{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(Yi,{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(_e,{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(Zi,{htmlFor:"title",children:"Título"}),a(Xi,{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(Qs,{id:"autoplay",checked:f.autoplay||!1,onCheckedChange:e=>k("autoplay",!0===e)}),a(Zi,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),t("div",{className:"flex items-center gap-2",children:[a(Qs,{id:"controls",checked:!1!==f.controls,onCheckedChange:e=>k("controls",!0===e)}),a(Zi,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:"Preview"}),a("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const r=f.videoUrl||ib(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"===_?tb(r,f.autoplay):nb(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(Yi,{variant:"outline",onClick:d,children:"Cancelar"}),a(Yi,{onClick:()=>{f.videoUrl||f.embedCode?l(f):C.error("Erro",{description:h("no_video_selected")})},disabled:!(f.videoUrl||f.embedCode),children:"Salvar"})]})]})}function db({content:r,className:n="",style:i}){const s=r.videoUrl||ib(r.embedCode)||"";if(!s)return null;const o=sb(s);return a(es,{className:`overflow-hidden my-4 ${n}`,style:i,children:t(ns,{className:"p-0",children:["file"===o?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:s}),"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"===o?tb(s,r.autoplay):nb(s,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 cb({value:e,onChange:n,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const{t:m}=nt(),[p,h]=s(e||{alignment:"center",allowDownload:!1}),f=u(null),{upload:g,uploading:v}=eb({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(Zi,{children:"URL"}),t("div",{className:"flex gap-2",children:[a(Xi,{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(Yi,{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(_e,{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(Zi,{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(Zi,{htmlFor:"caption",children:"Legenda"}),a(Xs,{id:"caption",placeholder:"Legenda",value:p.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),t("div",{className:"space-y-2",children:[a(Zi,{htmlFor:"alt",children:m("alt_text")}),a(Xi,{id:"alt",placeholder:m("alt_text"),value:p.alt||"",onChange:e=>b("alt",e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:"Alinhamento"}),t(Os,{value:p.alignment||"center",onValueChange:e=>b("alignment",e),children:[a(qs,{children:a($s,{})}),t(Hs,{children:[a(Ks,{value:"left",children:"Esquerda"}),a(Ks,{value:"center",children:"Centro"}),a(Ks,{value:"right",children:"Direita"})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Zi,{htmlFor:"width",children:"Largura"}),a(Xi,{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(Zi,{htmlFor:"height",children:"Altura"}),a(Xi,{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(Qs,{id:"allowDownload",checked:p.allowDownload||!1,onCheckedChange:e=>b("allowDownload",!0===e)}),a(Zi,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[a(Yi,{variant:"outline",onClick:o,children:"Cancelar"}),a(Yi,{onClick:()=>{p.imageUrl?i(p):C.error("Erro",{description:m("no_image_selected")})},disabled:!p.imageUrl,children:"Salvar"})]})]})}function ub({content:e,className:r="",style:n}){const{t:i}=nt();if(!e.imageUrl)return null;const s={left:"justify-start",center:"justify-center",right:"justify-end"}[e.alignment||"center"];return a("div",{className:`flex ${s} 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(Ce,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function mb(e,a){return e/a}function pb(e,a,t,r){const n=mb(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 hb(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 fb(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 gb(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function vb(){const{alias:e}=Tl(),[a,t]=s(null),[r,n]=s(!0);m(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=dl(),{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=dl(),{data:i,error:s}=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(s)throw s;return t(i),i},[e])}}const bb=import.meta.env.VITE_SUPABASE_URL,xb=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function yb(e,a,t){const r=nl.getSupabaseToken(),n={"Content-Type":"application/json",apikey:xb};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${bb}/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 Nb={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await yb(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 yb(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let wb=null;function _b(){return window.Clicksign?Promise.resolve():wb||(wb=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)}),wb)}const Cb="clicksign-container";function kb({signerId:e,environment:r="sandbox",onSign:n,onError:i,onClose:o}){const{t:l}=nt(),d=u(null),[c,p]=s(!0),[h,f]=s(null);return m(()=>{let a=!1;return d.current&&(d.current.unmount(),d.current=null),f(null),p(!0),_b().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(Cb),t.on("loaded",function(){p(!1)}),t.on("signed",function(){n?.()}),t.on("resized",function(e){const a=e,t=document.getElementById(Cb);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(){o?.()}),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:Cb,style:{height:"600px"}})]})}function Sb({documentKey:r,signerEmail:n,signerName:i,keySigner:o,environment:d,onSign:c,onError:p}){const h=u(null),[f,g]=s("loading"),[v,b]=s(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 o&&e.set("key_signer",o),`${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(sc,{variant:"danger",className:"my-4",children:[a(oc,{children:e.t("sign_doc_load_error")}),a(lc,{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 Ab({file:r,onDocumentSigned:n,onError:i,showEventLog:o=!1}){const{user:d,alias:c}=Tl(),{config:p,isLoading:h}=vb(),{t:f}=nt(),[g,v]=s(null),[b,x]=s(!1),[y,N]=s(null),[w,_]=s("sandbox"),[k,S]=s("clicksign"),[A,E]=s(null),[D,P]=s(null),[I,R]=s(!1),[M,L]=s(0),[z,F]=s(!1),[j,U]=s([]),O=u(null),B=u(null),$=l(e=>{o&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[o]),q=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 s=await Nb.createEnvelopeWithSigner({alias:c,contentBase64:n,filename:a.name,signerEmail:d.email||"",signerName:d.name||"",provider:t});$(`Envelope criado: ${s.envelope_id}`),E({envelope_id:s.envelope_id,document_id:s.document_id,signer_email:s.signer_email,key_signer:s.signer_id}),_(s.environment),S(s.provider||t),"d4sign"===t?($("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),N(s.document_id),C.success(f("sign_doc_sent","Documento enviado! Assine abaixo."))):s.signer_id?($(`Signer ID obtido: ${s.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),N(s.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,q(r))},[r,c,d,h,q]);const V=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 Nb.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 V())},[$,n,A,y,c,w,k,V]);if(!c)return a(es,{className:"border-amber-200 bg-amber-50",children:a(ns,{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=()=>o&&j.length>0?a("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:j.map((e,t)=>a("div",{children:e},t))}):null;return A&&!y&&(D||I||z)?t("div",{className:"space-y-4",children:[a(es,{className:"border-green-200 bg-green-50",children:t(ns,{className:"flex flex-col items-center gap-4 py-8",children:[a(Da,{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(Yi,{asChild:!0,variant:"default",className:"gap-2",children:t("a",{href:D,target:"_blank",rel:"noopener noreferrer",children:[a(Ce,{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(Yi,{variant:"secondary",className:"gap-2",onClick:V,children:[a(Ze,{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(Sb,{documentKey:y,signerEmail:A?.signer_email||d?.email||"",signerName:d?.name,keySigner:A?.key_signer,environment:w,onSign:W,onError:i}):a(kb,{signerId:y,environment:w,onSign:W,onError:i}),a(G,{})]}):r&&(b||h)?a(es,{children:t(ns,{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?q(a):C.error(f("sign_select_pdf","Selecione um arquivo PDF"))}}),a(es,b?{children:t(ns,{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(ns,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[a(_e,{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 Eb({onSaved:e}){const{config:r,isLoading:n,saveConfig:i}=vb(),{t:o}=nt(),[l,d]=s(""),[c,u]=s("sandbox"),[p,h]=s(!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(Xe,{className:"h-4 w-4"}),a("span",{children:o("sign_configured",o("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[a(U,{className:"h-4 w-4"}),a("span",{children:o("sign_not_configured",o("sign_not_configured_unit"))})]}),t(es,{children:[a(as,{children:a(ts,{className:"text-base",children:o("sign_digital_config")})}),a(ns,{children:t("form",{onSubmit:async a=>{if(a.preventDefault(),l.trim()){h(!0);try{await i(l.trim(),c),C.success(o("sign_config_saved",o("sign_config_saved_success"))),e?.()}catch(t){C.error(o("sign_config_save_error",o("sign_config_save_err")))}finally{h(!1)}}else C.error(o("sign_api_key_required",o("sign_api_key_info")))},className:"space-y-4",children:[t("div",{className:"space-y-2",children:[a(Zi,{htmlFor:"sign-api-key",children:"API Key"}),a(Xi,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder",o("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:o("sign_environment","Ambiente")}),t(Os,{value:c,onValueChange:e=>u(e),children:[a(qs,{children:a($s,{})}),t(Hs,{children:[a(Ks,{value:"sandbox",children:"Sandbox (Testes)"}),a(Ks,{value:"production",children:"Produção"})]})]})]}),t(Yi,{type:"submit",disabled:p,children:[p&&a(T,{className:"mr-2 h-4 w-4 animate-spin"}),r?o("sign_update_config",o("sign_update_config_btn")):o("sign_save_config",o("sign_save_config_btn"))]})]})})]})]})}var Db,Pb,Tb,Ib,Rb,Mb,Lb,zb,Fb,jb;(Pb=Db||(Db={}))[Pb.waitingStart=1]="waitingStart",Pb[Pb.running=2]="running",Pb[Pb.effectivenessCheck=3]="effectivenessCheck",Pb[Pb.done=4]="done",Pb[Pb.suspended=5]="suspended",Pb[Pb.canceled=6]="canceled",(Ib=Tb||(Tb={}))[Ib.low=0]="low",Ib[Ib.medium=1]="medium",Ib[Ib.high=2]="high",(Mb=Rb||(Rb={}))[Mb.plan=2]="plan",Mb[Mb.occurrence=3]="occurrence",Mb[Mb.risk=4]="risk",Mb[Mb.decisions=5]="decisions",Mb[Mb.audit=6]="audit",Mb[Mb.strategyExtension=7]="strategyExtension",Mb[Mb.standardization=8]="standardization",Mb[Mb.supplier=9]="supplier",Mb[Mb.auditItems=10]="auditItems",(zb=Lb||(Lb={}))[zb.currentProgress=1]="currentProgress",zb[zb.cumulativeProgress=2]="cumulativeProgress",(jb=Fb||(Fb={})).uploading="uploading",jb.waiting="waiting",jb.done="done",jb.error="error",jb.canceled="canceled",jb.duplicateItem="duplicateItem";const Ub={[Db.waitingStart]:"#D6D6D6",[Db.running]:"#DAE9F4",[Db.effectivenessCheck]:"#1B75BB29",[Db.done]:"#DDEECA",[Db.suspended]:"#FFF2D6",[Db.canceled]:"#F4433629"},Ob={[Db.waitingStart]:"#666666",[Db.running]:"#1B75BB",[Db.effectivenessCheck]:"#1B75BB",[Db.done]:"#4CAF50",[Db.suspended]:"#FF9800",[Db.canceled]:"#F44336"},Bb={[Db.waitingStart]:"waiting-start",[Db.running]:"running",[Db.effectivenessCheck]:"effectiveness-check",[Db.done]:"done",[Db.suspended]:"suspended",[Db.canceled]:"canceled"};function $b(){return{[Db.waitingStart]:e.t("ap_status_waiting_start"),[Db.running]:e.t("ap_status_running"),[Db.effectivenessCheck]:e.t("ap_status_effectiveness_check"),[Db.done]:e.t("ap_status_done"),[Db.suspended]:e.t("ap_status_suspended"),[Db.canceled]:e.t("ap_status_canceled")}}const qb=new Proxy({},{get:(e,a)=>{if("symbol"==typeof a)return;return $b()[a]}});function Vb(){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 Wb=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}];function Hb(){return[{id:Tb.low,label:e.t("ap_priority_low"),color:"#4CAF50"},{id:Tb.medium,label:e.t("ap_priority_medium"),color:"#FF9800"},{id:Tb.high,label:e.t("ap_priority_high"),color:"#F44336"}]}const Gb=[{id:Tb.low,label:"Baixa",color:"#4CAF50"},{id:Tb.medium,label:"Média",color:"#FF9800"},{id:Tb.high,label:"Alta",color:"#F44336"}],Kb=[Db.done,Db.canceled],Yb=[Db.waitingStart,Db.running,Db.effectivenessCheck,Db.suspended];function Qb(e){const{actionPlan:a,isNew:t=!1,config:r,onSave:n,onCancel:i,onDelete:o,onChangeStatus:d}=e,[c,u]=s({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});m(()=>{a&&u(e=>({...e,formData:a,isFormDisabled:r?.disableFields||Kb.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(o&&c.formData.id){u(e=>({...e,isLoading:!0}));try{await o(c.formData.id)}finally{u(e=>({...e,isLoading:!1}))}}},[o,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}}function Xb({status:e,labels:t,className:r}){const n=t?.[e]||qb[e]||"",i=Ub[e]||"#D6D6D6",s=Ob[e]||"#666666";return a("span",{className:Vi("inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold",r),style:{backgroundColor:i,color:s},children:n})}function Jb({formData:e,updateField:r,disabled:n=!1,users:s=[],places:o=[],actionTypes:l,causes:d=[],parentActions:c=[],config:u}){const{t:m}=nt(),p=u?.requiredFields,h=l||Wb,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(Zi,{className:Vi(g("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),a(Xi,{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(Zi,{className:Vi(g("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),t(Os,{value:e.responsibleId||"",onValueChange:e=>r("responsibleId",e),disabled:n,children:[a(qs,{children:a($s,{placeholder:m("ap_select_responsible")})}),a(Hs,{children:s.map(e=>a(Ks,{value:e.id,children:e.name},e.id))})]})]}),f("checkerWho")&&t("div",{className:"space-y-2",children:[a(Zi,{className:Vi(g("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),t(Os,{value:e.checkerId||"",onValueChange:e=>r("checkerId",e),disabled:n,children:[a(qs,{children:a($s,{placeholder:m("ap_select_checker")})}),a(Hs,{children:s.map(e=>a(Ks,{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(Zi,{className:Vi(g("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),t(Os,{value:e.placeId||"",onValueChange:e=>r("placeId",e),disabled:n,children:[a(qs,{children:a($s,{placeholder:m("ap_select_place")})}),a(Hs,{children:Zb(o).map(e=>a(Ks,{value:e.id,children:e.name},e.id))})]})]}),f("planType")&&t("div",{className:"space-y-2",children:[a(Zi,{className:Vi(g("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),t(Os,{value:e.typeId||"",onValueChange:e=>r("typeId",e),disabled:n,children:[a(qs,{children:a($s,{placeholder:m("ap_select_type")})}),a(Hs,{children:h.map(e=>a(Ks,{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(Zi,{className:Vi(g("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),t(Os,{value:e.priorityType?.toString()||"",onValueChange:e=>r("priorityType",Number(e)),disabled:n,children:[a(qs,{children:a($s,{placeholder:m("ap_select_priority")})}),a(Hs,{children:Gb.map(e=>a(Ks,{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(Zi,{children:m("ap_belongs_to")}),t(Os,{value:e.parentId||"",onValueChange:e=>r("parentId",e),disabled:n,children:[a(qs,{children:a($s,{placeholder:m("ap_select_parent")})}),a(Hs,{children:c.map(e=>a(Ks,{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(Zi,{className:Vi(g("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),a(Nu,{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(Zi,{className:Vi(g("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),a(Nu,{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(Zi,{children:m("ap_duration_days")}),a(Xi,{type:"number",value:v,disabled:!0,className:"bg-muted"})]})]}),f("estimatedCost")&&t("div",{className:"space-y-2 max-w-xs",children:[a(Zi,{className:Vi(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(Xi,{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(Zi,{children:"Causa"}),t(Os,{value:e.causeId||"",onValueChange:e=>r("causeId",e),disabled:n,children:[a(qs,{children:a($s,{placeholder:m("ap_select_cause")})}),a(Hs,{children:d.map(e=>a(Ks,{value:e.id,children:e.label},e.id))})]})]}),f("description")&&t("div",{className:"space-y-2",children:[a(Zi,{className:Vi(g("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),a(Xs,{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(Zi,{className:Vi(g("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),a(Xs,{value:e.justification||"",onChange:e=>r("justification",e.target.value),maxLength:4e3,disabled:n,rows:4,placeholder:m("ap_justification_placeholder")})]})]})}function Zb(e,a=0){const t=[];for(const r of e)t.push({...r,depth:a}),r.children?.length&&t.push(...Zb(r.children,a+1));return t}function ex(e){const{progress:a,onReportProgress:t,onEditProgress:r,onDeleteProgress:n}=e,[i,o]=s(!1),[d,c]=s(null),u=!!a&&Yb.includes(a.status),m=l(async e=>{if(t&&a){o(!0);try{const r=100===e.percentProgress;await t({id:a.id,...e,conclude:r})}finally{o(!1)}}},[t,a]),p=l(async e=>{if(r){o(!0);try{await r(e)}finally{o(!1),c(null)}}},[r]),h=l(async e=>{if(n){o(!0);try{await n(e)}finally{o(!1)}}},[n]);return{progress:a,canReportProgress:u,isSubmitting:i,editingReport:d,setEditingReport:c,reportProgress:m,editProgress:p,deleteProgress:h}}function ax(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 tx(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 rx(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function nx({open:e,onOpenChange:r,report:n,onSave:o,isSubmitting:l=!1}){const{t:d}=nt(),[c,u]=s(n?.percentProgress||0),[m,p]=s(n?.timeProgress||""),[h,f]=s(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(bs,{open:e,onOpenChange:r,children:t(Cs,{className:"sm:max-w-md",variant:"form",isDirty:g,children:[a(ks,{children:a(Es,{children:d("ap_edit_progress")})}),t("div",{className:"space-y-4 py-4",children:[t("div",{className:"space-y-2",children:[a(Zi,{children:d("ap_progress_percent")}),a(Xi,{type:"number",min:0,max:100,value:c,onChange:e=>u(Number(e.target.value))})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:d("ap_time_spent")}),a(Xi,{value:m,onChange:e=>p(e.target.value),onBlur:()=>p(ax(m)||""),placeholder:"00:00"})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:d("ap_comments")}),a(Xs,{value:h,onChange:e=>f(e.target.value),rows:3,maxLength:4e3})]})]}),t(As,{children:[a(Yi,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancelar"}),a(Yi,{onClick:()=>{n&&o({...n,percentProgress:c,timeProgress:ax(m)||"00:00",comments:h})},disabled:l,children:l?"Salvando...":"Salvar"})]})]})})}function ix(e){const{t:r}=nt(),{progress:n,canReportProgress:i,isSubmitting:o,editingReport:l,setEditingReport:d,reportProgress:c,editProgress:u,deleteProgress:m}=ex(e),[p,h]=s(""),[f,g]=s(""),[v,b]=s("");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=rx(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(Nm,{value:n.percentProgress,className:"h-3"}),n.timeProgress&&t("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",tx(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(Zi,{children:r("ap_progress_percent")}),a(Xi,{type:"number",min:0,max:100,value:p,onChange:e=>h(e.target.value),placeholder:"0"})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:r("ap_time_spent")}),a(Xi,{value:f,onChange:e=>g(e.target.value),onBlur:()=>g(ax(f)||""),placeholder:"00:00"})]})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:r("ap_comments")}),a(Xs,{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(Yi,{variant:"outline",size:"sm",onClick:()=>{h(""),g(""),b("")},disabled:N||o,children:"Limpar"}),a(Yi,{size:"sm",onClick:async()=>{const e=Number(p);(e||0===e)&&(await c({percentProgress:e,timeProgress:ax(f)||"00:00",comments:v}),h(""),g(""),b(""))},disabled:y||o,children:o?"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(sx,{report:e,onEdit:()=>d(e),onDelete:()=>m(e.id),disabled:!i},e.id))})]}),a(nx,{open:!!l,onOpenChange:e=>!e&&d(null),report:l,onSave:u,isSubmitting:o})]})}function sx({report:r,onEdit:n,onDelete:i,disabled:s}){const o=r.date?new Date(r.date):null,l=rx(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}),o&&a("span",{className:"text-xs text-muted-foreground",children:o.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: ",tx(r.timeProgress)]})]}),r.comments&&a("p",{className:"text-xs text-muted-foreground mt-1",children:r.comments})]}),!s&&t(no,{children:[a(io,{asChild:!0,children:a(Qi,{})}),t(po,{align:"end",children:[a(ho,{onClick:n,children:e.t("edit")}),a(ho,{className:"text-destructive",onClick:i,children:e.t("ap_delete")})]})]})]})}function ox({predecessors:e=[],availablePredecessors:r=[],onAdd:n,onRemove:s,disabled:o=!1}){const{t:l}=nt(),[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:[!o&&u.length>0&&t("div",{className:"flex items-end gap-3",children:[t("div",{className:"flex-1 space-y-2",children:[a(Zi,{children:l("ap_add_predecessor")}),t(Os,{value:d,onValueChange:c,children:[a(qs,{children:a($s,{placeholder:l("ap_select_action")})}),a(Hs,{children:u.map(e=>a(Ks,{value:e.id,children:e.label},e.id))})]})]}),t(Yi,{size:"sm",onClick:()=>{d&&n&&(n(d),c(""))},disabled:!d,children:[a(Y,{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(Xb,{status:e.predecessorStatus})]}),!o&&s&&t(no,{children:[a(io,{asChild:!0,children:a(Qi,{})}),a(po,{align:"end",children:a(ho,{className:"text-destructive",onClick:()=>s(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 lx({costs:e=[],onAdd:r,onEdit:n,onDelete:i,disabled:o=!1}){const{t:l}=nt(),[d,c]=s(""),[u,m]=s(""),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})]})]}),!o&&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(Zi,{children:"Descrição"}),a(Xi,{value:d,onChange:e=>c(e.target.value),placeholder:l("ap_cost_description")})]}),t("div",{className:"space-y-2",children:[a(Zi,{children:"Valor (R$)"}),a(Xi,{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(Yi,{size:"sm",onClick:()=>{d&&u&&r&&(r({description:d,value:Number(u),date:(new Date).toISOString()}),c(""),m(""))},disabled:!d||!u,children:[a(Y,{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})]}),!o&&(n||i)&&t(no,{children:[a(io,{asChild:!0,children:a(Qi,{})}),t(po,{align:"end",children:[n&&a(ho,{onClick:()=>n(e),children:l("edit")}),i&&a(ho,{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 dx({comments:e=[],currentUserId:r,onAdd:n,onEdit:i,onDelete:o,disabled:l=!1,maxLength:d=4e3}){const{t:c}=nt(),[u,m]=s(""),[p,h]=s(!1),[f,g]=s(null),[v,b]=s(""),x=()=>{g(null),b("")};return t("div",{className:"space-y-6 p-1",children:[!l&&n&&t("div",{className:"space-y-3",children:[a(Xs,{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(Yi,{variant:"outline",size:"sm",onClick:()=>m(""),disabled:!u||p,children:"Limpar"}),a(Yi,{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(Zs,{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(Fa,{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:cx(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(Xs,{value:v,onChange:e=>b(e.target.value),maxLength:d,rows:3}),t("div",{className:"flex gap-2 justify-end",children:[a(Yi,{variant:"outline",size:"sm",onClick:x,disabled:p,children:"Cancelar"}),a(Yi,{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(no,{children:[a(io,{asChild:!0,children:a(Qi,{})}),t(po,{align:"end",children:[i&&a(ho,{onClick:()=>(e=>{g(e.id),b(e.stringText||e.text)})(e),children:c("edit")}),o&&a(ho,{className:"text-destructive",onClick:()=>(async e=>{if(o){h(!0);try{await o(e)}finally{h(!1)}}})(e.id),children:"Excluir"})]})]})]},e.id))]})]})}function cx(e){const{t:a}=nt();if(!e)return"";const t=new Date(e);return`${t.toLocaleDateString("pt-BR")} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function ux({history:e=[],isLoading:r=!1}){const{t:n}=nt();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(Ee,{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(Be,{className:"h-3 w-3"}),a("span",{children:mx(e.date)})]}),t("div",{className:"flex items-center gap-1",children:[a(Ee,{className:"h-3 w-3"}),a("span",{children:px(e.date)})]}),e.isMobileRequest&&t("div",{className:"flex items-center gap-1",children:[a(ja,{className:"h-3 w-3"}),a("span",{children:n("ap_via_app")})]})]})]})]},e.id))})]})})}function mx(e){const{t:a}=nt();return new Date(e).toLocaleDateString("pt-BR")}function px(e){const{t:a}=nt();return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function hx({attachments:e=[],onUpload:n,onDelete:i,onRename:o,onDownload:l,onView:d,disabled:c=!1}){const{t:m}=nt(),p=u(null),[h,f]=s(null),[g,v]=s(""),b=async e=>{g.trim()&&o&&(await o(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(Yi,{size:"sm",onClick:()=>p.current?.click(),children:[a(Y,{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:Vi("flex items-center gap-3 rounded-lg border bg-card p-3",e.status===Fb.error&&"border-destructive/50 bg-destructive/5",e.status===Fb.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(Yi,{size:"sm",variant:"outline",onClick:x,children:m("cancel")}),a(Yi,{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===Fb.uploading||e.status===Fb.waiting)&&a(Nm,{value:e.progress||0,className:"h-1.5"}),e.status===Fb.error&&a("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),e.status===Fb.duplicateItem&&a("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),e.status===Fb.canceled&&a("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),t("div",{className:"flex items-center gap-2",children:[e.status===Fb.done&&t(r,{children:[a("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:fx(e.size)}),t(no,{children:[a(io,{asChild:!0,children:a(Qi,{})}),t(po,{align:"end",children:[o&&!c&&a(ho,{onClick:()=>(e=>{const a=e.name.replace(e.extension,"");f(e.id),v(a)})(e),children:"Renomear"}),d&&a(ho,{onClick:()=>d(e.id),children:"Visualizar"}),l&&a(ho,{onClick:()=>l(e.id),children:"Download"}),i&&!c&&t(r,{children:[a(bo,{}),a(ho,{className:"text-destructive",onClick:()=>i(e.id),children:"Excluir"})]})]})]})]}),e.status===Fb.uploading&&a(Yi,{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(Ua,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function fx(e){const{t:a}=nt();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 gx(e){const{formData:r,isLoading:n,isSaving:i,activeTab:s,isFormDisabled:o,updateField:l,setActiveTab:d,save:c,changeStatus:u,remove:m,cancel:p}=Qb(e),{t:h}=nt(),{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:T,onAddPredecessor:I,onRemovePredecessor:R,onAddCost:M,onEditCost:L,onDeleteCost:z,onAddComment:F,onEditComment:j,onDeleteComment:U,onUploadAttachment:O,onDeleteAttachment:B,onRenameAttachment:$,onDownloadAttachment:q,onViewAttachment:V}=e;if(n&&!r.id)return a(to,{isLoading:!0,children:a("div",{})});const W=function(e){const{t:a}=nt();if(!e)return[];return{[Db.waitingStart]:[Db.running,Db.suspended,Db.canceled],[Db.running]:[Db.effectivenessCheck,Db.done,Db.suspended,Db.canceled],[Db.effectivenessCheck]:[Db.running,Db.done,Db.suspended,Db.canceled],[Db.done]:[Db.running],[Db.suspended]:[Db.running,Db.canceled],[Db.canceled]:[Db.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(Yi,{variant:"ghost",size:"icon",onClick:p,children:a(Pe,{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(Xb,{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&&!o&&t(no,{children:[a(io,{asChild:!0,children:a(Yi,{variant:"outline",size:"sm",children:"Alterar Status"})}),a(po,{align:"end",children:W.map(e=>a(ho,{onClick:()=>u(e),children:qb[e]},e))})]}),!f&&e.onDelete&&t(no,{children:[a(io,{asChild:!0,children:a(Yi,{variant:"ghost",size:"icon",children:a(Ta,{className:"h-4 w-4"})})}),a(po,{align:"end",children:a(ho,{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(Rc,{value:s,onValueChange:d,children:[t(Mc,{className:"mb-6",children:[a(Lc,{value:"general",children:"Geral"}),!f&&a(Lc,{value:"progress",children:"Progresso"}),!f&&g?.enablePredecessors&&a(Lc,{value:"predecessors",children:h("ap_predecessors")}),!f&&g?.enableCosts&&a(Lc,{value:"costs",children:"Custos"}),!f&&g?.enableAttachments&&a(Lc,{value:"attachments",children:h("ap_attachments")}),!f&&g?.enableComments&&a(Lc,{value:"comments",children:h("ap_comments")}),!f&&g?.enableHistory&&a(Lc,{value:"history",children:"Histórico"})]}),a(zc,{value:"general",children:a(Jb,{formData:r,updateField:l,disabled:o,users:v,places:b,actionTypes:x,causes:y,parentActions:N,config:g})}),!f&&a(zc,{value:"progress",children:a(ix,{...e})}),!f&&g?.enablePredecessors&&a(zc,{value:"predecessors",children:a(ox,{predecessors:_,availablePredecessors:C,onAdd:I,onRemove:R,disabled:o})}),!f&&g?.enableCosts&&a(zc,{value:"costs",children:a(lx,{costs:k,onAdd:M,onEdit:L,onDelete:z,disabled:o})}),!f&&g?.enableAttachments&&a(zc,{value:"attachments",children:D||a(hx,{attachments:E,onUpload:O,onDelete:B,onRename:$,onDownload:q,onView:V,disabled:o})}),!f&&g?.enableComments&&a(zc,{value:"comments",children:P||a(dx,{comments:S,onAdd:F,onEdit:j,onDelete:U,disabled:o})}),!f&&g?.enableHistory&&a(zc,{value:"history",children:T||a(ux,{history:A})})]})})}),t("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[p&&a(Yi,{variant:"outline",onClick:p,disabled:i,children:"Cancelar"}),a(Yi,{onClick:c,disabled:i||o,children:i?"Salvando...":"Salvar"})]})]})}const vx=["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 bx(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 xx(e){const a=e.lastIndexOf(".");return-1===a?"":e.substring(a+1).toLowerCase()}function yx({storedFile:e,customFileName:r,allowedExtensions:n,customExtensionErrorMessage:i,minSizeInBytes:o=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}=nt(),S=u(null),[E,D]=s(null),[P,T]=s(null),[I,R]=s(!1),M=E||e,L=E?.name||e?.name||"",z=E?.size||e?.size;L&&xx(L);const F=r||L,j=c&&!E&&!!e,U=m&&!E&&!!e,O=!!P||!!b||f&&g&&!M,B=!!M,$=l(e=>{if(vx.includes(e.type))return{type:"forbidden-type"};if(e.size<=o)return{type:"min-size"};if(e.size>=d)return{type:"max-size"};if(n?.length){const a=xx(e.name);if(!n.includes(a))return{type:"extension",message:i}}return null},[o,d,n,i]),q=l(e=>{const a=e.target.files?.[0];if(!a)return;const t=$(a);if(t)return T(t),D(null),void(S.current&&(S.current.value=""));T(null),D(a),x?.(a),S.current&&(S.current.value="")},[$,x]),V=l(e=>{if(e.preventDefault(),e.stopPropagation(),v)return;const a=e.dataTransfer.files?.[0];if(!a)return;const t=$(a);if(t)return T(t),void D(null);T(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),T(null),y?.(),S.current&&(S.current.value="")},[y]),K=l(async()=>{if(!I&&e&&w){R(!0);try{await w(e)}finally{R(!1)}}},[I,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: ${bx(o)}`;case"max-size":return`Tamanho máximo: ${bx(d)}`;default:return k("file_error")}})();return t("div",{className:Vi("space-y-1",C),children:[a("div",{className:Vi("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(xe,{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:bx(z)}),t("div",{className:"flex items-center gap-0.5",children:[j&&w&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:I,onClick:K,children:a(Ce,{className:"h-3.5 w-3.5 text-primary"})})}),a(_o,{children:"Download"})]}),U&&_&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:Y,children:a(pe,{className:"h-3.5 w-3.5 text-primary"})})}),a(_o,{children:"Visualizar"})]}),p&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:H,children:a(Ze,{className:"h-3.5 w-3.5 text-primary"})})}),a(_o,{children:"Substituir"})]}),h&&t(No,{children:[a(wo,{asChild:!0,children:a(Yi,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:G,children:a(A,{className:"h-3 w-3 text-muted-foreground"})})}),a(_o,{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:V,onDragOver:W,children:[a(Oa,{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:q,disabled:v})]})}var Nx,wx,_x,Cx,kx,Sx;function Ax(e){switch(e.type){case Nx.text:return e.textValue;case Nx.number:return e.numberValue;case Nx.date:return e.dateValue;case Nx.time:return e.timeValue;case Nx.url:case Nx.singleSelection:case Nx.multiSelection:return e.itemsValue;case Nx.questions:return e.questionsValue;case Nx.readOnlyText:return e.textValue;default:return null}}function Ex(e,a){if(!a)return!0;const t=null!=Ax(e)&&""!==Ax(e)&&!(Array.isArray(Ax(e))&&0===Ax(e).length);return!1!==e.isActive||t}function Dx(e){return e.filter(e=>e.type!==Nx.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===Nx.text?e.textValue:void 0,numberValue:e.type===Nx.number?e.numberValue:void 0,dateValue:e.type===Nx.date?e.dateValue:void 0,timeValue:e.type===Nx.time?e.timeValue:void 0,itemsValue:[Nx.url,Nx.singleSelection,Nx.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===Nx.questions?e.questionsValue:void 0}))}function Px(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 Nx.text:r.textValue=t.textValue;break;case Nx.number:r.numberValue=t.numberValue;break;case Nx.date:r.dateValue=t.dateValue;break;case Nx.time:r.timeValue=t.timeValue;break;case Nx.url:case Nx.singleSelection:case Nx.multiSelection:r.itemsValue=t.itemsValue||[];break;case Nx.questions:r.questionsValue=t.questionsValue||[]}return r}):e}function Tx(e){const a=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===Nx.readOnlyText)return;const t=Ax(e);if((null==t||""===t||Array.isArray(t)&&0===t.length)&&a.push(e.id),e.type===Nx.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 Ix({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 Rx({field:e,readOnly:r,onChange:n}){const i=e.config,s=i?.multiline??!1,o=r||e.readOnly,l=a=>{n?.({...e,textValue:a})};return t("div",{className:"space-y-1.5",children:[a(Zi,{className:Vi(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?a(Xs,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:o,rows:4}):a(Xi,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:o})]})}function Mx({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,s=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(Zi,{className:Vi(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(Xi,{type:"date",value:s,onChange:a=>{return t=a.target.value,void n?.({...e,dateValue:t||void 0});var t},placeholder:e.placeholder,disabled:i})]})}function Lx({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,s=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(Zi,{className:Vi(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(Xi,{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:s(a.target.value)}),placeholder:e.placeholder,disabled:i})]})}function zx({field:e,readOnly:r,onChange:n}){const i=e.config,o=i?.multiple??!1,l=r||e.readOnly,[d,c]=s(""),u=e.itemsValue||[],m=()=>{if(!d.trim())return;const a={value:crypto.randomUUID(),text:d.trim()};n?.({...e,itemsValue:[...u,a]}),c("")};if(!o){const r=u[0]?.text||"";return t("div",{className:"space-y-1.5",children:[a(Zi,{className:Vi(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(Xi,{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(Yi,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:a("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:a(ea,{className:"h-4 w-4"})})})]})]})}return t("div",{className:"space-y-1.5",children:[a(Zi,{className:Vi(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(Xi,{type:"url",value:d,onChange:e=>c(e.target.value),placeholder:e.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),a(Yi,{variant:"outline",size:"icon",onClick:m,disabled:!d.trim(),className:"flex-shrink-0",children:a(Y,{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(Yi,{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(W,{className:"h-3 w-3"})})]},r.value))})]})}function Fx({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=null!=i?.decimals&&i.decimals>0?(1/Math.pow(10,i.decimals)).toString():"1";return t("div",{className:"space-y-1.5",children:[a(Zi,{className:Vi(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(Xi,{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:s,min:i?.min,max:i?.max,step:o}),null!=i?.min&&null!=i?.max&&t("p",{className:"text-xs text-muted-foreground",children:["Min: ",i.min," | Max: ",i.max]})]})}function jx({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=i?.viewMode??_x.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(Zi,{className:Vi(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===_x.dropdown&&t(Os,{value:d,onValueChange:c,disabled:s,children:[a(qs,{children:a($s,{placeholder:e.placeholder||"Selecione..."})}),a(Hs,{children:l.map(e=>t(Ks,{value:e.value,children:[e.text,!1===e.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},e.value))})]}),(o===_x.radio||o===_x.buttons)&&a(wm,{value:d,onValueChange:c,disabled:s,className:Vi(o===_x.buttons?"flex flex-wrap gap-2":"space-y-2"),children:l.map(r=>t("div",{className:"flex items-center gap-2",children:[a(_m,{value:r.value,id:`${e.id}-${r.value}`}),t(Zi,{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))}),!s&&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 Ux({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=i?.viewMode??_x.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(Zi,{className:Vi(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(Zs,{variant:"secondary",className:"gap-1 pr-1",children:[a("span",{className:"text-xs",children:r.text}),!s&&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(A,{className:"h-3 w-3"})})]},r.value))}),!s&&a("div",{className:Vi(o===_x.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(Qs,{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:s}),t(Zi,{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 Ox({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=i?.questions||[],l=i?.options||[],d=e.questionsValue||[];return 0===o.length||0===l.length?t("div",{className:"space-y-1.5",children:[a(Zi,{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(Zi,{className:Vi(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:o.map((r,i)=>t("tr",{className:Vi(i<o.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(wm,{value:(i=r.value,d.find(e=>e.questionValue===i)?.optionValue||""),onValueChange:a=>((a,t,r,i)=>{const s={questionValue:a,questionText:t,optionValue:r,optionText:i},o=d.filter(e=>e.questionValue!==a);o.push(s),n?.({...e,questionsValue:o})})(r.value,r.text,a,t.text),disabled:s,className:"flex justify-center",children:a(_m,{value:t.value,id:`${e.id}-${r.value}-${t.value}`})})},t.value);var i})]},r.value))})]})})]})}function Bx({fields:e,readOnly:t=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:i}){const s=l(a=>{if(i?.(a),n){const t=e.map(e=>e.id===a.id?a:e);n(t)}},[e,n,i]),o=e.filter(e=>Ex(e,r));return 0===o.length?null:a("div",{className:"space-y-4",children:o.map(e=>a($x,{field:e,readOnly:t,onChange:s},e.id))})}function $x({field:e,readOnly:t,onChange:r}){const n={field:e,readOnly:t,onChange:r};switch(e.type){case Nx.readOnlyText:return a(Ix,{...n});case Nx.text:return a(Rx,{...n});case Nx.date:return a(Mx,{...n});case Nx.time:return a(Lx,{...n});case Nx.url:return a(zx,{...n});case Nx.number:return a(Fx,{...n});case Nx.singleSelection:return a(jx,{...n});case Nx.multiSelection:return a(Ux,{...n});case Nx.questions:return a(Ox,{...n});default:return null}}function qx({queryParams:e,events:r,softwares:n,users:i=[],permissions:o={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:d=!1,onFilter:c,onReset:u,onExport:m,onSoftwareChange:p}){const[h,f]=s(e.softwareId),[g,v]=s(e.eventId),[b,x]=s(e.userId||"all"),[y,N]=s(Vx(e.startDate)),[w,_]=s(Vx(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(Vx(a)),_(Vx(a)),v(e.eventId),o.viewAllEvents&&x("all"),u?.()},[e.eventId,o.viewAllEvents,u]),A=o.viewOnlyMyEvents&&!o.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(Zi,{className:"text-xs text-muted-foreground",children:"Módulo *"}),t(Os,{value:String(h),onValueChange:C,disabled:d,children:[a(qs,{className:"h-8 text-xs",children:a($s,{placeholder:"Selecione..."})}),a(Hs,{children:n.map(e=>a(Ks,{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(Zi,{className:"text-xs text-muted-foreground",children:"Evento *"}),t(Os,{value:String(g),onValueChange:e=>v(parseInt(e)),disabled:d,children:[a(qs,{className:"h-8 text-xs",children:a($s,{placeholder:"Selecione..."})}),a(Hs,{children:r.map(e=>a(Ks,{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(Zi,{className:"text-xs text-muted-foreground",children:"Usuário *"}),t(Os,{value:b,onValueChange:x,disabled:d||A,children:[a(qs,{className:"h-8 text-xs",children:a($s,{placeholder:"Selecione..."})}),t(Hs,{children:[a(Ks,{value:"all",className:"text-xs",children:"Todos"}),i.map(e=>a(Ks,{value:e.id,className:"text-xs",children:e.name},e.id))]})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[a(Zi,{className:"text-xs text-muted-foreground",children:"De *"}),a(Xi,{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(Zi,{className:"text-xs text-muted-foreground",children:"Até *"}),a(Xi,{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(Yi,{variant:"outline",size:"sm",onClick:S,disabled:d,children:[a(Ba,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),o.download&&m&&t(Yi,{variant:"outline",size:"sm",onClick:()=>m("xlsx"),disabled:d,children:[a(Ce,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),t(Yi,{size:"sm",onClick:k,disabled:d||!E,children:[a(Re,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function Vx(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function Wx(e,a,t,r="Anônimo"){return e.map(e=>({...e,translatedSoftware:Gx(e.software,t),user:e.userEmail||e.userName||r,translatedEvent:Hx(e.eventName,a),date:new Date(e.dateTime)})).sort((e,a)=>(a.date?.getTime()??0)-(e.date?.getTime()??0))}function Hx(e,a){const t=a.find(a=>a.name===e);return t?.translation||e}function Gx(e,a){const t=e.includes(".")?e.split(".").pop():e,r=a.find(e=>e.software===t);return r?.translation||t}function Kx(e,a){const t=[],r={...ay,...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:Yx(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:Zx(e),value:a})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const i=Qx(e,n,a?.translateProperty),s=Xx(e,null,n,r,a);s&&t.push({name:i,value:s})})}),e.entities?.forEach(e=>{if(e.association?.length){const a=e.association.filter(e=>""!==e.id).map(e=>{const a=Yx(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 s=a?.formatDate?a.formatDate(e.dateTime):ey(e.dateTime);return t.push({name:r.accomplishedIn,value:s}),t}function Yx(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function Qx(e,a,t){if(e.propertyCustomName)return e.propertyCustomName;const r=Zx(e.property);return t?t(a,r):r}function Xx(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=Qx(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 s=`${a}: "${Jx(e,"newValue",r,n)}" ${i}`;const o=e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Xx(a,e,t,r,n)));return o.some(Boolean)&&(s+="\n"+o.filter(Boolean).join("\n")),s}return e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Xx(a,e,t,r,n))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const i=Jx(e,"oldValue",r,n),s=Jx(e,"newValue",r,n);return`${a?Qx(e,t,n?.translateProperty)+": ":""}${r.changedFrom} "${i}" ${r.changedTo} "${s}"`}const i=Jx(e,"newValue",r,n);return a?`${Qx(e,t,n?.translateProperty)}: ${i}`:i}function Jx(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):ey(n):String(n)}function Zx(e){return e.replace(/([A-Z])/g,(e,a,t)=>`${t>0?"-":""}${a.toLowerCase()}`)}function ey(e){try{return new Date(e).toLocaleString()}catch{return e}}(wx=Nx||(Nx={}))[wx.readOnlyText=1]="readOnlyText",wx[wx.text=2]="text",wx[wx.date=3]="date",wx[wx.time=4]="time",wx[wx.url=5]="url",wx[wx.number=6]="number",wx[wx.singleSelection=7]="singleSelection",wx[wx.multiSelection=8]="multiSelection",wx[wx.questions=9]="questions",(Cx=_x||(_x={}))[Cx.dropdown=1]="dropdown",Cx[Cx.buttons=2]="buttons",Cx[Cx.radio=3]="radio",Cx[Cx.checkbox=4]="checkbox",(Sx=kx||(kx={}))[Sx.custom=1]="custom",Sx[Sx.users=2]="users",Sx[Sx.usersLists=3]="usersLists";const ay={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 ty({documentId:e,onFetchDetails:r,onClose:n,labels:i,translateProperty:o,translatePropertyValue:d,formatDate:c}){const[u,p]=s(!1),[h,f]=s([]),[g,v]=s(null),b=l(async e=>{p(!0),v(null);try{const a=Kx(await r(e),{translateProperty:o,translatePropertyValue:d,formatDate:c,labels:i});f(a)}catch(a){v("Erro ao carregar detalhes da trilha de auditoria."),f([])}finally{p(!1)}},[r,o,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(Yi,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:n,children:a(A,{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(ao,{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 ry({title:r,softwares:n,softwareId:i,permissions:o={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}=nt();r??v("audit_trail");const[b,x]=s(!0),[y,N]=s([]),[w,_]=s([]),[C,k]=s([]),[S,A]=s(null),[E,D]=s(!1),P=u(null),T=new Date;T.setHours(0,0,0,0);const[I,R]=s({software:n.find(e=>e.id===i)?.software||"",softwareId:i,event:"All",eventId:1,startDate:T,endDate:T,limit:c,softwares:n,userId:o.viewOnlyMyEvents&&!o.viewAllEvents?p:void 0});m(()=>{(async()=>{x(!0);try{const[e,a]=await Promise.all([d.onFetchEvents(I.softwareId),d.onFetchUsers?.()??Promise.resolve([])]);_(e),k(a),await M(I,e)}catch(e){}finally{x(!1)}})()},[]);const M=l(async(e,a)=>{try{const t=Wx((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)},[]),j=l(()=>{D(!1),A(null)},[]),U=l(async()=>{const e={...I,startDate:T,endDate:T,eventId:1,userId:o.viewAllEvents?void 0:p};R(e),x(!0);try{await M(e)}finally{x(!1)}},[I,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(qx,{queryParams:I,events:w,softwares:n,users:C,permissions:o,isLoading:b,onFilter:L,onReset:U,onExport:o.download?O:void 0,onSoftwareChange:z})}),t("div",{className:"flex flex-1 min-h-0 relative",children:[t("div",{className:Vi("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(ao,{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(xe,{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($a,{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(Ee,{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(We,{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(xe,{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:Vi("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(pe,{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:Vi("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(ty,{documentId:S,onFetchDetails:d.onFetchDetails,onClose:j,labels:h,translateProperty:d.translateProperty,translatePropertyValue:d.translatePropertyValue,formatDate:f||B})})]})]})}function ny({open:r,onOpenChange:n,returnSteps:i,initialObservation:o="",title:l=e.t("approval_execute_action"),descriptions:d=[],setDefaultApproverOnInit:c=!0,onSubmit:u}){const[m,p]=s(!0),[h,f]=s(c&&i.length>0?i[0].id:null),[g,v]=s(o),b=e=>{p(e),e&&!c?f(null):!e&&!c&&i.length>0&&f(i[0].id)},x=g!==o||!m;return a(bs,{open:r,onOpenChange:n,children:t(Cs,{className:"sm:max-w-[480px]",variant:"form",isDirty:x,children:[a(ks,{children:a(Es,{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(Zi,{children:"Etapa"}),t(Os,{value:h??void 0,onValueChange:f,disabled:m,children:[a(qs,{children:a($s,{placeholder:e.t("approval_select_step")})}),a(Hs,{children:i.map(e=>a(Ks,{value:e.id,children:e.name},e.id))})]})]}),t("div",{className:"space-y-1.5",children:[a(Zi,{children:e.t("approval_opinion")}),a(Xs,{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(As,{children:[a(Yi,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),a(Yi,{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 iy({open:e,onOpenChange:r,approvers:n,isLoading:i=!1,ignoreUserIds:l=[],onSubmit:d}){const{t:c}=nt(),[u,m]=s(null),p=o(()=>{const e=new Set(l);return n.filter(a=>!e.has(a.id))},[n,l]),h=o(()=>p.map(e=>({value:e.id,label:e.name})),[p]);return a(bs,{open:e,onOpenChange:r,children:t(Cs,{className:"sm:max-w-[450px]",variant:"form",isDirty:!!u,children:[a(ks,{children:a(Es,{children:c("approval_select_approver")})}),a(to,{isLoading:i,type:"spinner",children:a("div",{className:"space-y-4",children:a(Oo,{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(As,{children:[a(Yi,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),a(Yi,{onClick:()=>{if(!u)return;const e=p.find(e=>e.id===u);e&&d(e)},disabled:!u||i,children:"Concluir"})]})]})})}function sy(e){const{t:a}=nt();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function oy({text:e,maxLength:r=130}){const{t:n}=nt(),[i,o]=s(!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:()=>o(!i),children:n(i?"approval_read_less":"approval_read_more")})]})}function ly({approver:e}){if(1===e.type&&e.approverId)return t(ou,{className:"h-9 w-9 shrink-0",children:[a(lu,{src:e.photoUrl,alt:e.name}),a(du,{className:"text-xs",children:e.name?.substring(0,2).toUpperCase()})]});const r=2===e.type?Aa:3===e.type?Oe:We;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 dy({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(Xe,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:sy(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(qa,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:sy(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(U,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function cy({approver:e}){const{t:r}=nt(),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(dy,{approver:e})]})}function uy({config:e,isLoading:r=!1,onClose:n,onApprove:i,onDefineApprover:o,onRefreshSteps:d,availableApprovers:c=[],isLoadingApprovers:u=!1}){const{t:m}=nt(),[p,h]=s(!1),[f,g]=s(!1),[v,b]=s(""),[x,y]=s(""),[N,w]=s(!1),[_,C]=s(""),k=r||p,S=l((e,a)=>{b(e),y(a??""),g(!0)},[]),E=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 o(e.associationId,_,a),await(d?.(e.associationId)),h(!1)},[e.associationId,_,o,d]),T=e.approvalFlowSteps.find(e=>e.isCurrentStep)?.approvers.filter(e=>1===e.type&&e.approverId).map(e=>e.approverId)??[],I=(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(Yi,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0",children:a(A,{className:"h-5 w-5"})}),a("span",{className:"text-lg font-medium",children:e.title})]}),k?a(to,{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:Vi("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:Vi("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(oy,{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 ",sy(r.returnDate)]})]}),r.returnObservation&&a("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:a(oy,{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(ly,{approver:e}),a(cy,{approver:e})]}),I(r,e)&&a(Yi,{size:"sm",onClick:()=>S(e.id),children:"Aprovar"}),R(r,e)&&a(Yi,{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(oy,{text:e.observation})}),e.returnObservation&&a("p",{className:"text-sm text-muted-foreground break-words ml-11",children:a(oy,{text:e.returnObservation})})]},e.id))]},r.id))]}),a(ny,{open:f,onOpenChange:g,returnSteps:e.returnSteps,initialObservation:x,title:e.approveDialogTitle,descriptions:e.approveDialogDescriptions,setDefaultApproverOnInit:e.approveDialogSetDefaultApproverOnInit,onSubmit:E}),a(iy,{open:N,onOpenChange:w,approvers:c,isLoading:u,ignoreUserIds:T,onSubmit:P})]})}var my,py;function hy({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}=nt(),g=u??f("leadership_remove_team"),v=p??f("leadership_no_members"),[b,x]=s(""),[y,N]=s(!1),[w,_]=s(null),C=o(()=>new Set(r),[r]),k=o(()=>e.filter(e=>C.has(e.id)),[e,C]),S=o(()=>e.filter(e=>!C.has(e.id)).map(e=>({value:e.id,label:e.name})),[e,C]),E=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:Vi("space-y-3",h),children:[a("div",{className:"flex items-start gap-3",children:a("div",{className:"flex-1",children:a(Oo,{options:S,value:b,onValueChange:e=>{const a="string"==typeof e?e:e?.[0]??"";x(a),a&&E(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(ou,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(lu,{src:e.avatar,alt:e.name}),a(du,{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(ue,{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(Oe,{className:"h-3.5 w-3.5"}),a("span",{className:"truncate max-w-[120px]",children:e.placeName})]}),a("button",{type:"button",className:Vi("text-muted-foreground hover:text-destructive transition-colors",i&&"opacity-50 pointer-events-none"),onClick:()=>!i&&D(e.id),title:f("remove"),children:a(A,{className:"h-4 w-4"})})]})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[a(We,{className:"h-12 w-12 mb-2 opacity-30"}),a("p",{className:"text-sm",children:v})]}),a(bs,{open:y,onOpenChange:N,children:t(Cs,{className:"sm:max-w-[400px]",children:[a(ks,{children:a(Es,{children:g})}),a("p",{className:"text-sm text-muted-foreground",children:m}),t(As,{children:[a(Yi,{variant:"ghost",onClick:()=>N(!1),children:"Cancelar"}),a(Yi,{variant:"destructive",onClick:P,children:"Remover"})]})]})})]})}(py=my||(my={}))[py.ApprovalFlow=1]="ApprovalFlow",py[py.Association=2]="Association";export{Cr as AUTH_CONFIG,Qc as AccessDeniedDialog,ru as Accordion,su as AccordionContent,nu as AccordionItem,iu as AccordionTrigger,Qi as ActionButton,Qi as ActionMenu,hd as ActionMenuItems,hx as ActionPlanAttachmentsTab,dx as ActionPlanCommentsTab,lx as ActionPlanCostTab,Jb as ActionPlanGeneralTab,ux as ActionPlanHistoryTab,gx as ActionPlanPage,ox as ActionPlanPredecessorsTab,nx as ActionPlanProgressDialog,ix as ActionPlanProgressTab,Xb as ActionPlanStatusBadge,jh as AggregationType,sc as Alert,lc as AlertDescription,os as AlertDialog,gs as AlertDialogAction,vs as AlertDialogCancel,us as AlertDialogContent,fs as AlertDialogDescription,ps as AlertDialogFooter,ms as AlertDialogHeader,cs as AlertDialogOverlay,ds as AlertDialogPortal,hs as AlertDialogTitle,ls as AlertDialogTrigger,oc as AlertTitle,rc as AliasRedirect,tc as AliasRouteGuard,Oh as AnalysisFunctionality,ov as AppHeader,bv as AppLayout,vv as AppSidebar,my as ApprovalFlowReturnStep,uy as ApprovalSidenav,ny as ApproveDialog,ty as AuditTrailDetails,qx as AuditTrailFilter,ry as AuditTrailPage,ml as AuthErrorInterceptor,Pl as AuthProvider,Sl as AuthService,Oo as AutoComplete,ou as Avatar,du as AvatarFallback,lu as AvatarImage,Zs as Badge,Od as BaseForm,am as Blockquote,Nv as BodyContent,cu as Breadcrumb,gu as BreadcrumbEllipsis,mu as BreadcrumbItem,pu as BreadcrumbLink,uu as BreadcrumbList,hu as BreadcrumbPage,fu as BreadcrumbSeparator,vg as BurndownPanel,Yi as Button,bu as ButtonGroup,Kb as CLOSED_STATUSES,kr as CRUD_CONFIG,jf as CURRENCY_FIELDS,xu as Calendar,dc as CallbackPage,es as Card,ns as CardContent,rs as CardDescription,is as CardFooter,as as CardHeader,Wl as CardSkeleton,ts as CardTitle,mg as CartesianPanel,Lp as ChartContainer,Up as ChartLegend,Op as ChartLegendContent,zp as ChartStyle,Fp as ChartTooltip,jp as ChartTooltipContent,Qs as Checkbox,Dc as Collapsible,Tc as CollapsibleContent,Pc as CollapsibleTrigger,Md as ColorPicker,Ko as ComboTree,Oo as Combobox,Eo as Command,Do as CommandDialog,Io as CommandEmpty,Ro as CommandGroup,Po as CommandInput,Lo as CommandItem,To as CommandList,Mo as CommandSeparator,zo as CommandShortcut,yv as ContentContainer,Zl as ContextMenu,dd as ContextMenuCheckboxItem,od as ContextMenuContent,ad as ContextMenuGroup,ld as ContextMenuItem,ud as ContextMenuLabel,td as ContextMenuPortal,nd as ContextMenuRadioGroup,cd as ContextMenuRadioItem,md as ContextMenuSeparator,pd as ContextMenuShortcut,rd as ContextMenuSub,sd as ContextMenuSubContent,id as ContextMenuSubTrigger,ed as ContextMenuTrigger,tu as CoreProviders,Cd as CrudActionBar,Bg as CrudActionMenu,Ug as CrudGrid,Kd as CrudPageInternal,$d as CrudPagination,$g as CrudPrimitiveFilterBar,Bd as CrudPrimitivePagination,Og as CrudPrimitiveTable,Td as CrudTable,Bx as CustomFormFields,Sb as D4SignWidget,Ff as DASHBOARD_STORAGE_KEYS,_i as DATETIME_FORMATS,Wb as DEFAULT_ACTION_TYPES,Si as DEFAULT_DATETIME_FORMAT,ki as DEFAULT_LOCALE,Ai as DEFAULT_TIMEZONE,Fg as DashboardForm,lf as DashboardFormTab,Bh as DashboardFunctionality,jg as DashboardGeneralView,Cg as DashboardGrid,mf as DashboardLanguage,Tg as DashboardList,qh as DashboardListType,Wh as DashboardPageTime,Gh as DashboardPanelDimension,Xh as DashboardPanelOrderBy,Yh as DashboardPanelOrderByType,Zh as DashboardPanelPeriod,Sg as DashboardPanelRenderer,af as DashboardPanelType,cf as DashboardShareType,rf as DashboardUpdateTime,Ag as DashboardView,sf as DashboardViewType,$g as DataFilterBar,yu as DataList,Bd as DataPagination,Og as DataTable,Nu as DatePicker,bs as Dialog,Ss as DialogBody,Ns as DialogClose,Cs as DialogContent,Ds as DialogDescription,As as DialogFooter,ks as DialogHeader,ws as DialogOverlay,ys as DialogPortal,Es as DialogTitle,xs as DialogTrigger,nh as DialogWizard,Co as DisabledMenuItem,Ab as DocumentSigner,wu as Drawer,ku as DrawerClose,Au as DrawerContent,Tu as DrawerDescription,Du as DrawerFooter,Eu as DrawerHeader,Su as DrawerOverlay,Cu as DrawerPortal,Pu as DrawerTitle,_u as DrawerTrigger,no as DropdownMenu,fo as DropdownMenuCheckboxItem,po as DropdownMenuContent,so as DropdownMenuGroup,ho as DropdownMenuItem,vo as DropdownMenuLabel,oo as DropdownMenuPortal,co as DropdownMenuRadioGroup,go as DropdownMenuRadioItem,bo as DropdownMenuSeparator,xo as DropdownMenuShortcut,lo as DropdownMenuSub,mo as DropdownMenuSubContent,uo as DropdownMenuSubTrigger,io as DropdownMenuTrigger,Fb as EAttachmentItemStatus,Nx as ECustomFormFieldType,_x as EFieldViewMode,kx as ESelectionFieldDataSource,Rb as ETaskPlanAssociationType,Tb as ETaskPlanPriority,Db as ETaskPlanStatus,Lb as ETaskPlanTypeProgress,th as ElectronicSignatureDialog,Xl as EllipsisText,Av as EmailService,Ql as EmptyState,Oo as EntitySelect,Ic as ErrorBoundary,eh as ExportDialog,Qp as ExportFormat,vx as FORBIDDEN_FILE_TYPES,uh as FilePrintType,dh as FileViewerType,Gd as FilterBar,Ps as Form,Fs as FormControl,Mx as FormDateField,js as FormDescription,Is as FormField,Ls as FormItem,zs as FormLabel,Us as FormMessage,Ux as FormMultiSelectionField,Fx as FormNumericField,Ox as FormQuestionsField,jx as FormSingleSelectionField,Hl as FormSkeleton,Rx as FormTextField,Lx as FormTimeField,zx as FormUrlField,Mu as Grid,Wu as H1,Hu as H2,Gu as H3,Ku as H4,Gl as HeaderSkeleton,Lu as HoverCard,Fu as HoverCardContent,zu as HoverCardTrigger,zd as IconPicker,wh as IframeDialog,cb as ImageEditor,ub as ImageRenderer,em as InlineCode,Xi as Input,ju as InputGroup,Ou as InputGroupAddon,$u as InputGroupButton,qu as InputGroupInput,Vu as InputGroupTextarea,Uf as LINK_PROPERTIES,Rr as LOGO_CONFIG,Zi as Label,Xu as Large,Qu as Lead,Qv as LeadershipDialog,Yv as LeadershipForm,Zv as LeadershipPage,tm as List,dg as ListPanel,to as LoadingState,Cc as LocaleProvider,cc as LoginPage,Mr as MESSAGES,Oc as MODULES_DATA,zf as MONTHS_MAP,Dv as ManageAccessModal,xg as MatrixRiskPanel,hf as MatrixViewType,Np as Menubar,Ap as MenubarCheckboxItem,kp as MenubarContent,vp as MenubarGroup,Sp as MenubarItem,Dp as MenubarLabel,gp as MenubarMenu,bp as MenubarPortal,yp as MenubarRadioGroup,Ep as MenubarRadioItem,Pp as MenubarSeparator,Tp as MenubarShortcut,xp as MenubarSub,Cp as MenubarSubContent,_p as MenubarSubTrigger,wp as MenubarTrigger,hv as ModalStateProvider,Jc as ModuleAccessGuard,qc as ModuleGrid,Zc as ModuleOfferContent,Ac as ModuleProvider,Vc as ModulesContent,Yc as ModulesDialog,Uc as ModulesFooterCards,Oo as MultiSelect,Ph as MultiselectPermissions,Zu as Muted,rm as NavigationMenu,lm as NavigationMenuContent,um as NavigationMenuIndicator,im as NavigationMenuItem,dm as NavigationMenuLink,nm as NavigationMenuList,om as NavigationMenuTrigger,cm as NavigationMenuViewport,av as NavigationProvider,og as NumericPanel,Kp as OnboardingDialog,Nh as OnlineEditorDialog,Yu as P,Gb as PRIORITIES,xr as PROD_PROJECT_ID,Yb as PROGRESS_ALLOWED_STATUSES,mm as PageBreadcrumb,mc as PageMetadataProvider,hm as Pagination,fm as PaginationContent,ym as PaginationEllipsis,gm as PaginationItem,vm as PaginationLink,xm as PaginationNext,bm as PaginationPrevious,Mf as PaletteType,tg as PanelError,ag as PanelHeader,gf as PanelItemsPerPanel,rg as PanelLoader,ng as PanelNoData,bf as PanelSortType,yf as PanelState,ig as PanelUnavailable,gg as ParetoPanel,bg as PerformancePanel,fg as PiePanel,Pv as PlaceCard,Tv as PlacesList,Cf as PlanType,ko as Popover,Ao as PopoverContent,So as PopoverTrigger,Nm as Progress,ec as ProtectedRoute,Ir as QUALIEX_CONFIG,Tr as QUERY_KEYS,yl as QualiexEnrichmentService,pl as QualiexErrorInterceptor,Ud as QualiexUserField,Sf as QueriesContextType,Ef as QueriesShareType,Pf as QuickFilterDashboard,wm as RadioGroup,_m as RadioGroupItem,Ix as ReadOnlyTextField,zh as ReportRequestList,Th as ReportRequestStatus,Sm as ResizableHandle,km as ResizablePanel,Cm as ResizablePanelGroup,Vp as RichTextEditor,If as RiskCriticality,Sr as SEARCH_CONFIG,Ub as STATUS_COLORS,qb as STATUS_LABELS,Bb as STATUS_MAP,Ob as STATUS_TEXT_COLORS,wi as SUPPORTED_LOCALES,Bo as ScrollArea,$o as ScrollBar,Os as Select,iy as SelectApproverDialog,Hs as SelectContent,Bs as SelectGroup,Ks as SelectItem,Gs as SelectLabel,Ws as SelectScrollDownButton,Vs as SelectScrollUpButton,Oo as SelectSearch,Ys as SelectSeparator,qs as SelectTrigger,$s as SelectValue,ss as Separator,Am as Sheet,Lm as SheetBody,Dm as SheetClose,Rm as SheetContent,jm as SheetDescription,zm as SheetFooter,Mm as SheetHeader,Tm as SheetOverlay,Pm as SheetPortal,Fm as SheetTitle,Em as SheetTrigger,qm as Sidebar,dv as SidebarActionTrigger,Xm as SidebarContent,Ym as SidebarFooter,Jm as SidebarGroup,ep as SidebarGroupAction,ap as SidebarGroupContent,Zm as SidebarGroupLabel,xv as SidebarHeader,Gm as SidebarInput,Hm as SidebarInset,sv as SidebarLogo,tp as SidebarMenu,sp as SidebarMenuAction,op as SidebarMenuBadge,ip as SidebarMenuButton,rp as SidebarMenuItem,lp as SidebarMenuSkeleton,dp as SidebarMenuSub,up as SidebarMenuSubButton,cp as SidebarMenuSubItem,$m as SidebarProvider,Wm as SidebarRail,Qm as SidebarSeparator,Kl as SidebarSkeleton,Vm as SidebarTrigger,Eb as SignConfigForm,kb as SignWidget,yx as SingleFileUpload,Fo as Skeleton,mp as Slider,Ju as Small,ro as SonnerToaster,ao as Spinner,Yp as SplitButton,Hd as Stack,rh as StepSelector,rh as Stepper,Fh as StimulsoftViewer,Fd as Switch,Ci as TIMEZONES,fp as TabPageContent,hp as TabPageHeader,pp as TabPageLayout,zl as Table,jl as TableBody,ql as TableCaption,$l as TableCell,Ul as TableFooter,Bl as TableHead,Fl as TableHeader,Jl as TableResizeHandle,Ol as TableRow,fd as TableRowActions,Vl as TableSkeleton,Rc as Tabs,zc as TabsContent,Mc as TabsList,Lc as TabsTrigger,hy as TeamSelector,_h as TermsOfUseDialog,Ch as TermsOfUseViewer,lg as TextPanel,Xs as Textarea,ah as Timepicker,ro as Toaster,yd as Toggle,wd as ToggleGroup,_d as ToggleGroupItem,nl as TokenManager,Yo as TokenService,No as Tooltip,_o as TooltipContent,yo as TooltipProvider,wo as TooltipTrigger,Ko as TreeSelect,Gg as TreeTable,Xl as TruncatedCell,lh as UpdatesNotification,Ah as UsersGroupsSelector,lb as VideoEditor,db as VideoRenderer,xh as ViewerDialog,wf as VisualizationType,yc as addAppTranslations,Fr as assets,Js as badgeVariants,Kx as buildDetailRows,Mv as buildHierarchy,qi as buildModuleUrl,Xf as buildPlacesTree,bh as buildWopiUrl,vu as buttonGroupVariants,Ki as buttonVariants,mb as calculateAspectRatio,Zx as camelToDash,Vi as cn,Yd as createCrudPage,Yg as createCrudRoutingConfig,Kg as createRoutingHandlers,_l as createService,Qd as createSimpleSaveHandler,Rl as createSimpleService,Lr as createTranslatedMessages,Qf as currencyFormatter,Hi as debounce,gl as deriveEmailField,fl as deriveNameField,vl as deriveUsernameField,Mi as detectBrowserLocale,Fi as detectBrowserPreferences,Li as detectBrowserTimezone,sb as detectVideoProvider,Ev as emailService,il as errorService,fb as extractImageFileName,Yf as extractNumberFromCurrency,rb as extractVimeoId,ab as extractYouTubeId,Rv as filterAndPromoteOrphans,Di as findDatetimeFormat,Ei as findLocale,Pi as findTimezone,Lv as flattenTree,bx as formatBytes,Bi as formatCurrency,Oi as formatDate,Ui as formatDatetime,gb as formatFileSize,tx as formatTime,ax as formatTimeProgress,Xd as generateCrudConfig,Vb as getActionTypes,Ng as getDefaultPanelSize,wr as getEnvironmentConfig,Ax as getFieldValue,xx as getFileExtension,Dx as getFormFieldValues,Vf as getLinkFromRow,wg as getMinPanelSize,fh as getOnlineViewerType,Hb as getPriorities,rx as getProgressColor,Pr as getQualiexApiUrl,$b as getStatusLabels,dl as getSupabaseClient,hh as getViewerType,vh as getWopiViewer,$i as handleExternalLink,zi as inferDatetimeFormat,Uu as inputGroupAddonVariants,Bu as inputGroupButtonVariants,Kf as isCurrency,Dr as isDevEnvironment,_r as isDevSupabaseProject,hb as isImageUrl,Ar as isLovablePreview,$f as isNullOrEmptyField,Ii as isValidDatetimeFormat,Ti as isValidLocale,Ri as isValidTimezone,_b as loadClicksignScript,au as loadForlogicFonts,jr as logoSrc,kv as mergeTranslationFiles,sm as navigationMenuTriggerStyle,ob as normalizeVideoUrl,nb as normalizeVimeoUrl,tb as normalizeYouTubeUrl,ib as parseIframeSrc,Iv as placeService,Wx as processTrails,qf as processUrl,hl as qualiexApi,pb as resizeKeepingAspect,bl as resolveFieldMappings,nv as resolvePageTitle,Px as setFormFieldValues,fc as setupQualiexCore,Ex as shouldShowField,Er as shouldUseDevTokens,Nb as signService,Gi as slugify,Ur as smallLogoSrc,Of as sortByMonthYear,Wf as toQueryString,xd as toggleVariants,Wi as trimTextFields,Qb as useActionPlan,ex as useActionPlanProgress,wv as useActiveModules,ac as useAliasFromUrl,Tl as useAuth,Id as useBaseForm,bd as useColumnResize,Uv as useCreateMultipleLeadersMutation,jv as useCreateSingleLeaderMutation,Il as useCrud,iv as useDebounce,Kc as useDerivedContractedModules,Rs as useFormField,gv as useHasOpenModal,Sv as useI18nFormatters,Ll as useIsMobile,zv as useLeadershipApi,kc as useLocale,Ml as useMediaQuery,eb as useMediaUpload,fv as useModalState,Gc as useModuleAccess,Ec as useModuleConfig,tv as useNavigation,hc as usePageMetadata,pc as usePageMetadataContext,rv as usePageTitle,lv as usePermissionQuery,jd as useQualiexUsers,Bv as useRemoveLeaderMutation,pm as useRouteBreadcrumbs,_v as useRowResize,Bm as useSidebar,mv as useSidebarResize,vb as useSignConfig,$v as useSyncSubordinatesMutation,Ov as useUpdateLeaderMutation,oh as useUpdatesNotification,Cv as useWizard,Tx 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 s,useMemo as o,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{EllipsisVertical as S,X as A,ChevronDown as E,ChevronUp as D,Check as P,Loader2 as I,Loader2Icon as T,OctagonXIcon as R,TriangleAlertIcon as M,InfoIcon as L,CircleCheckIcon as z,ChevronRight as F,Circle as j,AlertCircle as U,Search as O,FileX as B,Edit as $,PowerOff as q,Power as V,Trash2 as W,Pencil as H,ToggleRight as G,ToggleLeft as K,Plus as Y,LayoutGrid as Q,List as X,Table2 as J,Columns3 as Z,GripVertical as ee,Group as ae,ArrowUp as te,ArrowDown as re,ChevronsLeft as ne,ChevronLeft as ie,ChevronsRight as se,CheckCircle as oe,AlertTriangle as le,Info as de,RefreshCw as ce,Copy as ue,ExternalLink as me,NotebookText as pe,Building2 as he,User as fe,LogOut as ge,Sparkles as ve,MoreHorizontal as be,Calendar as xe,PanelLeft as ye,Edit3 as Ne,Code as we,Eye as _e,Heading1 as Ce,Heading2 as ke,Heading3 as Se,Bold as Ae,Italic as Ee,Underline as De,Strikethrough as Pe,ListOrdered as Ie,Highlighter as Te,Link as Re,RemoveFormatting as Me,Undo as Le,Redo as ze,ImageIcon as Fe,ArrowLeft as je,ArrowRight as Ue,FileText as Oe,FileSpreadsheet as Be,Image as $e,FileImage as qe,Clock as Ve,Lock as We,ShieldCheck as He,Mail as Ge,Coffee as Ke,CheckCheck as Ye,Star as Qe,Download as Xe,Users as Je,TriangleAlert as Ze,CheckCircle2 as ea,Hourglass as aa,MoreVertical as ta,ArrowUpToLine as ra,Camera as na,UserPen as ia,Menu as sa,Crown as oa,UserPlus as la,Settings as da,Upload as ca,MessageSquare as ua,Smartphone as ma,Paperclip as pa,CloudUpload as ha,RotateCcw as fa,Filter as ga,Layers as va,MapPin as ba,XCircle as xa,Shield as ya}from"lucide-react";import*as Na from"@radix-ui/react-label";import*as wa from"@radix-ui/react-dialog";import*as _a from"@radix-ui/react-separator";import*as Ca from"@radix-ui/react-alert-dialog";import{useFormContext as ka,FormProvider as Sa,Controller as Aa,appendErrors as Ea,useForm as Da}from"react-hook-form";import*as Pa from"@radix-ui/react-select";import*as Ia from"@radix-ui/react-checkbox";import*as Ta from"@radix-ui/react-dropdown-menu";import*as Ra from"@radix-ui/react-tooltip";import*as Ma from"@radix-ui/react-popover";import{useTranslation as La,initReactI18next as za,I18nextProvider as Fa}from"react-i18next";export{I18nextProvider,useTranslation}from"react-i18next";import*as ja from"@radix-ui/react-scroll-area";import{createClient as Ua}from"@supabase/supabase-js";import{useQueryClient as Oa,useQuery as Ba,useMutation as $a,QueryClient as qa,QueryClientProvider as Va}from"@tanstack/react-query";import{useSearchParams as Wa,useParams as Ha,useNavigate as Ga,useLocation as Ka,Navigate as Ya,Link as Qa}from"react-router-dom";import*as Xa from"@radix-ui/react-context-menu";import*as Ja from"@radix-ui/react-toggle-group";import*as Za from"@radix-ui/react-toggle";import*as et from"@radix-ui/react-switch";import*as at from"@radix-ui/react-collapsible";import*as tt from"@radix-ui/react-tabs";import*as rt from"@radix-ui/react-accordion";import*as nt from"@radix-ui/react-avatar";import{DayPicker as it}from"react-day-picker";import{Drawer as st}from"vaul";import*as ot from"@radix-ui/react-hover-card";import*as lt from"@radix-ui/react-navigation-menu";import*as dt from"@radix-ui/react-progress";import*as ct from"@radix-ui/react-radio-group";import*as ut from"react-resizable-panels";import*as mt from"@radix-ui/react-slider";import*as pt from"@radix-ui/react-menubar";import*as ht from"recharts";import{ResponsiveContainer as ft,XAxis as gt,YAxis as vt,CartesianGrid as bt,Tooltip as xt,Legend as yt,BarChart as Nt,Bar as wt,AreaChart as _t,Area as Ct,LineChart as kt,Line as St,PieChart as At,Pie as Et,Cell as Dt,ComposedChart as Pt}from"recharts";import{useEditor as It,EditorContent as Tt}from"@tiptap/react";import Rt from"@tiptap/starter-kit";import Mt from"@tiptap/extension-underline";import Lt from"@tiptap/extension-link";import{TextStyle as zt}from"@tiptap/extension-text-style";import{Color as Ft}from"@tiptap/extension-color";import jt from"@tiptap/extension-highlight";import{useSensors as Ut,useSensor as Ot,PointerSensor as Bt,DndContext as $t,closestCenter as qt}from"@dnd-kit/core";import{SortableContext as Vt,rectSortingStrategy as Wt,useSortable as Ht}from"@dnd-kit/sortable";import{z as Gt}from"zod";import{validateFieldsNatively as Kt,toNestErrors as Yt}from"@hookform/resolvers";const Qt="ccjfvpnndclajkleyqkc",Xt={storageProjectId:"ccjfvpnndclajkleyqkc",oauth:{authUrl:"https://login.qualiex.com/oauth2/authorize",clientId:"ae6021a0-e874-4aab-9716-b478e59cec20"},qualiexApiUrl:"https://common-v4-api.qualiex.com"},Jt={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 Zt(){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===Qt?Xt:Jt}function er(){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!==Qt}const ar={get oauth(){const e=Zt();return{authUrl:e.oauth.authUrl,clientId:e.oauth.clientId,responseType:"id_token token",scope:"openid profile email"}}},tr={pagination:{defaultPageSize:25,pageSizeOptions:[10,25,50,100]},sorting:{defaultField:"updated_at",defaultDirection:"desc"}},rr={debounceDelay:500},nr=()=>{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},ir=()=>nr(),sr=nr,or=()=>Zt().qualiexApiUrl,lr={crud:e=>[e],list:(e,a)=>[e,"list",a],detail:(e,a)=>[e,"detail",a]},dr={userNameFieldSuffix:"_name",userEmailFieldSuffix:"_email",userUsernameFieldSuffix:"_username"},cr={isQualiex:"true"===import.meta.env.VITE_IS_QUALIEX},ur={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}`}},mr=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)}}),pr=`https://${Zt().storageProjectId}.supabase.co/storage/v1/object/public/library-assets`,hr={logo:cr.isQualiex?`${pr}/logo-qualiex-white.svg`:`${pr}/saber-gestao-white.png`,smallLogo:cr.isQualiex?`${pr}/logo-forlogic-white.svg`:`${pr}/small.svg`,favicon:`${pr}/favicon.png`},fr=hr.logo,gr=hr.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=hr.favicon,document.head.appendChild(e)}const vr={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 br(e){return(a={})=>{const t=a.width?String(a.width):e.defaultWidth;return e.formats[t]||e.formats[e.defaultWidth]}}const xr={date:br({formats:{full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},defaultWidth:"full"}),time:br({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:br({formats:{full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},yr={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"};function Nr(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 wr(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 s=i[0],o=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(o)?function(e,a){for(let t=0;t<e.length;t++)if(a(e[t]))return t;return}(o,e=>e.test(s)):function(e,a){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&a(e[t]))return t;return}(o,e=>e.test(s));let d;d=e.valueCallback?e.valueCallback(l):l,d=t.valueCallback?t.valueCallback(d):d;return{value:d,rest:a.slice(s.length)}}}function _r(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 s=e.valueCallback?e.valueCallback(i[0]):i[0];s=t.valueCallback?t.valueCallback(s):s;return{value:s,rest:a.slice(n.length)}}}const Cr={code:"en-US",formatDistance:(e,a,t)=>{let r;const n=vr[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:xr,formatRelative:(e,a,t,r)=>yr[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:Nr({values:{narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},defaultWidth:"wide"}),quarter:Nr({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:Nr({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:Nr({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:Nr({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:_r({matchPattern:/^(\d+)(th|st|nd|rd)?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:wr({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:wr({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:wr({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:wr({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:wr({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 kr={};function Sr(){return kr}const Ar=6048e5;function Er(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 Dr(e){const a=Er(e);return a.setHours(0,0,0,0),a}function Pr(e){const a=Er(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 Ir(e,a){return e instanceof Date?new e.constructor(a):new Date(a)}function Tr(e){const a=Er(e),t=function(e,a){const t=Dr(e),r=Dr(a),n=+t-Pr(t),i=+r-Pr(r);return Math.round((n-i)/864e5)}(a,function(e){const a=Er(e),t=Ir(e,0);return t.setFullYear(a.getFullYear(),0,1),t.setHours(0,0,0,0),t}(a));return t+1}function Rr(e,a){const t=Sr(),r=a?.weekStartsOn??a?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,n=Er(e),i=n.getDay(),s=(i<r?7:0)+i-r;return n.setDate(n.getDate()-s),n.setHours(0,0,0,0),n}function Mr(e){return Rr(e,{weekStartsOn:1})}function Lr(e){const a=Er(e),t=a.getFullYear(),r=Ir(e,0);r.setFullYear(t+1,0,4),r.setHours(0,0,0,0);const n=Mr(r),i=Ir(e,0);i.setFullYear(t,0,4),i.setHours(0,0,0,0);const s=Mr(i);return a.getTime()>=n.getTime()?t+1:a.getTime()>=s.getTime()?t:t-1}function zr(e){const a=Er(e),t=+Mr(a)-+function(e){const a=Lr(e),t=Ir(e,0);return t.setFullYear(a,0,4),t.setHours(0,0,0,0),Mr(t)}(a);return Math.round(t/Ar)+1}function Fr(e,a){const t=Er(e),r=t.getFullYear(),n=Sr(),i=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=Ir(e,0);s.setFullYear(r+1,0,i),s.setHours(0,0,0,0);const o=Rr(s,a),l=Ir(e,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);const d=Rr(l,a);return t.getTime()>=o.getTime()?r+1:t.getTime()>=d.getTime()?r:r-1}function jr(e,a){const t=Er(e),r=+Rr(t,a)-+function(e,a){const t=Sr(),r=a?.firstWeekContainsDate??a?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,n=Fr(e,a),i=Ir(e,0);return i.setFullYear(n,0,r),i.setHours(0,0,0,0),Rr(i,a)}(t,a);return Math.round(r/Ar)+1}function Ur(e,a){return(e<0?"-":"")+Math.abs(e).toString().padStart(a,"0")}const Or={y(e,a){const t=e.getFullYear(),r=t>0?t:1-t;return Ur("yy"===a?r%100:r,a.length)},M(e,a){const t=e.getMonth();return"M"===a?String(t+1):Ur(t+1,2)},d:(e,a)=>Ur(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)=>Ur(e.getHours()%12||12,a.length),H:(e,a)=>Ur(e.getHours(),a.length),m:(e,a)=>Ur(e.getMinutes(),a.length),s:(e,a)=>Ur(e.getSeconds(),a.length),S(e,a){const t=a.length,r=e.getMilliseconds();return Ur(Math.trunc(r*Math.pow(10,t-3)),a.length)}},Br="midnight",$r="noon",qr="morning",Vr="afternoon",Wr="evening",Hr="night",Gr={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 Or.y(e,a)},Y:function(e,a,t,r){const n=Fr(e,r),i=n>0?n:1-n;if("YY"===a){return Ur(i%100,2)}return"Yo"===a?t.ordinalNumber(i,{unit:"year"}):Ur(i,a.length)},R:function(e,a){return Ur(Lr(e),a.length)},u:function(e,a){return Ur(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 Ur(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 Ur(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 Or.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 Ur(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=jr(e,r);return"wo"===a?t.ordinalNumber(n,{unit:"week"}):Ur(n,a.length)},I:function(e,a,t){const r=zr(e);return"Io"===a?t.ordinalNumber(r,{unit:"week"}):Ur(r,a.length)},d:function(e,a,t){return"do"===a?t.ordinalNumber(e.getDate(),{unit:"date"}):Or.d(e,a)},D:function(e,a,t){const r=Tr(e);return"Do"===a?t.ordinalNumber(r,{unit:"dayOfYear"}):Ur(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 Ur(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 Ur(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 Ur(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?$r:0===r?Br: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?Wr:r>=12?Vr:r>=4?qr:Hr,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 Or.h(e,a)},H:function(e,a,t){return"Ho"===a?t.ordinalNumber(e.getHours(),{unit:"hour"}):Or.H(e,a)},K:function(e,a,t){const r=e.getHours()%12;return"Ko"===a?t.ordinalNumber(r,{unit:"hour"}):Ur(r,a.length)},k:function(e,a,t){let r=e.getHours();return 0===r&&(r=24),"ko"===a?t.ordinalNumber(r,{unit:"hour"}):Ur(r,a.length)},m:function(e,a,t){return"mo"===a?t.ordinalNumber(e.getMinutes(),{unit:"minute"}):Or.m(e,a)},s:function(e,a,t){return"so"===a?t.ordinalNumber(e.getSeconds(),{unit:"second"}):Or.s(e,a)},S:function(e,a){return Or.S(e,a)},X:function(e,a,t){const r=e.getTimezoneOffset();if(0===r)return"Z";switch(a){case"X":return Yr(r);case"XXXX":case"XX":return Qr(r);default:return Qr(r,":")}},x:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"x":return Yr(r);case"xxxx":case"xx":return Qr(r);default:return Qr(r,":")}},O:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"O":case"OO":case"OOO":return"GMT"+Kr(r,":");default:return"GMT"+Qr(r,":")}},z:function(e,a,t){const r=e.getTimezoneOffset();switch(a){case"z":case"zz":case"zzz":return"GMT"+Kr(r,":");default:return"GMT"+Qr(r,":")}},t:function(e,a,t){return Ur(Math.trunc(e.getTime()/1e3),a.length)},T:function(e,a,t){return Ur(e.getTime(),a.length)}};function Kr(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+Ur(i,2)}function Yr(e,a){if(e%60==0){return(e>0?"-":"+")+Ur(Math.abs(e)/60,2)}return Qr(e,a)}function Qr(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+Ur(Math.trunc(r/60),2)+a+Ur(r%60,2)}const Xr=(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"})}},Jr=(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"})}},Zr={p:Jr,P:(e,a)=>{const t=e.match(/(P+)(p+)?/)||[],r=t[1],n=t[2];if(!n)return Xr(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}}",Xr(r,a)).replace("{{time}}",Jr(n,a))}},en=/^D+$/,an=/^Y+$/,tn=["D","DD","YY","YYYY"];function rn(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=Er(e);return!isNaN(Number(t))}const nn=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,sn=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,on=/^'([^]*?)'?$/,ln=/''/g,dn=/[a-zA-Z]/;function cn(e,a,t){const r=Sr(),n=t?.locale??r.locale??Cr,i=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,s=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Er(e);if(!rn(o))throw new RangeError("Invalid time value");let l=a.match(sn).map(e=>{const a=e[0];if("p"===a||"P"===a){return(0,Zr[a])(e,n.formatLong)}return e}).join("").match(nn).map(e=>{if("''"===e)return{isToken:!1,value:"'"};const a=e[0];if("'"===a)return{isToken:!1,value:un(e)};if(Gr[a])return{isToken:!0,value:e};if(a.match(dn))throw new RangeError("Format string contains an unescaped latin alphabet character `"+a+"`");return{isToken:!1,value:e}});n.localize.preprocessor&&(l=n.localize.preprocessor(o,l));const d={firstWeekContainsDate:i,weekStartsOn:s,locale:n};return l.map(r=>{if(!r.isToken)return r.value;const i=r.value;(!t?.useAdditionalWeekYearTokens&&function(e){return an.test(e)}(i)||!t?.useAdditionalDayOfYearTokens&&function(e){return en.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(tn.includes(e))throw new RangeError(r)}(i,a,String(e));return(0,Gr[i[0]])(o,i,n.localize,d)}).join("")}function un(e){const a=e.match(on);return a?a[1].replace(ln,"'"):e}function mn(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 pn(e,a){const t=function(e){fn[e]||(fn[e]=vn?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 fn[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=hn[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 hn={year:0,month:1,day:2,hour:3,minute:4,second:5};const fn={},gn=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")),vn="06/25/2014, 00:00:00"===gn||"‎06‎/‎25‎/‎2014‎ ‎00‎:‎00‎:‎00"===gn;function bn(e,a,t,r,n,i,s){const o=new Date(0);return o.setUTCFullYear(e,a,t),o.setUTCHours(r,n,i,s),o}const xn=36e5,yn={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Nn(e,a,t){if(!e)return 0;let r,n,i=yn.timezoneZ.exec(e);if(i)return 0;if(i=yn.timezoneHH.exec(e),i)return r=parseInt(i[1],10),_n(r)?-r*xn:NaN;if(i=yn.timezoneHHMM.exec(e),i){r=parseInt(i[2],10);const e=parseInt(i[3],10);return _n(r,e)?(n=Math.abs(r)*xn+6e4*e,"+"===i[1]?-n:n):NaN}if(function(e){if(Cn[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Cn[e]=!0,!0}catch(a){return!1}}(e)){a=new Date(a||Date.now());const r=t?a:function(e){return bn(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}(a),n=wn(r,e),i=t?n:function(e,a,t){const r=e.getTime();let n=r-a;const i=wn(new Date(n),t);if(a===i)return a;n-=i-a;const s=wn(new Date(n),t);if(i===s)return i;return Math.max(i,s)}(a,n,e);return-i}return NaN}function wn(e,a){const t=pn(e,a),r=bn(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 _n(e,a){return-23<=e&&e<=23&&(null==a||0<=a&&a<=59)}const Cn={};const kn={X:function(e,a,t){const r=Sn(t.timeZone,e);if(0===r)return"Z";switch(a){case"X":return Dn(r);case"XXXX":case"XX":return En(r);default:return En(r,":")}},x:function(e,a,t){const r=Sn(t.timeZone,e);switch(a){case"x":return Dn(r);case"xxxx":case"xx":return En(r);default:return En(r,":")}},O:function(e,a,t){const r=Sn(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+An(i,2)}(r,":");default:return"GMT"+En(r,":")}},z:function(e,a,t){switch(a){case"z":case"zz":case"zzz":return mn("short",e,t);default:return mn("long",e,t)}}};function Sn(e,a){const t=e?Nn(e,a,!0)/6e4:a?.getTimezoneOffset()??0;if(Number.isNaN(t))throw new RangeError("Invalid time zone specified: "+e);return t}function An(e,a){const t=e<0?"-":"";let r=Math.abs(e).toString();for(;r.length<a;)r="0"+r;return t+r}function En(e,a=""){const t=e>0?"-":"+",r=Math.abs(e);return t+An(Math.floor(r/60),2)+a+An(Math.floor(r%60),2)}function Dn(e,a){if(e%60==0){return(e>0?"-":"+")+An(Math.abs(e)/60,2)}return En(e,a)}function Pn(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 In=36e5,Tn=6e4,Rn={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 Mn(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=Rn.dateTimePattern.exec(e);r?(a.date=r[1],t=r[3]):(r=Rn.datePattern.exec(e),r?(a.date=r[1],t=r[2]):(a.date=null,t=e));if(t){const e=Rn.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=Rn.YYY[a],r=Rn.YYYYY[a];let n=Rn.YYYY.exec(e)||r.exec(e);if(n){const a=n[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(n=Rn.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),s=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=Rn.MM.exec(e);if(i)return t=new Date(0),r=parseInt(i[1],10)-1,Un(a,r)?(t.setUTCFullYear(a,r),t):new Date(NaN);if(i=Rn.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=jn(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=Rn.MMDD.exec(e),i){t=new Date(0),r=parseInt(i[1],10)-1;const e=parseInt(i[2],10);return Un(a,r,e)?(t.setUTCFullYear(a,r,e),t):new Date(NaN)}if(i=Rn.Www.exec(e),i)return n=parseInt(i[1],10)-1,On(n)?Ln(a,n):new Date(NaN);if(i=Rn.WwwD.exec(e),i){n=parseInt(i[1],10)-1;const e=parseInt(i[2],10)-1;return On(n,e)?Ln(a,n,e):new Date(NaN)}return null}(i,n);if(null===s||isNaN(s.getTime()))return new Date(NaN);if(s){const e=s.getTime();let t,n=0;if(r.time&&(n=function(e){let a,t,r=Rn.HH.exec(e);if(r)return a=parseFloat(r[1].replace(",",".")),Bn(a)?a%24*In:NaN;if(r=Rn.HHMM.exec(e),r)return a=parseInt(r[1],10),t=parseFloat(r[2].replace(",",".")),Bn(a,t)?a%24*In+t*Tn:NaN;if(r=Rn.HHMMSS.exec(e),r){a=parseInt(r[1],10),t=parseInt(r[2],10);const e=parseFloat(r[3].replace(",","."));return Bn(a,t,e)?a%24*In+t*Tn+1e3*e:NaN}return null}(r.time),null===n||isNaN(n)))return new Date(NaN);if(r.timeZone||a.timeZone){if(t=Nn(r.timeZone||a.timeZone,new Date(e+n)),isNaN(t))return new Date(NaN)}else t=Pn(new Date(e+n)),t=Pn(new Date(e+n+t));return new Date(e+n+t)}return new Date(NaN)}function Ln(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 zn=[31,28,31,30,31,30,31,31,30,31,30,31],Fn=[31,29,31,30,31,30,31,31,30,31,30,31];function jn(e){return e%400==0||e%4==0&&e%100!=0}function Un(e,a,t){if(a<0||a>11)return!1;if(null!=t){if(t<1)return!1;const r=jn(e);if(r&&t>Fn[a])return!1;if(!r&&t>zn[a])return!1}return!0}function On(e,a){return!(e<0||e>52)&&(null==a||!(a<0||a>6))}function Bn(e,a,t){return!(e<0||e>=25)&&((null==a||!(a<0||a>=60))&&(null==t||!(t<0||t>=60)))}const $n=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function qn(e,a,t,r){return function(e,a,t={}){const r=(a=String(a)).match($n);if(r){const n=Mn(t.originalDate||e,t);a=r.reduce(function(e,a){if("'"===a[0])return e;const r=e.indexOf(a),i="'"===e[r-1],s=e.replace(a,"'"+kn[a[0]](n,a,t)+"'");return i?s.substring(0,r-1)+s.substring(r+1):s},a)}return cn(e,a,t)}(function(e,a,t){const r=Nn(a,e=Mn(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 Vn={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"}},Wn={date:br({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:br({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:br({formats:{full:"{{date}} 'a las' {{time}}",long:"{{date}} 'a las' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Hn={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"},Gn={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"},Kn={code:"es",formatDistance:(e,a,t)=>{let r;const n=Vn[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:Wn,formatRelative:(e,a,t,r)=>1!==a.getHours()?Gn[e]:Hn[e],localize:{ordinalNumber:(e,a)=>Number(e)+"º",era:Nr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","después de cristo"]},defaultWidth:"wide"}),quarter:Nr({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:Nr({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:Nr({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:Nr({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:_r({matchPattern:/^(\d+)(º)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e,10)}}),era:wr({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:wr({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:wr({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:wr({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:wr({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}},Yn={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"}},Qn={date:br({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:br({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:br({formats:{full:"{{date}} 'às' {{time}}",long:"{{date}} 'às' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Xn={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"},Jn={code:"pt-BR",formatDistance:(e,a,t)=>{let r;const n=Yn[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:Qn,formatRelative:(e,a,t,r)=>{const n=Xn[e];return"function"==typeof n?n(a):n},localize:{ordinalNumber:(e,a)=>{const t=Number(e);return"week"===a?.unit?t+"ª":t+"º"},era:Nr({values:{narrow:["AC","DC"],abbreviated:["AC","DC"],wide:["antes de cristo","depois de cristo"]},defaultWidth:"wide"}),quarter:Nr({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:Nr({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:Nr({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:Nr({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:_r({matchPattern:/^(\d+)[ºªo]?/i,parsePattern:/\d+/i,valueCallback:e=>parseInt(e,10)}),era:wr({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:wr({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:wr({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:wr({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:wr({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}},Zn=[{value:"pt-BR",label:"Português (BR)",flag:"🇧🇷"},{value:"en-US",label:"English (US)",flag:"🇺🇸"},{value:"es-ES",label:"Español",flag:"🇪🇸"}],ei=[{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"}],ai=[{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"}],ti="pt-BR",ri="dd/MM/yyyy HH:mm",ni="America/Sao_Paulo",ii=e=>Zn.find(a=>a.value===e),si=e=>ei.find(a=>a.value===e),oi=e=>ai.find(a=>a.value===e),li=e=>Zn.some(a=>a.value===e),di=e=>ei.some(a=>a.value===e),ci=e=>ai.some(a=>a.value===e),ui=()=>{if("undefined"==typeof navigator)return ti;const e=navigator.language;if(li(e))return e;const a=e.split("-")[0],t=Zn.find(e=>e.value.startsWith(a));return t?.value||ti},mi=()=>{if("undefined"==typeof Intl)return ni;try{const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return ci(e)?e:ni}catch{return ni}},pi=e=>({"pt-BR":"dd/MM/yyyy HH:mm","en-US":"MM/dd/yyyy hh:mm a","es-ES":"dd/MM/yyyy HH:mm"}[e]||ri),hi=()=>{const e=ui();return{locale:e,timezone:mi(),datetimeFormat:pi(e)}},fi={"pt-BR":Jn,"en-US":Cr,"es-ES":Kn},gi=(e,a=ri,t=ni,r=ti)=>{if(!e)return"";const n=N(e);if(!w(n))return"Data inválida";const i=fi[r]||Jn;try{return qn(n,t,a,{locale:i})}catch(s){return qn(n,ni,a,{locale:i})}},vi=(e,a=ti,t=ni)=>{if(!e)return"";const r=N(e);if(!w(r))return"Data inválida";const n=fi[a]||Jn;try{return qn(r,t,"PP",{locale:n})}catch(i){return qn(r,ni,"PP",{locale:n})}},bi=(e,a="BRL",t="pt-BR")=>null==e?"":new Intl.NumberFormat(t,{style:"currency",currency:a,minimumFractionDigits:2,maximumFractionDigits:2}).format(e);function xi(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 yi(e,a){return a?e.replace(/\{alias\}/g,a):e}function Ni(...e){return x(b(e))}const wi=e=>{if(null==e)return e;if("string"==typeof e)return e.trim();if(Array.isArray(e))return e.map(wi);if("object"==typeof e&&e.constructor===Object){const a={};for(const[t,r]of Object.entries(e))a[t]=wi(r);return a}return e},_i=(e,a)=>{let t;return(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),a)}},Ci=e=>e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-"),ki=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"}}),Si=n.forwardRef(({className:e,variant:t,size:r,asChild:n=!1,...i},s)=>a(n?g:"button",{className:Ni(ki({variant:t,size:r,className:e})),ref:s,...i}));Si.displayName="Button";const Ai=i.forwardRef(({className:e,children:t,variant:r="action",...n},i)=>a(Si,{ref:i,variant:r,size:"icon",className:Ni("h-8 w-8",e),...n,children:t||a(S,{size:16})}));Ai.displayName="ActionButton";const Ei=n.forwardRef(({className:e,type:r,showCharCount:i,maxLength:s,onChange:o,...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:Ni("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:s,onChange:e=>{u(e.target.value.length),o?.(e)},...l}),i&&s&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[c," / ",s]})]})});Ei.displayName="Input";const Di=v("text-xs font-medium leading-none text-foreground peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Pi=n.forwardRef(({className:e,...t},r)=>a(Na.Root,{ref:r,className:Ni(Di(),e),...t}));Pi.displayName=Na.Root.displayName;const Ii=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));Ii.displayName="Card";const Ti=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("flex flex-col space-y-1.5 p-6",e),...t}));Ti.displayName="CardHeader";const Ri=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Ni("text-2xl font-semibold leading-none tracking-tight",e),...t}));Ri.displayName="CardTitle";const Mi=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Ni("text-sm text-muted-foreground",e),...t}));Mi.displayName="CardDescription";const Li=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("p-6 pt-0",e),...t}));Li.displayName="CardContent";const zi=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("flex items-center p-6 pt-0",e),...t}));zi.displayName="CardFooter";const Fi=n.forwardRef(({className:e,orientation:t="horizontal",decorative:r=!0,...n},i)=>a(_a.Root,{ref:i,decorative:r,orientation:t,className:Ni("shrink-0 bg-border","horizontal"===t?"h-[1px] w-full":"h-full w-[1px]",e),...n}));Fi.displayName=_a.Root.displayName;const ji=Ca.Root,Ui=Ca.Trigger,Oi=Ca.Portal,Bi=n.forwardRef(({className:e,...t},r)=>a(Ca.Overlay,{className:Ni("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}));Bi.displayName=Ca.Overlay.displayName;const $i=n.forwardRef(({className:e,...r},n)=>t(Oi,{children:[a(Bi,{}),a(Ca.Content,{ref:n,className:Ni("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})]}));$i.displayName=Ca.Content.displayName;const qi=({className:e,...t})=>a("div",{className:Ni("flex flex-col space-y-2 text-center sm:text-left",e),...t});qi.displayName="AlertDialogHeader";const Vi=({className:e,...t})=>a("div",{className:Ni("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",e),...t});Vi.displayName="AlertDialogFooter";const Wi=n.forwardRef(({className:e,...t},r)=>a(Ca.Title,{ref:r,className:Ni("text-lg font-semibold",e),...t}));Wi.displayName=Ca.Title.displayName;const Hi=n.forwardRef(({className:e,...t},r)=>a(Ca.Description,{ref:r,className:Ni("text-sm text-muted-foreground",e),...t}));Hi.displayName=Ca.Description.displayName;const Gi=n.forwardRef(({className:e,...t},r)=>a(Ca.Action,{ref:r,className:Ni(ki(),e),...t}));Gi.displayName=Ca.Action.displayName;const Ki=n.forwardRef(({className:e,...t},r)=>a(Ca.Cancel,{ref:r,className:Ni(ki({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));Ki.displayName=Ca.Cancel.displayName;const Yi=wa.Root,Qi=wa.Trigger,Xi=wa.Portal,Ji=wa.Close,Zi=n.forwardRef(({className:e,...t},r)=>a(wa.Overlay,{ref:r,className:Ni("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}));Zi.displayName=wa.Overlay.displayName;const es={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"}},as=n.forwardRef(({className:r,children:i,size:s,variant:o="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),E=n.useRef(!1),D=s??(d||c||u||m||p||h?void 0:"md"),P=D?es[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"===o&&l?(S.current=e,k(!0)):e()},[o,l]),R=n.useRef(null),M="destructive"!==o;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(Xi,{children:[a(Zi,{}),t(wa.Content,{ref:_,className:Ni("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"!==o&&"destructive"!==o?y?.(e):e.preventDefault()},onEscapeKeyDown:e=>{if("destructive"!==o)return"form"===o&&l?(e.preventDefault(),void T(()=>{E.current=!0,R.current?.click()})):void N?.(e);e.preventDefault()},...w,children:[i,M&&t(wa.Close,{ref:R,onClick:e=>{E.current?E.current=!1:"form"===o&&l&&(e.preventDefault(),T(()=>{E.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(A,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]}),a(ji,{open:C,onOpenChange:k,children:t($i,{children:[t(qi,{children:[a(Wi,{children:f}),a(Hi,{children:g})]}),t(Vi,{children:[a(Ki,{onClick:()=>{k(!1),S.current=null},children:v}),a(Gi,{onClick:()=>{k(!1),S.current?.(),S.current=null},children:b})]})]})})]})});as.displayName=wa.Content.displayName;const ts=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Ni("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(Fi,{className:"mt-2"})]});ts.displayName="DialogHeader";const rs=({className:e,...t})=>a("div",{className:Ni("flex-1 min-h-0 overflow-auto py-4 px-2 -mx-2",e),...t});rs.displayName="DialogBody";const ns=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(Fi,{className:"mb-4"}),a("div",{className:Ni("flex flex-row justify-end gap-2",e),...n,children:r})]});ns.displayName="DialogFooter";const is=n.forwardRef(({className:e,...t},r)=>a(wa.Title,{ref:r,className:Ni("text-xl font-semibold leading-none tracking-tight",e),...t}));is.displayName=wa.Title.displayName;const ss=n.forwardRef(({className:e,...t},r)=>a(wa.Description,{ref:r,className:Ni("text-sm text-muted-foreground",e),...t}));ss.displayName=wa.Description.displayName;const os=Sa,ls=n.createContext({}),ds=({...e})=>a(ls.Provider,{value:{name:e.name},children:a(Aa,{...e})}),cs=()=>{const e=n.useContext(ls),a=n.useContext(us),{getFieldState:t,formState:r}=ka(),i=t(e.name,r);if(!e)throw new Error("useFormField should be used within <FormField>");const{id:s}=a;return{id:s,name:e.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...i}},us=n.createContext({}),ms=n.forwardRef(({className:e,...t},r)=>{const i=n.useId();return a(us.Provider,{value:{id:i},children:a("div",{ref:r,className:Ni("space-y-1.5",e),...t})})});ms.displayName="FormItem";const ps=n.forwardRef(({className:e,...t},r)=>{const{error:n,formItemId:i}=cs();return a(Pi,{ref:r,className:Ni(n&&"text-destructive",e),htmlFor:i,...t})});ps.displayName="FormLabel";const hs=n.forwardRef(({...e},t)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:s}=cs();return a(g,{ref:t,id:n,"aria-describedby":r?`${i} ${s}`:`${i}`,"aria-invalid":!!r,...e})});hs.displayName="FormControl";const fs=n.forwardRef(({className:e,...t},r)=>{const{formDescriptionId:n}=cs();return a("p",{ref:r,id:n,className:Ni("text-sm text-muted-foreground",e),...t})});fs.displayName="FormDescription";const gs=n.forwardRef(({className:e,children:t,...r},n)=>{const{error:i,formMessageId:s}=cs(),o=i?String(i?.message):t;return o?a("p",{ref:n,id:s,className:Ni("text-sm font-medium text-destructive",e),...r,children:o}):null});gs.displayName="FormMessage";const vs=Pa.Root,bs=Pa.Group,xs=Pa.Value,ys=n.forwardRef(({className:e,children:r,...n},i)=>t(Pa.Trigger,{ref:i,className:Ni("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(Pa.Icon,{asChild:!0,children:a(E,{className:"h-4 w-4 opacity-50"})})]}));ys.displayName=Pa.Trigger.displayName;const Ns=n.forwardRef(({className:e,...t},r)=>a(Pa.ScrollUpButton,{ref:r,className:Ni("flex cursor-default items-center justify-center py-1",e),...t,children:a(D,{className:"h-4 w-4"})}));Ns.displayName=Pa.ScrollUpButton.displayName;const ws=n.forwardRef(({className:e,...t},r)=>a(Pa.ScrollDownButton,{ref:r,className:Ni("flex cursor-default items-center justify-center py-1",e),...t,children:a(E,{className:"h-4 w-4"})}));ws.displayName=Pa.ScrollDownButton.displayName;const _s=n.forwardRef(({className:e,children:r,position:n="popper",container:i,collisionBoundary:s,...o},l)=>a(Pa.Portal,{container:i,children:t(Pa.Content,{ref:l,className:Ni("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:s,...o,children:[a(Ns,{}),a(Pa.Viewport,{className:Ni("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:r}),a(ws,{})]})}));_s.displayName=Pa.Content.displayName;const Cs=n.forwardRef(({className:e,...t},r)=>a(Pa.Label,{ref:r,className:Ni("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));Cs.displayName=Pa.Label.displayName;const ks=n.forwardRef(({className:e,children:r,...n},i)=>t(Pa.Item,{ref:i,className:Ni("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(Pa.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),a(Pa.ItemText,{children:r})]}));ks.displayName=Pa.Item.displayName;const Ss=n.forwardRef(({className:e,...t},r)=>a(Pa.Separator,{ref:r,className:Ni("-mx-1 my-1 h-px bg-muted",e),...t}));Ss.displayName=Pa.Separator.displayName;const As=n.forwardRef(({className:e,...t},r)=>a(Ia.Root,{ref:r,className:Ni("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(Ia.Indicator,{className:Ni("flex items-center justify-center text-current"),children:a(P,{className:"h-4 w-4"})})}));As.displayName=Ia.Root.displayName;const Es=n.forwardRef(({className:e,showCharCount:r,maxLength:i,onChange:s,...o},l)=>{const[d,c]=n.useState(0);n.useEffect(()=>{"string"==typeof o.value?c(o.value.length):"string"==typeof o.defaultValue&&c(o.defaultValue.length)},[o.value,o.defaultValue]);return t("div",{className:"w-full",children:[a("textarea",{className:Ni("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),s?.(e)},...o}),r&&i&&t("div",{className:"text-right text-xs text-muted-foreground mt-1",children:[d," / ",i]})]})});Es.displayName="Textarea";const Ds=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"}}),Ps=n.forwardRef(({className:e,variant:t,...r},n)=>a("div",{ref:n,className:Ni(Ds({variant:t}),e),...r}));Ps.displayName="Badge";const Is={sm:"h-4 w-4",md:"h-6 w-6",lg:"h-8 w-8"};function Ts({size:e="md",className:t}){return a(I,{className:Ni("animate-spin text-muted-foreground",Is[e],t)})}function Rs({isLoading:e,children:n,className:i,type:s="spinner",size:o="md"}){return e?"overlay"===s?t("div",{className:Ni("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(Ts,{size:o})})]}):a("div","skeleton"===s?{className:Ni("animate-pulse",i),children:a("div",{className:"bg-muted rounded-md h-full w-full"})}:{className:Ni("flex items-center justify-center py-8",i),children:a(Ts,{size:o})}):a(r,{children:n})}const Ms=({...e})=>a(k,{className:"group",position:"top-right",expand:!0,visibleToasts:5,closeButton:!0,icons:{success:a(z,{className:"h-4 w-4"}),info:a(L,{className:"h-4 w-4"}),warning:a(M,{className:"h-4 w-4"}),error:a(R,{className:"h-4 w-4"}),loading:a(T,{className:"h-4 w-4 animate-spin"})},toastOptions:{classNames:{toast:"group toast group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:relative",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",closeButton:"group-[.toast]:absolute group-[.toast]:right-2 group-[.toast]:top-2 group-[.toast]:left-auto group-[.toast]:transform-none group-[.toast]:border-0 group-[.toast]:bg-transparent group-[.toast]:opacity-70 group-[.toast]:hover:opacity-100 group-[.toast]:hover:bg-transparent group-[.toast]:transition-opacity",success:"!bg-success-light !border-success-light",error:"!bg-destructive/10 !border-destructive/10",warning:"!bg-warning-light !border-warning-light",info:"!bg-info-light !border-info-light"}},...e}),Ls=Ta.Root,zs=Ta.Trigger,Fs=Ta.Group,js=Ta.Portal,Us=Ta.Sub,Os=Ta.RadioGroup,Bs=n.forwardRef(({className:e,inset:r,children:n,...i},s)=>t(Ta.SubTrigger,{ref:s,className:Ni("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(F,{className:"ml-auto h-4 w-4"})]}));Bs.displayName=Ta.SubTrigger.displayName;const $s=n.forwardRef(({className:e,...t},r)=>a(Ta.SubContent,{ref:r,className:Ni("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}));$s.displayName=Ta.SubContent.displayName;const qs=n.forwardRef(({className:e,sideOffset:t=4,...r},n)=>a(Ta.Portal,{children:a(Ta.Content,{ref:n,sideOffset:t,className:Ni("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})}));qs.displayName=Ta.Content.displayName;const Vs=n.forwardRef(({className:e,inset:t,...r},n)=>a(Ta.Item,{ref:n,className:Ni("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}));Vs.displayName=Ta.Item.displayName;const Ws=n.forwardRef(({className:e,children:r,checked:n,...i},s)=>t(Ta.CheckboxItem,{ref:s,className:Ni("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(Ta.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),r]}));Ws.displayName=Ta.CheckboxItem.displayName;const Hs=n.forwardRef(({className:e,children:r,...n},i)=>t(Ta.RadioItem,{ref:i,className:Ni("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(Ta.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));Hs.displayName=Ta.RadioItem.displayName;const Gs=n.forwardRef(({className:e,inset:t,...r},n)=>a(Ta.Label,{ref:n,className:Ni("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));Gs.displayName=Ta.Label.displayName;const Ks=n.forwardRef(({className:e,...t},r)=>a(Ta.Separator,{ref:r,className:Ni("-mx-1 my-1 h-px bg-muted",e),...t}));Ks.displayName=Ta.Separator.displayName;const Ys=({className:e,...t})=>a("span",{className:Ni("ml-auto text-xs tracking-widest opacity-60",e),...t});Ys.displayName="DropdownMenuShortcut";const Qs=({delayDuration:e=300,...t})=>a(Ra.Provider,{delayDuration:e,...t}),Xs=Ra.Root,Js=Ra.Trigger,Zs=n.forwardRef(({className:e,sideOffset:t=4,...r},n)=>a(Ra.Content,{ref:n,sideOffset:t,className:Ni("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),...r}));Zs.displayName=Ra.Content.displayName;const eo=n.forwardRef(({children:e,disabledReason:r,className:n},i)=>{const s=a(Vs,{ref:i,className:Ni("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(Qs,{delayDuration:100,children:t(Xs,{children:[a(Js,{asChild:!0,children:a("div",{className:"w-full",children:s})}),a(Zs,{side:"right",sideOffset:8,className:"max-w-[200px] z-[100]",children:r})]})}):s});eo.displayName="DisabledMenuItem";const ao=Ma.Root,to=Ma.Trigger,ro=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,container:n,...i},s)=>a(Ma.Portal,{container:n,children:a(Ma.Content,{ref:s,align:t,sideOffset:r,className:Ni("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})}));ro.displayName=Ma.Content.displayName;const no=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));no.displayName="Command";const io=({children:e,...t})=>a("div",{...t,children:a(no,{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})}),so=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:Ni("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})}));so.displayName="CommandInput";const oo=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));oo.displayName="CommandList";const lo=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("py-6 text-center text-sm text-muted-foreground",e),...t}));lo.displayName="CommandEmpty";const co=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("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}));co.displayName="CommandGroup";const uo=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("-mx-1 h-px bg-border",e),...t}));uo.displayName="CommandSeparator";const mo=n.forwardRef(({className:e,disabled:t,onSelect:r,value:n,...i},s)=>a("div",{ref:s,className:Ni("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}));mo.displayName="CommandItem";const po=({className:e,...t})=>a("span",{className:Ni("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});function ho({className:e,...t}){return a("div",{className:Ni("animate-pulse rounded-md bg-muted",e),...t})}po.displayName="CommandShortcut";const fo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function go({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:_}){const[C,k]=s(!1),[S,D]=s(""),I=o(()=>i?Array.isArray(i)?i:[i]:[],[i]),T=o(()=>{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]),R=o(()=>{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]),M=o(()=>{if(!S)return R;const e=fo(S);return R.filter(a=>fo(a.label).includes(e))},[R,S]),L=o(()=>R.filter(e=>I.includes(e.value)),[R,I]),z=e=>{k(e),e?w?.():(D(""),_?.())},F=(e,a)=>{a.preventDefault(),a.stopPropagation(),l&&l(r?I.filter(a=>a!==e):"")},j=y?L.slice(0,y):L,U=y&&L.length>y?L.length-y:0;return t("div",{className:Ni("space-y-2",b),children:[m&&t(Pi,{children:[m,v&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(ao,{open:C,onOpenChange:z,modal:!1,children:[a(to,{asChild:!0,children:r?t("div",{role:"combobox","aria-expanded":C,"aria-disabled":g,tabIndex:g?-1:0,onKeyDown:e=>{g||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),z(!C))},className:Ni("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===L.length&&"text-muted-foreground"),children:[0===L.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(Ps,{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&&F(e.value,a)},onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:a=>F(e.value,a),children:a(A,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),U>0&&t(Ps,{variant:"outline",className:"gap-1",children:["+",U]})]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]}):t(Si,{variant:"outline",role:"combobox","aria-expanded":C,disabled:g,className:Ni("w-full justify-between min-h-10 h-auto",0===L.length&&"text-muted-foreground"),children:[0===L.length?t("span",{className:"flex items-center gap-2",children:[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"}),L[0]?.label]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),a(ro,{className:"w-full p-0 bg-popover z-[60]",align:"start",container:T,collisionBoundary:T,children:t(no,{children:[t("div",{className:"relative",children:[a(so,{placeholder:f,value:S,onChange:e=>D(e.target.value)}),S&&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:()=>D(""),children:a(A,{className:"h-3.5 w-3.5"})})]}),a(oo,{children:0===n.length?a(lo,{children:h}):0===M.length?a(lo,{children:e.t("no_results")}):a(co,{children:M.map(e=>t(mo,{value:e.value,onSelect:()=>(e=>{if(l)if(r){const a=I.includes(e)?I.filter(a=>a!==e):[...I,e];l(a)}else l(e),k(!1)})(e.value),className:"cursor-pointer",children:[a(P,{className:Ni("mr-2 h-4 w-4",I.includes(e.value)?"opacity-100":"opacity-0")}),e.label]},e.value))})})]})})]})]})}function vo({multiple:e=!1,options:r,items:n,value:i,onChange:s,onValueChange:o,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}){const{t:k}=La(),S=r||n||[],A=o||s,E=c||k("select_placeholder","Selecione..."),D=p||k("no_results",k("no_results")),P=h||k("search_placeholder","Pesquisar...");if(v)return t("div",{className:Ni("space-y-2",x),children:[u&&t(Pi,{children:[u,g&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(ho,{className:"h-10 w-full"})]});const I="string"==typeof b?b:b instanceof Error?b.message:b?k("error_loading",k("error_loading")):void 0;return I?t("div",{className:Ni("space-y-2",x),children:[u&&t(Pi,{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(U,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:I})]})]}):a(go,{multiple:e,options:S,value:i||(e?[]:""),onChange:A,getOptionValue:l,getOptionLabel:d,placeholder:E,label:u,icon:m,emptyMessage:D,searchPlaceholder:P,disabled:f,required:g,className:x,sortOptions:y,maxDisplayedBadges:N,popoverContainer:w,onOpen:_,onClose:C})}const bo=n.forwardRef(({className:e,children:r,...n},i)=>t(ja.Root,{ref:i,className:Ni("relative overflow-hidden",e),...n,children:[a(ja.Viewport,{className:"h-full w-full rounded-[inherit]",children:r}),a(xo,{}),a(ja.Corner,{})]}));bo.displayName=ja.Root.displayName;const xo=n.forwardRef(({className:e,orientation:t="vertical",...r},n)=>a(ja.ScrollAreaScrollbar,{ref:n,orientation:t,className:Ni("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(ja.ScrollAreaThumb,{className:"relative flex-1 rounded-full bg-border"})}));xo.displayName=ja.ScrollAreaScrollbar.displayName;const yo=e=>e.normalize("NFD").replace(/\p{Diacritic}/gu,"").toLowerCase();function No(e,a){if(!a)return null;const t=yo(a),r=[];for(const n of e){const e=yo(n.label).includes(t),i=n.children?No(n.children,a):null,s=i&&i.length>0;(e||s)&&r.push({...n,children:e?n.children:s?i:n.children})}return r}function wo(e,a){for(const t of e){if(t.value===a)return t.label;if(t.children){const e=wo(t.children,a);if(e)return e}}}function _o({node:e,level:r,expanded:n,onToggleExpand:i,selectedValues:s,onSelect:o}){const l=e.children&&e.children.length>0,d=s.includes(e.value);return t("div",{role:"treeitem","aria-expanded":l?n:void 0,"aria-selected":d,className:Ni("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(),o(e.value)},children:[a(P,{className:Ni("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:Ni("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?E:F,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}function Co({nodes:e,level:n,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:d}){return a(r,{children:e.map(e=>{const r=s.has(e.value);return t(i.Fragment,{children:[a(_o,{node:e,level:n,expanded:r,onToggleExpand:o,selectedValues:l,onSelect:d}),r&&e.children&&e.children.length>0&&a(Co,{nodes:e.children,level:n+1,expandedIds:s,onToggleExpand:o,selectedValues:l,onSelect:d})]},e.value)})})}function ko({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}=La(),[k,S]=s(!1),[D,P]=s(""),[I,T]=s(()=>_?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=o(()=>n?Array.isArray(n)?n:[n]:[],[n]),F=o(()=>{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]),j=o(()=>No(r,D),[r,D])??r,B=o(()=>D?function(e,a){const t=new Set,r=yo(a);function n(e){if(!e.children||0===e.children.length)return yo(e.label).includes(r);let a=!1;for(const t of e.children)n(t)&&(a=!0);return a&&t.add(e.value),a||yo(e.label).includes(r)}for(const i of e)n(i);return t}(r,D):new Set,[r,D]),$=D?B:I,q=l(e=>{D||T(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[D]),V=o(()=>z.map(e=>({value:e,label:wo(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?V.slice(0,x):V,Y=x&&V.length>x?V.length-x:0;if(g)return t("div",{className:Ni("space-y-2",b),children:[c&&t(Pi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(ho,{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:Ni("space-y-2",b),children:[c&&t(Pi,{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(U,{className:"h-4 w-4"}),a("span",{className:"text-sm",children:Q})]})]}:{className:Ni("space-y-2",b),children:[c&&t(Pi,{children:[c,f&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(ao,{open:k,onOpenChange:W,modal:!1,children:[a(to,{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:Ni("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===V.length&&"text-muted-foreground"),children:[0===V.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(Ps,{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(A,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},e.value)),Y>0&&t(Ps,{variant:"outline",className:"gap-1",children:["+",Y]})]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]}):t(Si,{variant:"outline",role:"combobox","aria-expanded":k,disabled:h,className:Ni("w-full justify-between min-h-10 h-auto font-normal",0===V.length&&"text-muted-foreground"),children:[0===V.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"}),V[0]?.label]}),a(E,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),t(ro,{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(O,{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:D,onChange:e=>P(e.target.value)}),D&&a("button",{type:"button",className:"rounded-sm p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>P(""),children:a(A,{className:"h-3.5 w-3.5"})})]}),a(bo,{className:"max-h-[300px]",children:a("div",{role:"tree",className:"p-1",children:0===j.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(Co,{nodes:j,level:0,expandedIds:$,onToggleExpand:q,selectedValues:z,onSelect:H})})})]})]})]})}class So{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 s=!0;if(!i){const e="Access token decode falhou - será tentado novamente nas chamadas de API";t.push(e),s=!1}const o=Math.floor(Date.now()/1e3);if(i?.exp&&i.exp<o){const e="Access token expirado - pode precisar de refresh";t.push(e),s=!1}if(n.exp&&n.exp<o){const e="ID token expirado - autenticação inválida";return r.push(e),{isValid:!1,idTokenValid:!1,accessTokenValid:s,warnings:t,errors:r}}return{isValid:!0,idTokenValid:!0,accessTokenValid:s,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()}}So.LARGE_PAYLOAD_THRESHOLD=1e3;const Ao="qualiex_access_token",Eo="qualiex_id_token",Do="supabase_token",Po="oauth_state",Io="oauth_nonce",To="selected_alias",Ro="manual_logout",Mo="supabase_project_id",Lo={setAccessToken:e=>localStorage.setItem(Ao,e),getAccessToken:()=>localStorage.getItem(Ao),setIdToken:e=>localStorage.setItem(Eo,e),getIdToken:()=>localStorage.getItem(Eo),getSupabaseToken:()=>localStorage.getItem(Do),setOAuthState:e=>sessionStorage.setItem(Po,e),getOAuthState:()=>sessionStorage.getItem(Po),clearOAuthState:()=>sessionStorage.removeItem(Po),setOAuthNonce:e=>sessionStorage.setItem(Io,e),getOAuthNonce:()=>sessionStorage.getItem(Io),clearOAuthNonce:()=>sessionStorage.removeItem(Io),setSelectedAlias:e=>localStorage.setItem(To,e),getSelectedAlias:()=>localStorage.getItem(To),clearSelectedAlias:()=>localStorage.removeItem(To),generateOAuthNonce:()=>{const e=new Uint8Array(32);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/[+/=]/g,"")},hasAllTokens:()=>!(!Lo.getAccessToken()||!Lo.getIdToken()),checkProjectMismatch:()=>{const e=import.meta.env.VITE_SUPABASE_PROJECT_ID;if(!e)return!1;const a=localStorage.getItem(Mo);return a&&a!==e?(Lo.clearAll(),localStorage.setItem(Mo,e),!0):(a||localStorage.setItem(Mo,e),!1)},setSupabaseToken:e=>{localStorage.setItem(Do,e),Lo._clearValidationCache()},areAllTokensValid:()=>{const e=Lo.getAccessToken(),a=Lo.getIdToken();if(!e||!a)return!1;try{const t=So.validateTokens(e,a);return!!t.idTokenValid&&t.idTokenValid}catch(t){return!1}},clearExpiredTokens:()=>{let e=!1;const a=Lo.getAccessToken(),t=Lo.getIdToken(),r=Lo.getSupabaseToken();return a&&Lo.isTokenExpired(a)&&(localStorage.removeItem(Ao),e=!0),t&&Lo.isTokenExpired(t)&&(localStorage.removeItem(Eo),e=!0),r&&Lo.isTokenExpired(r)&&(localStorage.removeItem(Do),e=!0),e},clearAll:()=>{localStorage.removeItem(Ao),localStorage.removeItem(Eo),localStorage.removeItem(Do),localStorage.removeItem(To),localStorage.removeItem(Ro),sessionStorage.removeItem(Po),sessionStorage.removeItem(Io),Lo._clearValidationCache()},setManualLogout:()=>localStorage.setItem(Ro,"true"),isManualLogout:()=>"true"===localStorage.getItem(Ro),clearManualLogout:()=>localStorage.removeItem(Ro),isTokenExpired:e=>{try{return So.isTokenExpired(e)}catch{return!0}},_validationCache:{isValid:!1,timestamp:0,cacheValidityMs:3e5},_clearValidationCache:()=>{Lo._validationCache.isValid=!1,Lo._validationCache.timestamp=0},isSupabaseTokenValid:()=>{const e=Lo.getSupabaseToken();if(!e)return!1;if(Lo.isTokenExpired(e))return Lo._clearValidationCache(),Lo._handleExpiredToken(),!1;const a=Date.now();return a-Lo._validationCache.timestamp<Lo._validationCache.cacheValidityMs?Lo._validationCache.isValid:(Lo._validationCache.isValid=!0,Lo._validationCache.timestamp=a,!0)},getValidSupabaseToken:()=>Lo.isSupabaseTokenValid()?Lo.getSupabaseToken():null,_handleExpiredToken:()=>{Lo.clearAll()},extractTokenData:()=>{if(!Lo.isSupabaseTokenValid())return null;const e=Lo.getSupabaseToken();if(!e)return null;try{const a=So.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 Lo._handleExpiredToken(),null}},getCompanyId:e=>{const a=Lo.getAccessToken();if(a)try{const t=So.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=Lo.extractTokenData();if(t?.companyId)return t.companyId;const r=Lo.getIdToken();if(r)try{const a=So.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=[Lo.getAccessToken(),Lo.getIdToken()];for(const t of a)if(t)try{const a=So.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=Lo.extractTokenData();return e?.companyId||null},getAllCompaniesData:()=>{const e=Lo.getIdToken();if(!e)return[];try{const a=So.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 zo=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=[]}},Fo=import.meta.env.VITE_SUPABASE_URL,jo=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;class Uo{constructor(){this.currentToken=null,this.client=this.createClientWithToken(null)}createClientWithToken(e){const a={apikey:jo};e&&this.isTokenValid(e)&&(a.Authorization=`Bearer ${e}`);return Ua(Fo,jo,{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 Uo.instance||(Uo.instance=new Uo),Uo.instance}getClient(){const e=Lo.getValidSupabaseToken();return e!==this.currentToken&&(this.client=this.createClientWithToken(e),this.currentToken=e),this.client}isTokenValid(e){try{return!So.isTokenExpired(e)}catch(a){return zo.handleError(a instanceof Error?a:"Supabase - Error validating token",!1),!1}}}function Oo(){return Uo.getInstance().getClient()}class Bo{static async generateToken(e,a,t,r=!1){try{if(!r){const e=Lo.getSupabaseToken();if(e&&Lo.isSupabaseTokenValid())return e}const n=Oo(),{data:i,error:s}=await n.functions.invoke("validate-token",{body:{access_token:e,alias:a}});return s&&(s.message?.includes("401")||s.message?.includes("Unauthorized"))?(t?.(),null):i?.access_token?(Lo.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 $o{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=Lo.getAccessToken(),t=Lo.getSelectedAlias();if(!a||!t)return null;const r=await Bo.generateToken(a,t,this.onLogoutCallback||void 0,e);return r||null}catch(a){return null}}}$o.regenerationPromise=null,$o.onLogoutCallback=null;class qo{static handleError(e){if(!e)return!1;const a=e.message||e.toString();return!!this.isAuthenticationError(e,a)&&(Lo.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 Vo{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 $o.attemptRegeneration()?(this.isRetrying=!1,!0):(qo.handleError(e),this.isRetrying=!1,!1)}catch(r){return qo.handleError(e),this.isRetrying=!1,!1}}return!1}static validateToken(){const e=Lo.getAccessToken();return e?Lo.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."}}}Vo.isRetrying=!1;const Wo=new class{get baseUrl(){return or()}async makeApiCall(e,a,t){const r=Vo.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Lo.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status} ${s.statusText}`);throw e.status=s.status,e.statusCode=s.status,e}return await s.json()}mapToQualiexUser(e){return{id:e.id||e.ID||"",userId:e.userId||String(e.ID),userName:e.userName||"Nome não disponível",userEmail:e.userEmail||"Email não disponível",placeId:null,placeName:e.placeName||null,roleId:e.roleId||void 0,roleName:e.roleName||void 0,companyId:e.companyId||void 0,companyName:e.companyName||void 0}}parseUsersResponse(e,a=""){let t=e;if(e.data)t=e.data;else{if(!Array.isArray(e))return zo.handleError(`[QualiexApi] Formato de resposta inesperado${a}`,!1),null;t=e}return Array.isArray(t)?t.map(this.mapToQualiexUser):(zo.handleError(`[QualiexApi] Resposta não é um array${a}`,!1),null)}async fetchUsers(e,a){const t={companyId:a,search:"",filterStatus:"active"};try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a)??[]}catch(r){if(await Vo.handleApiError(r))try{const a=await this.makeApiCall("/api/common/v1/companiesusers",t,e);return this.parseUsersResponse(a," após retry")??[]}catch(n){return zo.handleError(n instanceof Error?n:"Erro ao buscar usuários após renovação de token",!0),[]}return zo.handleError(r instanceof Error?r.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 zo.handleError(r instanceof Error?r:"[QualiexApi] Error fetching user by ID"),null}}async fetchActiveUsersMap(e,a){const t=await this.fetchUsers(e,a),r=new Map;return t.forEach(e=>r.set(e.userId,e)),r}async getUsers(e){const a=Lo.extractTokenData();return a&&a.companyId?this.fetchUsers(e,a.companyId):[]}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||""})):(zo.handleError("[QualiexApi] fetchSoftwares: formato de resposta inesperado",!1),[])}catch(a){if(await Vo.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 zo.handleError(t instanceof Error?t:"Erro ao buscar softwares após renovação de token",!0),[]}return zo.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})):(zo.handleError("[QualiexApi] fetchUserAssociations: formato de resposta inesperado",!1),[])}catch(t){if(await Vo.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 zo.handleError(r instanceof Error?r:"Erro ao buscar associações após renovação de token",!0),[]}return zo.handleError(t instanceof Error?t.message:"Erro ao buscar associações do usuário",!0),[]}}};function Ho(e,a){const t=a||dr.userNameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Go(e,a){const t=a||dr.userEmailFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Ko(e,a){const t=a||dr.userUsernameFieldSuffix;return e.endsWith("_id")?e.replace(/_id$/,t):`${e}${t}`}function Yo(e,a){return a&&a.length>0?a.map(e=>({idField:e.idField,nameField:e.nameField||Ho(e.idField),emailField:e.emailField||Go(e.idField),usernameField:e.usernameField||Ko(e.idField)})):e&&e.length>0?e.map(e=>({idField:e,nameField:Ho(e),emailField:Go(e),usernameField:Ko(e)})):[{idField:"id_user",nameField:"responsible_name"}]}const Qo=new Map;class Xo{static async fetchQualiexUsers(e,a){const t=`${a}_${e}`,r=Qo.get(t);if(r&&Date.now()-r.timestamp<3e5)return r.users;const n=await Wo.fetchUsers(e,a);return Qo.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(!Lo.areAllTokensValid())return e;const t=Lo.extractTokenData();if(!t)return e;const{alias:r,companyId:n}=t;if(!r||!n)return e;const i=Yo(a.userIdFields,a.userFieldsMapping);if(0===this.extractUserIds(e,i).size)return e;const s=await this.fetchQualiexUsers(r,n),o=this.indexUsers(s);return e.map(e=>this.enrichEntity(e,i,o))}catch(t){return zo.handleError(t instanceof Error?t:new Error(`[QualiexEnrichment.${a.entityName}] Erro crítico`),!1),e}}}const Jo=["responsible_name"],Zo=e=>Jo.includes(e);function el(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:s,schemaName:o,entityName:l,enableQualiexEnrichment:d=!1}=r,c=()=>{if(!Lo.getValidSupabaseToken())throw new Error("Token de autenticação expirado. Faça login novamente.");return Oo().schema(o).from(n)},u=(e,a,t,r)=>{let n=c().select(s||"*",{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 o=a.includes(".");return o||Zo(a)||(n=n.order(a,{ascending:"asc"===t})),{query:n,isForeignKey:o}},m=async(e,a,t,n,i)=>{const s=Yo(r.userIdFields,r.userFieldsMapping).some(e=>e.nameField===a||e.emailField===a||e.usernameField===a),o=a.includes(".");if(Zo(a)||o||s){const e={search:"",sortField:void 0,sortDirection:void 0,page:1,limit:500},s=await p.getAll(e);if(!s?.data?.length)return s;const d=await Xo.enrichWithUserData(s.data,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping});let c;c=o?d.sort((e,r)=>{const n=a.split(".").reduce((e,a)=>e?.[a],e)||"",i=a.split(".").reduce((e,a)=>e?.[a],r)||"",s=String(n).localeCompare(String(i),"pt-BR");return"asc"===t?s:-s}):((e,a,t)=>[...e].sort((e,r)=>{const n=e[a]||"",i=r[a]||"",s=n.localeCompare(i,"pt-BR",{sensitivity:"base"});return"asc"===t?s:-s}))(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 Xo.enrichWithUserData(e,{entityName:l,userIdFields:r.userIdFields,userFieldsMapping:r.userFieldsMapping})},p={async getAll(e={}){const{search:a,sortField:t,sortDirection:i,page:s,limit:o,additionalFilters:c}=(e=>{const{search:a="",sortField:t="updated_at",sortDirection:r="desc",page:n=1,limit:i=25,...s}=e;return{search:a,sortField:t,sortDirection:r,page:n,limit:i,additionalFilters:s}})(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,s,o),{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,s,o);if((e=>{if(!d||!l||0===e.length)return!1;const a=Yo(r.userIdFields,r.userFieldsMapping);return e.some(e=>a.some(a=>e[a.idField]))})(b.data)){const e=await m(b.data,t,i,s,o);if(!Array.isArray(e))return e;b={...b,data:e}}return b},async getById(e){const{data:a,error:t}=await c().select(s||"*").eq("id",e).maybeSingle();if(t)throw new Error(`Error fetching ${n}: ${t.message}`);return a},async create(e){const a=wi(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={...wi(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 al;const tl={isAuthenticated:!1,isLoading:!1,user:null,alias:null,companies:[],selectedUnit:null,userId:null,userAlias:null,placeId:null,placeName:null,activePlaceId:null,activePlaceName:null};class rl{static async initialize(){try{if(Lo.checkProjectMismatch())return{...tl};if(!Lo.hasAllTokens()||!Lo.areAllTokensValid())return Lo.clearExpiredTokens(),{...tl};const e=Lo.getAccessToken(),a=Lo.getIdToken();Lo.clearManualLogout();const t=this.extractUserFromIdToken(a,e),r=this.extractCompaniesFromIdToken(a),n=this.extractAliasFromAccessToken(e),i=Lo.extractTokenData(),s=i?.alias;let o=null;if(s&&r.some(e=>e.alias===s))o=s;else{const e=Lo.getSelectedAlias(),a=e&&r.some(a=>a.alias===e);o=a?e:n||r[0]?.alias||null}if(!Lo.isSupabaseTokenValid()&&o&&await $o.attemptRegeneration(),!Lo.isSupabaseTokenValid())return{...tl};let l=null;if(o){const e=Lo.getCompanyId(o),a=r.find(e=>e.alias===o);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:o,companies:r,selectedUnit:l,userId:t?.id||null,userAlias:t?.id||null,placeId:d,placeName:c,activePlaceId:d,activePlaceName:c}}catch(e){return{...tl}}}static async loginDev(){try{const e=Oo(),{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==";Lo.setOAuthState(e);const a=Lo.generateOAuthNonce();Lo.setOAuthNonce(a);const t=`${window.location.origin}/callback`,r=new URL(ar.oauth.authUrl);r.searchParams.set("client_id",ar.oauth.clientId),r.searchParams.set("response_type",ar.oauth.responseType),r.searchParams.set("scope",ar.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=Lo.getAccessToken();e!==r&&Lo.clearAll()}if(Lo.hasAllTokens()){return Lo.getValidSupabaseToken()||await $o.attemptRegeneration(!0),!0}const s=r,o=n;if(!s||!o)throw new Error("Tokens não encontrados na URL de callback");Lo.setAccessToken(s),Lo.setIdToken(o),Lo.clearManualLogout();const l=this.extractAliasFromAccessToken(s);if(l)Lo.setSelectedAlias(l);else{const e=this.extractCompaniesFromIdToken(o);if(0===e.length)throw new Error("Nenhuma empresa encontrada nos tokens");Lo.setSelectedAlias(e[0].alias)}if(!await $o.attemptRegeneration(!0))throw new Error("Falha ao gerar token Supabase");return Lo.clearOAuthState(),Lo.clearOAuthNonce(),!0}catch(e){throw e}}static async logout(){Lo.setManualLogout(),Lo.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 So.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}}al=rl,$o.setLogoutCallback(()=>{al.logout()});const nl=e=>e?.placeId||null,il=e=>e?.placeName||null,sl=d(void 0),ol=({children:e})=>{const[t,r]=s({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=Oa()}catch{}const[i,d]=s(!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=Lo.getAccessToken();if(!i)return;const s=await Bo.generateToken(i,e.alias,void 0,!0);if(c.current!==a)return;if(!s)return;Lo.setSupabaseToken(s),Lo.setSelectedAlias(e.alias);const o=Lo.extractTokenData(),l=o?.alias||e.alias,d=o?.companyId||Lo.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 Wo.fetchActiveUsersMap(l,d);if(c.current!==a)return;const r=e.get(t.user.id);if(r){const e=(e=>({placeId:nl(e),placeName:il(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 rl.processCallback();if(e){const e=await rl.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 rl.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(Lo.areAllTokensValid()){if(!Lo.isSupabaseTokenValid())try{await $o.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 rl.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&&(qo.handleError(a),h(!1))}})(),()=>{e=!1}},[p,h,b]);const w=o(()=>({...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(sl.Provider,{value:w,children:e})},ll=()=>{const e=c(sl);if(void 0===e)throw new Error("useAuth deve ser usado dentro de um AuthProvider");return e};function dl({queryKey:e,service:a,entityName:t,searchFields:r,additionalFilters:n={},onSuccess:i}){const[d,c]=Wa(),u=Oa(),{alias:m,userId:p,isAuthenticated:h}=ll(),{t:f}=La(),g=l(a=>{const t=`${e}_${a}`,r=d.get(t);return r||(d.get(a)||"")},[d,e]),v=g("search"),b=g("sortField")||tr.sorting.defaultField,x=g("sortDirection")||tr.sorting.defaultDirection,y=parseInt(g("page")||"1"),N=parseInt(g("limit")||String(tr.pagination.defaultPageSize)),w=v,_=o(()=>({search:w,sortField:b,sortDirection:x,page:y,limit:N,...n}),[w,b,x,y,N,n]),k=l(()=>a.getAll(_),[a,_]),S=Ba({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=$a({mutationFn:a.create,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(ur.success.created(t)),i?.()},onError:e=>{C.error(`${ur.error.create(t)}: ${e.message}`)}}),E=$a({mutationFn:({id:e,data:t})=>a.update(e,t),onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(ur.success.updated(t)),i?.()},onError:e=>{C.error(`${ur.error.update(t)}: ${e.message}`)}}),D=$a({mutationFn:a.delete,onSuccess:()=>{u.invalidateQueries({queryKey:[e]}),C.success(ur.success.deleted(t))},onError:e=>{C.error(`${ur.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]=s([]),j=l(e=>{F(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),U=l(()=>{const e=S?.data?.data.map(e=>e.id)||[];F(a=>a.length===e.length?[]:e)},[S?.data?.data]),O=l(()=>{F([])},[]),B=o(()=>{const e=S?.data?.data.map(e=>e.id)||[];return e.length>0&&z.length===e.length},[z,S?.data?.data]),$=$a({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}`))}}),q=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||tr.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:q,handleSearch:I,handleSort:T,handlePageChange:R,handleItemsPerPageChange:M,clearFilters:L,refetch:S.refetch,selectedIds:z,selectItem:j,selectAll:U,clearSelection:O,isAllSelected:B,bulkDelete:e=>$.mutateAsync(e),isBulkDeleting:$.isPending}}function cl(e){const a=el({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)=>dl({queryKey:e.tableName,service:a,entityName:e.entityName,additionalFilters:t,onSuccess:r})}}function ul(e){const[a,t]=s(()=>"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 ml(e=768){return ul(`(max-width: ${e-1}px)`)}const pl=n.forwardRef(({className:e,...t},r)=>a("table",{ref:r,className:Ni("w-full caption-bottom text-[13px] table-fixed",e),...t}));pl.displayName="Table";const hl=n.forwardRef(({className:e,...t},r)=>a("thead",{ref:r,className:Ni("[&_tr]:border-b sticky top-0 z-[1] bg-background",e),...t}));hl.displayName="TableHeader";const fl=n.forwardRef(({className:e,...t},r)=>a("tbody",{ref:r,className:Ni("[&_tr:last-child]:border-0",e),...t}));fl.displayName="TableBody";const gl=n.forwardRef(({className:e,...t},r)=>a("tfoot",{ref:r,className:Ni("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));gl.displayName="TableFooter";const vl=n.forwardRef(({className:e,...t},r)=>a("tr",{ref:r,className:Ni("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted even:bg-table-stripe",e),...t}));vl.displayName="TableRow";const bl=n.forwardRef(({className:e,...t},r)=>a("th",{ref:r,className:Ni("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}));bl.displayName="TableHead";const xl=n.forwardRef(({className:e,...t},r)=>a("td",{ref:r,className:Ni("px-4 py-2 align-middle overflow-hidden [&:has([role=checkbox])]:pr-0",e),...t}));xl.displayName="TableCell";const yl=n.forwardRef(({className:e,...t},r)=>a("caption",{ref:r,className:Ni("mt-4 text-sm text-muted-foreground",e),...t}));function Nl({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(ho,{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(ho,{className:"h-4 w-20"},t))})},t))})]})})}function wl({count:e=3}){return a("div",{className:"space-y-4",children:Array.from({length:e}).map((e,r)=>t(Ii,{children:[t(Ti,{children:[a(ho,{className:"h-4 w-3/4"}),a(ho,{className:"h-3 w-1/2"})]}),a(Li,{children:t("div",{className:"space-y-2",children:[a(ho,{className:"h-3 w-full"}),a(ho,{className:"h-3 w-2/3"})]})})]},r))})}function _l({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(ho,{className:"h-4 w-24"}),a(ho,{className:"h-10 w-full"})]},r)),t("div",{className:"flex justify-end space-x-2 pt-4",children:[a(ho,{className:"h-10 w-20"}),a(ho,{className:"h-10 w-20"})]})]})}function Cl(){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(ho,{className:"h-8 w-8 rounded-full"}),a(ho,{className:"h-6 w-32"})]}),t("div",{className:"flex items-center space-x-2",children:[a(ho,{className:"h-8 w-8"}),a(ho,{className:"h-8 w-24"})]})]})}function kl(){return a("div",{className:"w-64 border-r bg-muted/10",children:t("div",{className:"p-4",children:[a(ho,{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(ho,{className:"h-4 w-4"}),a(ho,{className:"h-4 w-20"})]},r))})]})})}yl.displayName="TableCaption";const Sl={default:B,search:O,error:U};function Al({icon:e,title:r,description:n,action:i,className:s,variant:o="default"}){const{t:l}=La(),d=!!e,c=Sl[o];return t("div",{className:Ni("flex flex-col items-center justify-center py-12 px-4 text-center",s),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(Si,{onClick:i.onClick,variant:"outline",children:i.label})]})}function El({children:e,className:r}){const i=n.useRef(null),[s,o]=n.useState(!1);n.useEffect(()=>{const e=()=>{const e=i.current;e&&o(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 s?a(Qs,{delayDuration:300,children:t(Xs,{children:[a(Js,{asChild:!0,children:l}),a(Zs,{side:"top",className:"max-w-[400px] break-words",children:e})]})}):l}const Dl=n.forwardRef(({direction:e,onMouseDown:t,isDragging:r,className:n},i)=>{const s="horizontal"===e;return a("div",{ref:i,onMouseDown:t,className:Ni("absolute z-20 select-none touch-none","transition-colors duration-150",s&&["top-0 right-0 h-full w-2 -mr-1","cursor-col-resize","hover:bg-primary/20","group flex items-center justify-center"],!s&&["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:Ni("rounded-full bg-border transition-colors group-hover:bg-primary",r&&"bg-primary",s?"h-6 w-0.5":"w-6 h-0.5")})})});Dl.displayName="TableResizeHandle";const Pl=Xa.Root,Il=Xa.Trigger,Tl=Xa.Group,Rl=Xa.Portal,Ml=Xa.Sub,Ll=Xa.RadioGroup,zl=n.forwardRef(({className:e,inset:r,children:n,...i},s)=>t(Xa.SubTrigger,{ref:s,className:Ni("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(F,{className:"ml-auto h-4 w-4"})]}));zl.displayName=Xa.SubTrigger.displayName;const Fl=n.forwardRef(({className:e,...t},r)=>a(Xa.SubContent,{ref:r,className:Ni("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}));Fl.displayName=Xa.SubContent.displayName;const jl=n.forwardRef(({className:e,...t},r)=>a(Xa.Portal,{children:a(Xa.Content,{ref:r,className:Ni("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})}));jl.displayName=Xa.Content.displayName;const Ul=n.forwardRef(({className:e,inset:t,...r},n)=>a(Xa.Item,{ref:n,className:Ni("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}));Ul.displayName=Xa.Item.displayName;const Ol=n.forwardRef(({className:e,children:r,checked:n,...i},s)=>t(Xa.CheckboxItem,{ref:s,className:Ni("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(Xa.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),r]}));Ol.displayName=Xa.CheckboxItem.displayName;const Bl=n.forwardRef(({className:e,children:r,...n},i)=>t(Xa.RadioItem,{ref:i,className:Ni("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(Xa.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));Bl.displayName=Xa.RadioItem.displayName;const $l=n.forwardRef(({className:e,inset:t,...r},n)=>a(Xa.Label,{ref:n,className:Ni("px-2 py-1.5 text-sm font-semibold text-foreground",t&&"pl-8",e),...r}));$l.displayName=Xa.Label.displayName;const ql=n.forwardRef(({className:e,...t},r)=>a(Xa.Separator,{ref:r,className:Ni("-mx-1 my-1 h-px bg-border",e),...t}));ql.displayName=Xa.Separator.displayName;const Vl=({className:e,...t})=>a("span",{className:Ni("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});Vl.displayName="ContextMenuShortcut";const Wl=({onEdit:e,onDelete:n,onToggleStatus:i,isActive:s=!0,canDelete:o=!0,customActions:l=[],renderAs:d})=>{const{t:c}=La(),u=[];if(e){const a={icon:$,label:c("edit"),onClick:e};u.push(a)}if(l.forEach(e=>{u.push(e)}),i){const e={icon:s?q:V,label:s?"Inativar":"Ativar",onClick:i};u.push(e)}if(o&&n){const e={icon:W,label:c("ap_delete"),onClick:n,destructive:!0};u.push(e)}const m="dropdown"===d?Vs:Ul;return a(r,{children:u.map((e,r)=>t(m,{onClick:e.onClick,className:Ni("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))})},Hl=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>t(Ls,{children:[a(zs,{asChild:!0,children:a(Si,{variant:"action",size:"sm",className:"h-7 px-2 text-xs",children:a(S,{size:12})})}),a(qs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[160px]",children:a(Wl,{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:s,canDelete:n&&!!r,customActions:o,renderAs:"dropdown"})})]}),Gl=({onEdit:e,onDelete:r,canDelete:n=!0,onToggleStatus:i,isActive:s=!0,customActions:o=[]})=>{const{t:l}=La();return a(Qs,{delayDuration:200,children:t("div",{className:"flex items-center justify-end gap-0.5",children:[e&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e()},children:a(H,{size:14})})}),a(Zs,{children:l("edit")})]}),o.map((e,r)=>{const n=e.icon;return t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a=>{a.stopPropagation(),e.onClick()},children:a(n,{size:14})})}),a(Zs,{children:e.label})]},r)}),i&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:e=>{e.stopPropagation(),i()},children:a(s?G:K,{size:14})})}),a(Zs,{children:s?"Inativar":"Ativar"})]}),r&&n&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:Ni("h-7 w-7 hover:text-destructive"),onClick:e=>{e.stopPropagation(),r()},children:a(W,{size:14})})}),a(Zs,{children:l("ap_delete")})]})]})})},Kl=150;function Yl({columns:e,storageKey:a,onResize:t,enabled:r=!0}){const[n,i]=s(()=>{if(!r||"undefined"==typeof window)return e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Kl,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??Kl,e),{})}),[o,d]=s(!1),[c,p]=s(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]??Kl)},[r,n]);m(()=>{if(!o||!c)return;const r=e.find(e=>e.key===c),n=r?.minWidth??60,s=r?.maxWidth??500,l=e=>{const a=e.clientX-h.current,r=Math.max(n,Math.min(s,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)}},[o,c,e,a,t]),m(()=>(o?(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=""}),[o]);const v=l(()=>{const r=e.reduce((e,a)=>(e[a.key]=a.defaultWidth??Kl,e),{});i(r),a&&localStorage.removeItem(a),t?.(r)},[e,a,t]);return{columnWidths:n,isDragging:o,activeColumn:c,handleMouseDown:g,resetWidths:v}}const Ql=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"}}),Xl=n.forwardRef(({className:e,variant:t,size:r,...n},i)=>a(Za.Root,{ref:i,className:Ni(Ql({variant:t,size:r,className:e})),...n}));Xl.displayName=Za.Root.displayName;const Jl=n.createContext({size:"default",variant:"default"}),Zl=n.forwardRef(({className:e,variant:t,size:r,children:n,...i},s)=>a(Ja.Root,{ref:s,className:Ni("flex items-center justify-center gap-1",e),...i,children:a(Jl.Provider,{value:{variant:t,size:r},children:n})}));Zl.displayName=Ja.Root.displayName;const ed=n.forwardRef(({className:e,children:t,variant:r,size:i,...s},o)=>{const l=n.useContext(Jl);return a(Ja.Item,{ref:o,className:Ni(Ql({variant:l.variant||r,size:l.size||i}),e),...s,children:t})});ed.displayName=Ja.Item.displayName;const ad=p(function({onNew:e,newButtonLabel:r,showNewButton:n=!0,showSearch:i=!1,searchValue:s="",onSearchChange:o,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}=La(),_=c>0,C=e&&n||h.length>0,k=f||b||y,S=i&&o;return C||S||k||d&&_?t("div",{className:Ni("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(Si,{onClick:e,children:[a(Y,{size:16,className:"mr-2"}),r||"Novo"]}),h.map((e,r)=>{const n=e.icon;return t(Si,{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(Ps,{variant:"secondary",className:"mr-1 tabular-nums",children:c}),t(Qs,{delayDuration:200,children:[u.length>0?u.map((e,r)=>{const n=e.icon,i=e.disabled;return t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:Ni("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(Zs,{children:e.label})]},r)}):t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:m,children:a(W,{size:16})})}),a(Zs,{children:w("ap_delete")})]}),t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:p,children:a(A,{size:16})})}),a(Zs,{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(O,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Ei,{type:"text",placeholder:l||"Pesquisar",value:s,onChange:e=>o?.(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(Zl,{type:"single",value:g,onValueChange:e=>e&&v(e),size:"sm",children:x.map(e=>{const t=(e=>{switch(e){case"table":return J;case"list":return X;case"grid":return Q}})(e);return a(ed,{value:e,"aria-label":"Visualizar como "+("table"===e?"tabela":"list"===e?"lista":"grade"),children:a(t,{className:"h-4 w-4"})},e)})}),y]})]}):null}),td=p(({checked:e,onCheckedChange:t})=>a(As,{checked:e,onCheckedChange:t}),(e,a)=>e.checked===a.checked);function rd(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=o(()=>e.map(e=>String(e.key)),[e]),i=o(()=>new Set(r??[]),[r]),[d,c]=s(()=>{if(!t)return i;if(!a)return i;const e=rd(a);return e?.hiddenColumns??i}),[u,p]=s(()=>{if(!t||!a)return n;const e=rd(a)?.columnOrder;return e&&e.length>0?e:n}),[h,f]=s(()=>t&&a?rd(a)?.groupByColumns??[]:[]),[g,v]=s(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=o(()=>{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,...s]=t,o=new Map;for(const l of a){const e=String(l[i]??"(vazio)");o.has(e)||o.set(e,[]),o.get(e).push(l)}return Array.from(o.entries()).map(([a,t])=>{const o=n?`${n}|${i}:${a}`:`${i}:${a}`,l=s.length>0?e(t,s,r+1,o):void 0;return{groupKey:o,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 id({enabled:e=!1,onReorder:a}){const[t,r]=s(null),[n,i]=s(null),d=l(()=>{r(null),i(null)},[]),c=l((n,s)=>({draggable:e,onDragStart:a=>{e&&(r(n),a.dataTransfer.effectAllowed="copyMove",a.dataTransfer.setData("text/plain",String(n)),s&&a.dataTransfer.setData("application/column-key",s))},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 o(()=>({dragFromIndex:t,dragOverIndex:n,isDragging:null!==t,getDragProps:c}),[t,n,c])}function sd({columns:e,columnOrder:r,isColumnHidden:n,toggleColumn:i,showAllColumns:o,reorderColumns:l,groupByColumn:d,setGroupByColumn:c,groupByColumns:m=[],addGroupByColumn:p,removeGroupByColumn:h,resetColumns:f}){const{t:g}=La(),[v,b]=s(null),[x,y]=s(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(ao,{children:[a(to,{asChild:!0,children:a(Si,{variant:"outline",size:"icon",className:"h-8 w-8",children:a(Z,{size:16})})}),t(ro,{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(Qs,{delayDuration:300,children:_.map((e,r)=>{const s=String(e.key),o=n(s),u=!1!==e.hideable,f=!0===e.groupable,w=m.includes(s)||d===s;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:Ni("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(ee,{size:14,className:"text-muted-foreground shrink-0"}),a(As,{checked:!o,onCheckedChange:()=>u&&i(s),disabled:!u,className:"shrink-0"}),a("span",{className:Ni("flex-1 truncate",o&&"text-muted-foreground"),children:e.header}),f&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:Ni("h-6 w-6 shrink-0",w&&"text-primary bg-primary/10"),onClick:e=>{e.stopPropagation(),w?h?h(s):c?.(null):p?p(s):c?.(s)},children:a(ae,{size:14})})}),a(Zs,{children:g(w?"remove_grouping":"group_by_column")})]})]},s)})})}),t("div",{className:"border-t px-3 py-2 space-y-1",children:[a(Si,{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))):o,children:g(k?"deselect_all":"select_all_columns")}),f&&a(Si,{variant:"ghost",size:"sm",className:"w-full text-xs font-normal justify-start",onClick:f,children:"Redefinir padrão"})]})]})]})}function od({columns:e,groupByColumns:r,addGroupByColumn:n,removeGroupByColumn:o,reorderGroupByColumns:l}){const[d,c]=s(!1),[u,m]=s(null),[p,h]=s(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:Ni("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(ae,{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 s=u===r,d=p===r&&u!==r;return t(i.Fragment,{children:[r>0&&a("span",{className:"text-xs text-muted-foreground",children:"›"}),t(Ps,{variant:"secondary",className:Ni("cursor-grab active:cursor-grabbing gap-1 pr-1 select-none",s&&"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(),o(e)},className:"ml-0.5 rounded-full p-0.5 hover:bg-muted-foreground/20 transition-colors",children:a(A,{size:12})})]})]},e)}):a("span",{className:"text-xs",children:"Arraste um cabeçalho de coluna aqui para agrupar"})})]})}const ld=({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:D=[],onBulkDelete:P,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M=!1,enableColumnResize:L=!0,resizeStorageKey:z,enableColumnManager:j=!0,columnManagerStorageKey:U,defaultHiddenColumns:O,enableGrouping:B=!1,enableExpandableRows:$=!1,renderExpandedContent:q,expandedRowIds:V,onToggleExpand:W,defaultExpandAll:H=!1,hideActionsColumn:G=!1})=>{const{t:K}=La(),{setSearchVisible:Y}=ll(),Q=ml(),[X,J]=s(()=>H&&$?new Set(r.entities.map(e=>e.id)):new Set),Z=void 0!==V,ee=Z?new Set(V):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]),ne=void 0!==w?!w:_;m(()=>{if(!C)return Y(!0),()=>Y(!1)},[Y,C]);const ie=nd({columns:n,storageKey:U,enabled:j,defaultHiddenColumns:O}),se=id({enabled:j,onReorder:ie.reorderColumns}),oe=j?ie.visibleColumns:n,{columnWidths:le,isDragging:de,activeColumn:ce,handleMouseDown:ue}=Yl({columns:oe.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=o(()=>(()=>{if(L)return oe.map(e=>{const a=le[String(e.key)]??e.width??e.minWidth??150;return{...e,calculatedWidth:a,style:{width:`${a}px`}}});let e=0;const a=oe.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`}})})(),[oe,L,le]),pe=b||N.length>0||C||g||I||M||j,he=ne&&pe,fe=P||(()=>{r.bulkDelete?.(r.selectedIds)}),ge=e=>a(xl,{className:"text-center",children:h?h(e):"inline"===v?a("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity duration-150",children:a(Gl,{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(Hl,{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(jl,{className:"w-[160px]",children:a(Wl,{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=j?a(sd,{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(wl,{count:3}):0===r.entities.length?a(Al,{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(ad,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:D,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(Pl,{children:[a(Il,{asChild:!0,children:a(Ii,{className:Ni("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(Li,{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(td,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),t("div",{className:"flex-1",children:[oe.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(Hl,{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)+oe.length+(G?0:1),we=e=>{const n=$&&ee.has(e.id);return t(i.Fragment,{children:[t(Pl,{children:[a(Il,{asChild:!0,children:t(vl,{className:Ni("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(xl,{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?E:F,{size:16,className:"text-muted-foreground"})})}),g&&a(xl,{onClick:e=>e.stopPropagation(),children:a(td,{checked:r.selectedIds.includes(e.id),onCheckedChange:()=>r.selectItem(e.id)})}),oe.map(t=>a(xl,{className:t.className,children:a(El,{children:t.render?t.render(e):String(e[t.key]??"")})},String(t.key))),!G&&ge(e)]})}),ve(e)]}),n&&q&&a(vl,{className:"bg-muted/30 hover:bg-muted/30",children:a(xl,{colSpan:Ne,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:q(e)})})})]},e.id)},_e=(e,r)=>{const{t:n}=La();return e.map(e=>{const n=ie.collapsedGroups.has(e.groupKey),s=16*e.level,o=Math.max(30,70-15*e.level);return t(i.Fragment,{children:[a(vl,{className:Ni("hover:bg-muted cursor-pointer"),style:{backgroundColor:`hsl(var(--muted) / ${o}%)`},onClick:()=>ie.toggleGroupCollapse(e.groupKey),children:a(xl,{colSpan:r,className:"py-2 px-4",children:t("div",{className:"flex items-center gap-2 font-medium text-sm",style:{paddingLeft:`${s}px`},children:[a(n?F:E,{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(ad,{onNew:b,newButtonLabel:x,showNewButton:y,showSearch:C,searchValue:k,onSearchChange:S,searchPlaceholder:A,showBulkActions:g,selectedCount:r.selectedIds.length,bulkActions:D,onBulkDelete:fe,onClearSelection:r.clearSelection,customActions:N,filters:I,viewMode:T,onViewModeChange:R,showViewToggle:M}),r.isLoading?a(Nl,{rows:5,columns:oe.length}):t("div",{className:"flex flex-col h-full overflow-hidden",children:[B&&a(od,{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-auto",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(hl,{children:t(vl,{children:[$&&a(bl,{className:"w-[40px]"}),g&&a(bl,{className:"w-[50px]",children:a(td,{checked:r.isAllSelected,onCheckedChange:r.selectAll})}),oe.map((e,n)=>{const i=L&&!1!==e.resizable,s=ce===String(e.key),o=j?se.getDragProps(n,String(e.key)):{},l=se.dragFromIndex===n,d=se.dragOverIndex===n&&se.dragFromIndex!==n;return t(bl,{className:Ni(e.className,!1!==e.sortable&&"hover:bg-muted/50 cursor-pointer","relative transition-opacity",j&&se.isDragging&&"cursor-grabbing",l&&"opacity-50",d&&"border-l-2 border-primary"),onClick:!1!==e.sortable?()=>r.handleSort(String(e.key)):void 0,...o,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(te,{size:14,className:"ml-1"}):a(re,{size:14,className:"ml-1"}))]}),i&&a(Dl,{direction:"horizontal",onMouseDown:a=>ue(String(e.key),a),isDragging:s})]},String(e.key));var c}),!G&&a(bl,{className:"w-[50px] text-center",children:be||e.t("actions")})]})}),a(fl,{children:0===r.entities.length?a(vl,{children:a(xl,{colSpan:Ne,className:"h-32",children:a(Al,{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 dd(e,a,t,r){const[n,i]=s({}),[l,d]=s({}),c=o(()=>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),s={};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);s[e.name]=t}),n.forEach(e=>{const a=h(e,s);void 0!==a&&(s[e.name]=a)}),a&&Object.keys(a).forEach(e=>{n.find(a=>a.name===e)||void 0===a[e]||(s[e]=a[e])}),i(s),d({}),t&&t(s)},[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 cd=["#3b82f6","#ef4444","#10b981","#f59e0b","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6b7280"],ud=({value:e="#3b82f6",onChange:r,label:n,customColorLabel:i,presetColorsLabel:s})=>{const{t:o}=La(),l=i??o("custom_color"),d=s??o("preset_colors");return t("div",{className:"space-y-2",children:[n&&a(Pi,{children:n}),t(ao,{children:[a(to,{asChild:!0,children:t(Si,{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(ro,{className:"w-64",children:t("div",{className:"space-y-3",children:[t("div",{children:[a(Pi,{htmlFor:"color-input",children:l}),a(Ei,{id:"color-input",type:"color",value:e,onChange:e=>r?.(e.target.value),className:"h-10 w-full"})]}),t("div",{children:[a(Pi,{children:d}),a("div",{className:"grid grid-cols-5 gap-2 mt-2",children:cd.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))})]})]})})]})]})},md=[{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 pd({name:e,filled:t,className:r}){return a("span",{className:`material-symbols-outlined ${r??""}`,style:t?{fontVariationSettings:"'FILL' 1"}:void 0,children:e})}const hd=({value:e=null,onChange:r,label:n,noIconLabel:i="SEM ÍCONE"})=>{const[o,l]=s(!1),d=e=>{r?.(e),l(!1)};return t("div",{className:"space-y-2",children:[n&&a(Pi,{children:n}),t(ao,{open:o,onOpenChange:l,children:[a(to,{asChild:!0,children:t(Si,{variant:"outline",className:"justify-start text-left font-normal gap-2",children:[e?a(pd,{name:e.name,filled:e.filled,className:"text-xl text-muted-foreground"}):a("span",{className:"text-muted-foreground text-sm",children:i}),a(E,{className:"ml-auto h-4 w-4 opacity-50"})]})}),a(ro,{className:"w-72 p-3",align:"start",children:t("div",{className:"space-y-3",children:[a(bo,{className:"h-64",children:a("div",{className:"grid grid-cols-7 gap-1",children:md.map(t=>a("button",{type:"button",className:"flex items-center justify-center p-1.5 rounded hover:bg-accent transition-colors "+(e?.name===t.name?"bg-primary/10 text-primary":"text-muted-foreground"),onClick:()=>d(t),title:t.name,children:a(pd,{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:()=>d(null),children:i})]})})]})]})},fd=n.forwardRef(({className:e,...t},r)=>a(et.Root,{className:Ni("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(et.Thumb,{className:Ni("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")})}));fd.displayName=et.Root.displayName;const gd=(e={})=>{const{user:a,alias:t}=ll(),{enabled:r=!0}=e;return Ba({queryKey:["qualiex-users",t],queryFn:()=>Wo.getUsers(t),enabled:r&&!!t&&!!a,staleTime:3e5,retry:2,retryDelay:1e3})},vd=({value:t,onChange:r,multiple:n=!1,label:i,required:s,placeholder:d,icon:c,maxDisplayedBadges:u,className:m,disabled:p,enabled:h,displayFormat:f="name",customDisplayFn:g,filterFn:v,sortOptions:b=!0,popoverContainer:x,onOpen:y,onClose:N})=>{const{t:w}=La(),{data:_=[],isLoading:C,error:k}=gd({enabled:h}),S=o(()=>v?_.filter(v):_,[_,v]),A=o(()=>{const a=t?Array.isArray(t)?t:[t]:[];if(0===a.length)return S;const r=new Set(S.map(e=>e.userId||e.id||"")),n=a.filter(e=>e&&!r.has(e));if(0===n.length)return S;const i=n.map(a=>({userId:a,id:a,userName:e.t("inactive_user"),userEmail:""}));return[...S,...i]},[S,t]),E=l(e=>{if("custom"===f&&g)return g(e);const a=e.userName||"";switch(f){case"name-email":return e.userEmail?`${a} (${e.userEmail})`:a;case"name-role":return e.roleName?`${a} - ${e.roleName}`:a;default:return a}},[f,g]);return a(vo,{multiple:n,value:t??(n?[]:""),onChange:r,options:A,isLoading:C,error:k,getOptionValue:e=>e.userId||e.id||"",getOptionLabel:E,placeholder:d||"Pesquisar...",searchPlaceholder:"Pesquisar...",emptyMessage:w("no_results"),label:i,required:s,icon:c,maxDisplayedBadges:u,disabled:p,className:m,sortOptions:b,popoverContainer:x,onOpen:y,onClose:N})};function bd({title:e,sections:r,initialData:n,onSubmit:d,onCancel:c,open:m,submitButtonText:p,isLoading:h=!1,usersData:f}){const[g,v]=s(r?.[0]?.id||""),b=u(null),[x,y]=s(null),N=l(e=>{b.current=e,y(e)},[]),w=o(()=>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}=dd(w,n,void 0,m),A=o(()=>r&&Array.isArray(r)?r.map(e=>({...e,disabled:e.condition?!e.condition(_):e.disabled||!1})):[],[r,_]),E=o(()=>{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,s=r?`flex gap-3 w-full ${e.className||""}`:"space-y-3",o=r?Ni("space-y-2 w-full",e.wrapperClassName):Ni("space-y-2",e.className,e.wrapperClassName);return t("div",{className:o,children:[e.label,a("div",{className:s,children:e.fields?.map(e=>P(e))})]},e.name);case"user-select":return t("div",{className:`space-y-2 ${e.className||""}`,children:[t(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(vd,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Es,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),t(vs,{value:String(n),onValueChange:a=>{k(e.name,a),e.onValueChange&&e.onValueChange(a)},disabled:e.disabled,children:[a(ys,{className:`${i?"border-destructive":""} ${e.disabled?"bg-muted cursor-not-allowed":""}`,children:a(xs,{placeholder:e.placeholder})}),a(_s,{children:e.options?.map(e=>a(ks,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(vo,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ei,{id:e.name,type:"date",value:String(n),onChange:a=>k(e.name,a.target.value),placeholder:e.placeholder,disabled:e.disabled,className:Ni("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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ei,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(ud,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(hd,{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(Pi,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ei,{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(As,{id:e.name,checked:!!n,onCheckedChange:a=>k(e.name,a),disabled:e.disabled}),t(Pi,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(fd,{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(Pi,{htmlFor:e.name,children:[e.label,e.required&&a("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ei,{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(Si,{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(Si,{type:"button",variant:"outline",onClick:c,children:"Cancelar"}),a(Si,{type:"submit",disabled:h,children:p||"Salvar"})]})]})})]});return a(Yi,{open:m,onOpenChange:e=>{!1===e&&!0===m&&c()},children:t(as,{ref:N,variant:"form",className:"max-w-4xl max-h-[90vh] overflow-visible",children:[t(ts,{showSeparator:!0,children:[a(is,{children:e}),a(ss,{className:"sr-only",children:"Formulário para preenchimento de dados"})]}),T]})})}function xd({currentPage:e,totalPages:n,totalItems:i,itemsPerPage:s,onPageChange:o,onItemsPerPageChange:l,variant:d="full"}){const{t:c}=La();if(0===i)return null;const u=(e-1)*s+1,m=Math.min(e*s,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(vs,{value:String(s),onValueChange:e=>l(Number(e)),children:[a(ys,{className:"h-8 w-[70px]",children:a(xs,{})}),t(_s,{children:[a(ks,{value:"10",children:"10"}),a(ks,{value:"25",children:"25"}),a(ks,{value:"50",children:"50"}),a(ks,{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(Si,{variant:"outline",size:"sm",onClick:()=>o(1),disabled:1===e,className:"h-8 w-8 p-0",children:a(ne,{size:16})}),a(Si,{variant:"outline",size:"sm",onClick:()=>o(e-1),disabled:1===e,className:"h-8 w-8 p-0",children:a(ie,{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(Si,{variant:"outline",size:"sm",onClick:()=>o(e+1),disabled:e===n,className:"h-8 w-8 p-0",children:a(F,{size:16})}),a(Si,{variant:"outline",size:"sm",onClick:()=>o(n),disabled:e===n,className:"h-8 w-8 p-0",children:a(se,{size:16})})]})]})}function yd({manager:e}){return a(xd,{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 Nd={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"},wd={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 Cd({children:e,direction:t="column",gap:r="md",align:n="stretch",justify:i="start",wrap:s=!1,className:o}){return a("div",{className:Ni("flex","column"===t?"flex-col":"flex-row",Nd[r],wd[n],_d[i],s&&"flex-wrap",o),children:e})}function kd({manager:e,filters:n,inline:i=!1}){const{t:s}=La(),{isSearchVisible:o}=ll(),l=e.searchTerm,d=t(r,{children:[n.some(e=>"search"===e.type)&&!o&&t("div",{className:"relative flex-1",children:[a(O,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(Ei,{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(vs,{value:e.value||"",onValueChange:a=>e.onChange?.(a),children:[a(ys,{className:"w-[180px]",children:a(xs,{placeholder:e.placeholder})}),a(_s,{children:e.options.map(e=>a(ks,{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(Si,{variant:"outline",onClick:e.clearFilters,className:"whitespace-nowrap",children:[a(A,{className:"h-4 w-4 mr-2"}),"Limpar"]})]});return i?a("div",{className:"flex items-center gap-2",children:d}):a(Cd,{direction:"column",gap:"md",className:"mb-6",children:a(Cd,{direction:"row",gap:"md",wrap:!0,className:"flex-col sm:flex-row",children:d})})}function Sd({manager:e,config:r,formSections:n,onSave:i,onToggleStatus:o,defaultSort:l}){e&&e.queryKey;const{setSearchVisible:d}=ll(),[c,u]=Wa(),[p,h]=s(!1),[f,g]=s(null),[v,b]=s({isOpen:!1,entityId:null,entityName:""}),[x,y]=s({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(ad,{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(kd,{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(ld,{manager:e,columns:r.columns,onEdit:N,onDelete:w,onToggleStatus:o,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(yd,{manager:e})}),!r.useCustomRouting&&!r.onNew&&n.length>0&&a(bd,{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(Yi,{open:v.isOpen,onOpenChange:_,children:t(as,{size:"sm",variant:"destructive",children:[a(ts,{showSeparator:!0,children:a(is,{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(ns,{children:[a(Si,{variant:"outline",onClick:_,children:"Cancelar"}),a(Si,{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(Yi,{open:x.isOpen,onOpenChange:()=>y({isOpen:!1,count:0}),children:t(as,{size:"sm",variant:"destructive",children:[a(ts,{showSeparator:!0,children:a(is,{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(ns,{children:[a(Si,{variant:"outline",onClick:()=>y({isOpen:!1,count:0}),children:"Cancelar"}),a(Si,{variant:"destructive",onClick:()=>{e.bulkDelete?.(e.selectedIds),y({isOpen:!1,count:0})},disabled:e.isBulkDeleting,children:e.isBulkDeleting?"Excluindo...":"Sim, excluir"})]})]})})]})}function Ad(e){return({manager:t})=>{const{manager:r,config:n,onSave:i,onEdit:s,onToggleStatus:o}=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:s||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(Sd,{manager:l,config:d,formSections:n.formSections,onSave:i,onToggleStatus:o,defaultSort:n.defaultSort})}}function Ed(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 Dd(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:Id(e),label:Id(e),...Pd(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 Pd(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 Id(e){return e.replace(/([A-Z])/g," $1").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Td=({children:n})=>{const{isAuthenticated:s,isLoading:o}=ll();if(i.useEffect(()=>{if(o)return;if(s)return;if(Lo.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=ir(),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 rl.loginDev():rl.loginProd()})()},[s,o]),o&&!s)return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ii,{className:"w-full max-w-md",children:[a(Ti,{className:"text-center",children:a(Ri,{className:"text-xl font-semibold",children:"Carregando..."})}),t(Li,{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(!s){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(Ii,{className:"w-full max-w-md",children:[a(Ti,{className:"text-center",children:a(Ri,{className:"text-xl font-semibold",children:"Processando..."})}),t(Li,{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(Ii,{className:"w-full max-w-md",children:[a(Ti,{className:"text-center",children:a(Ri,{className:"text-xl font-semibold",children:"Iniciando..."})}),t(Li,{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:ir()?e.t("auto_login"):e.t("redirecting_auth")})]})]})})}return a(r,{children:n})};function Rd(e={}){const{paramName:a="alias"}=e,t=Ha(),{alias:r,companies:n}=ll(),i=t[a]||null;return o(()=>{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 Md({children:e,paramName:n="alias"}){const i=Ga(),o=Ka(),d=Ha(),{alias:c,isAuthenticated:p,isLoading:h,switchUnit:f}=ll(),{urlAlias:g,isAliasMismatch:v,isValidAlias:b,isMissing:x,matchedCompany:y}=Rd({paramName:n}),[N,w]=s(!1),_=u(!1),C=n in d,k=l(e=>{const a=d[n],{pathname:t,search:r,hash:i}=o;if(a){const n=t.split("/"),s=n.findIndex(e=>e===a);if(s>=0)return n[s]=e,n.join("/")+r+i}return`/${e}${"/"===t?"":t}${r}${i}`},[d,n,o]);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(Ts,{size:"lg"}),a("p",{className:"text-sm text-muted-foreground",children:"Trocando unidade..."})]})}):a(r,{children:e})}function Ld(){const{alias:e}=ll(),{pathname:t,search:r,hash:n}=Ka();return e?a(Ya,{to:`/${e}${t}${r}${n}`,replace:!0}):null}const zd=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"}}),Fd={info:de,warning:de,danger:le,success:oe},jd=n.forwardRef(({className:e,variant:r="info",showIcon:n=!0,children:i,...s},o)=>{const l=Fd[r||"info"];return t("div",{ref:o,role:"alert",className:Ni(zd({variant:r}),e),...s,children:[n&&a(l,{className:"h-4 w-4"}),i]})});jd.displayName="Alert";const Ud=n.forwardRef(({className:e,...t},r)=>a("h5",{ref:r,className:Ni("mb-1 font-medium leading-none tracking-tight",e),...t}));Ud.displayName="AlertTitle";const Od=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("text-sm [&_p]:leading-relaxed",e),...t}));Od.displayName="AlertDescription";const Bd=()=>{const{processCallback:e}=ll(),n=Ga(),[i,o]=s(null),[l,d]=s(!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 o("Falha na autenticação. Tente novamente.")}catch(a){localStorage.removeItem("auth_return_url"),o(a?.message||"Erro durante a autenticação. Tente novamente.")}})()},[e,n]);const c=async()=>{d(!0),o(null);try{await e()||o("Falha na autenticação. Tente novamente.")}catch(a){o(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(Ii,{className:"w-full max-w-md",children:[a(Ti,{className:"text-center",children:t(Ri,{className:"text-xl font-semibold text-destructive flex items-center justify-center gap-2",children:[a(U,{className:"h-5 w-5"}),"Erro na Autenticação"]})}),t(Li,{className:"space-y-4",children:[a(jd,{variant:"danger",children:a(Od,{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(Si,{onClick:c,disabled:l,className:"flex-1",children:t(r,l?{children:[a(Ts,{size:"sm",className:"mr-2"}),"Tentando..."]}:{children:[a(ce,{className:"h-4 w-4 mr-2"}),"Tentar Novamente"]})}),a(Si,{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(Ii,{className:"w-full max-w-md",children:[a(Ti,{className:"text-center",children:a(Ri,{className:"text-xl font-semibold",children:"Processando Autenticação"})}),t(Li,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(Ts,{size:"lg"})}),a("p",{className:"text-muted-foreground",children:"Processando tokens e redirecionando..."})]})]})})},$d=()=>{const{t:e}=La();return a("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 to-secondary/5",children:t(Ii,{className:"w-full max-w-md",children:[a(Ti,{className:"text-center",children:a(Ri,{className:"text-2xl font-bold",children:"Acesso ao Sistema"})}),t(Li,{className:"text-center space-y-4",children:[a("p",{className:"text-muted-foreground",children:"Faça login para acessar o sistema"}),a(Si,{onClick:async()=>{ir()?await rl.loginDev():rl.loginProd()},className:"w-full",size:"lg",children:ir()?e("dev_login"):e("login_with_qualiex")})]})]})})},qd=d(void 0);function Vd({children:e,actions:t}){const{t:r}=La(),[n,i]=s({}),[d,c]=s(t);m(()=>{c(t)},[t]);const u=l(()=>i({}),[]),p=o(()=>({metadata:n,setMetadata:i,clearMetadata:u,headerActions:d,setHeaderActions:c}),[n,u,d]);return a(qd.Provider,{value:p,children:e})}function Wd(){const e=c(qd);if(!e)throw new Error("usePageMetadataContext must be used within PageMetadataProvider");return e}function Hd(e){const{setMetadata:a,clearMetadata:t}=Wd(),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 Gd(e){return{queryClient:e.queryClient||new qa({defaultOptions:{queries:{retry:1,refetchOnWindowFocus:!1}}}),config:e}}var Kd={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_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",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..."},Yd={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_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",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..."},Qd={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_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",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 Xd="true"===import.meta.env.VITE_I18N_DEBUG_MODE;function Jd(a,t){e.addResourceBundle(a,"app",t,!0,!0)}Xd&&e.use({type:"postProcessor",name:"debugKeys",process:(e,a)=>`🔑 ${Array.isArray(a)?a[0]:a}`}),e.use(za).init({resources:{"pt-BR":{core:Kd},"en-US":{core:Yd},"es-ES":{core:Qd}},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:Xd?["debugKeys"]:[]});const Zd=d(void 0),ec={locale:ti,timezone:ni,datetimeFormat:ri},ac=async()=>{},tc=({children:e})=>a(Zd.Provider,{value:{...ec,setLocale:ac,setTimezone:ac,setDatetimeFormat:ac,isLoading:!1},children:e}),rc=()=>{const e=c(Zd);if(!e)throw new Error("useLocale deve ser usado dentro de LocaleProvider");return e},nc=d({moduleAlias:null});function ic({moduleAlias:e=null,children:t}){return a(nc.Provider,{value:{moduleAlias:e},children:t})}function sc(){return c(nc)}const oc=at.Root,lc=at.CollapsibleTrigger,dc=at.CollapsibleContent;class cc extends h{constructor(a){super(a),this.copyErrorDetails=()=>{const a=zo.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;zo.handleError(e,!1),this.setState({errorInfo:a})}render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const r=zo.getErrors().slice(0,2);return a("div",{className:"flex items-center justify-center min-h-screen p-4",children:t(Ii,{className:"w-full max-w-2xl",children:[t(Ti,{className:"text-center",children:[a("div",{className:"flex justify-center mb-4",children:a(le,{className:"h-12 w-12 text-destructive"})}),a(Ri,{children:e.t("something_went_wrong")})]}),t(Li,{className:"space-y-4",children:[a("p",{className:"text-center text-muted-foreground",children:"Ocorreu um erro inesperado. Tente recarregar a página."}),t(oc,{open:this.state.showDetails,onOpenChange:e=>this.setState({showDetails:e}),children:[a(lc,{asChild:!0,children:t(Si,{variant:"outline",className:"w-full flex items-center justify-center gap-2",children:[a(E,{className:"h-4 w-4 transition-transform "+(this.state.showDetails?"rotate-180":"")}),"Ver Detalhes Técnicos"]})}),t(dc,{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(bo,{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(Si,{variant:"outline",onClick:this.copyErrorDetails,className:"w-full flex items-center justify-center gap-2",children:[a(ue,{className:"h-4 w-4"}),"Copiar Detalhes"]})]})]}),a(Si,{onClick:()=>window.location.reload(),className:"w-full",children:"Recarregar Página"})]})]})})}return this.props.children}}const uc=tt.Root,mc=n.forwardRef(({className:e,...t},r)=>a(tt.List,{ref:r,className:Ni("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),...t}));mc.displayName=tt.List.displayName;const pc=n.forwardRef(({className:e,...t},r)=>a(tt.Trigger,{ref:r,className:Ni("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}));pc.displayName=tt.Trigger.displayName;const hc=n.forwardRef(({className:e,...t},r)=>a(tt.Content,{ref:r,className:Ni("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 fc({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 gc({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"})]})}function vc({educaUrl:e="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:r="https://sabergestao.com.br/",wikiUrl:n,alias:i}){const{t:s}=La(),o=yi(e||n||"https://educacao.sabergestao.com.br/{alias}/fe",i);return t("div",{className:"flex-shrink-0 pt-4",children:[a(Fi,{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:o,target:"_blank",rel:"noopener noreferrer",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(me,{className:"h-3.5 w-3.5"})]})]}),a(fc,{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",className:"inline-flex items-center gap-1 text-sm text-primary underline underline-offset-2 hover:opacity-80 mt-2",children:["Saiba mais",a(me,{className:"h-3.5 w-3.5"})]})]}),a(gc,{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",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(me,{className:"h-3.5 w-3.5"})]})]}),a(pe,{className:"absolute right-2 top-2 bottom-2 h-[calc(100%-1rem)] w-auto text-[#E0E0E0] pointer-events-none",strokeWidth:1})]})]})]})}hc.displayName=tt.Content.displayName;const bc=[{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 xc({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:Ni("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 yc(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 Nc({modules:e,onModuleClick:r,contractedModules:n,onModuleInterest:i}){const o=function(){const[e,a]=s(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=yc(c,o),h=yc(u,o),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(xc,{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(xc,{module:e,onClick:()=>f(e,!1)},e.name))})]})]})}function wc({onModuleClick:e,contractedModules:r,onModuleInterest:n,nonContractedUrl:i="https://qualiex.com/",educaUrl:o="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:l="https://sabergestao.com.br/",wikiUrl:d,alias:c}){const[u,m]=s("qualiex"),p=a=>{e?.(a)},h=e=>{window.open(i,"_blank","noopener,noreferrer"),n?.(e)};return t("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[t(uc,{value:u,onValueChange:m,className:"flex-1 flex flex-col min-h-0",children:[a(mc,{className:"w-fit shrink-0",children:bc.map(e=>t(pc,{value:e.id,children:[e.label,t("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",e.modules.length,")"]})]},e.id))}),bc.map(e=>a(hc,{value:e.id,className:"flex-1 mt-4 overflow-auto pr-2",children:a(Nc,{modules:e.modules,onModuleClick:p,contractedModules:"qualiex"===e.id?r:void 0,onModuleInterest:h})},e.id))]}),a(vc,{educaUrl:o,saberGestaoUrl:l,wikiUrl:d,alias:c})]})}const _c={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},Cc=6e5;function kc(e){const{moduleAlias:a}=sc(),{alias:t,user:r,isAuthenticated:n}=ll(),i=e??a,s=r?.id??null,d=n&&!!t&&!!s,{data:c=[],isLoading:u}=Ba({queryKey:["qualiex-associations",s,t],queryFn:()=>Wo.fetchUserAssociations(s,t),enabled:d,staleTime:Cc,gcTime:12e5}),m=o(()=>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=_c[e];return void 0!==a&&m.softwares.includes(a)})},[m]);return{hasAccess:o(()=>!i||p(i),[i,p]),isLoading:d&&u,role:o(()=>m?{id:m.roleId,name:m.roleName}:null,[m]),association:m,hasAccessTo:p}}function Sc(e){const{association:a}=kc();return o(()=>{if(e)return e;if(!a?.softwares)return;const t=a.softwares,r=bc.find(e=>"qualiex"===e.id);return r?r.modules.filter(e=>{if(!e.softwareAlias)return!1;const a=_c[e.softwareAlias];return void 0!==a&&t.includes(a)}).map(e=>e.name):void 0},[e,a])}function Ac({open:e,onOpenChange:r,onModuleClick:n,contractedModules:i,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:d}){const{alias:c}=ll(),u=Sc(i);return a(Yi,{open:e,onOpenChange:r,children:t(as,{size:"lg",className:"overflow-hidden flex flex-col",children:[a(ts,{className:"sr-only",children:a(is,{children:"Módulos"})}),a(wc,{onModuleClick:e=>{n?n(e):e.url&&xi(yi(e.url,c||void 0))},contractedModules:u,onModuleInterest:s,educaUrl:o,saberGestaoUrl:l,wikiUrl:d,alias:c||void 0})]})})}function Ec({open:r,onOpenChange:n,onModuleClick:i,contractedModules:s,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}){const{t:N}=La(),w=o(()=>{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(Yi,{open:r,onOpenChange:b?void 0:n,children:t(as,{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(is,{children:N("no_access_page")}),a(ss,{children:"Selecione um módulo para continuar navegando!"})]}),t("div",{className:"flex items-center gap-2 shrink-0",children:[w.length>1&&t(Ls,{children:[a(zs,{asChild:!0,children:t(Si,{variant:"outline",size:"sm",className:"gap-2 max-w-[200px]",children:[a(he,{className:"h-4 w-4 shrink-0"}),a("span",{className:"truncate text-xs",children:c||"Unidade"}),a(E,{className:"h-3 w-3 shrink-0"})]})}),a(qs,{align:"end",className:"max-h-[300px] overflow-auto",children:w.map(e=>t(Vs,{onClick:()=>p?.(e),className:e.alias===m?"bg-muted":"",children:[a(he,{className:"mr-2 h-4 w-4 shrink-0"}),a("span",{className:"truncate",children:e.name}),e.alias===m&&a(Ps,{variant:"outline",className:"ml-auto text-xs shrink-0",children:"Atual"})]},e.alias))})]}),t(Ls,{children:[a(zs,{asChild:!0,children:t(Si,{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(fe,{className:"h-3.5 w-3.5 text-primary-foreground"})}),a(E,{className:"h-3 w-3"})]})}),t(qs,{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(Ks,{}),t(Vs,{onClick:h,children:[a(ge,{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(vc,{educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m})]}):a(wc,{onModuleClick:i,contractedModules:s,onModuleInterest:l,educaUrl:f,saberGestaoUrl:g,wikiUrl:v,alias:m})]})})}function Dc(e,a){const{t:t}=La();return a.some(a=>a.endsWith("*")?e.startsWith(a.slice(0,-1)):e===a)}function Pc({children:e,contractedModules:t,onModuleClick:n,onModuleInterest:i,educaUrl:s="https://educacao.sabergestao.com.br/{alias}/fe",saberGestaoUrl:d="https://sabergestao.com.br/",wikiUrl:c,bypassPaths:u,accessDeniedRoutes:m}){const{t:p}=La(),{hasAccess:h,isLoading:f,association:g}=kc(),{user:v,alias:b,companies:x,isAuthenticated:y,isLoading:N,logout:w,switchUnit:_}=ll(),C=Sc(t),k=o(()=>x?.length?b&&x.find(e=>e.alias===b)||x[0]:null,[x,b]),S=o(()=>x?.length?x.map(e=>({alias:e.alias,name:e.name||e.alias})):[],[x]),A=l(e=>{const a=x?.find(a=>a.alias===e.alias);if(!a)return;const{pathname:t,search:r,hash:n}=window.location;if(b){const e=t.split("/"),i=e.indexOf(b);if(i>=0)return e[i]=a.alias,void(window.location.href=e.join("/")+r+n)}_(a)},[b,_,x]),E=l(e=>{n?n(e):e.url&&xi(yi(e.url,b||void 0))},[n,b]),D=o(()=>{if(!m)return;const e=window.location.pathname,a=Object.keys(m).find(a=>Dc(e,[a]));return a?m[a]:void 0},[m]);return N||!y||u?.length&&Dc(window.location.pathname,u)?a(r,{children:e}):f?a("div",{className:"flex items-center justify-center min-h-screen",children:a(Ts,{size:"lg"})}):h?a(r,{children:e}):a(Ec,{open:!0,onModuleClick:E,contractedModules:C,onModuleInterest:i,userName:v?.name,unitName:k?.name,units:S,currentAlias:b||void 0,onUnitChange:A,onLogout:w,educaUrl:s,saberGestaoUrl:d,wikiUrl:c,blocking:!0,children:D})}function Ic({title:e,description:r,image:n,icon:i,ctaLabel:s,onCtaClick:o,children:l}){const{t:d}=La(),c=s??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}):o?t(Si,{onClick:o,size:"lg",className:"gap-2",children:[a(ve,{className:"h-4 w-4"}),c]}):null]})}let Tc=!1;function Rc(){if(Tc||"undefined"==typeof document)return;Tc=!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 Mc({children:t,queryClient:r,moduleAlias:n,moduleAccessGuardProps:s,appTranslations:o}){Rc();const[l]=i.useState(()=>new qa({defaultOptions:{queries:{staleTime:3e5,retry:1}}})),d=r??l;return i.useEffect(()=>{if(o)for(const[e,a]of Object.entries(o))Jd(e,a)},[o]),a(cc,{children:a(Fa,{i18n:e,children:a(Va,{client:d,children:a(ol,{children:a(tc,{children:a(ic,{moduleAlias:n,children:a(Pc,{...s,children:t})})})})})})})}const Lc=rt.Root,zc=n.forwardRef(({className:e,...t},r)=>a(rt.Item,{ref:r,className:Ni("border-b",e),...t}));zc.displayName="AccordionItem";const Fc=n.forwardRef(({className:e,children:r,...n},i)=>a(rt.Header,{className:"flex",children:t(rt.Trigger,{ref:i,className:Ni("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(E,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Fc.displayName=rt.Trigger.displayName;const jc=n.forwardRef(({className:e,children:t,...r},n)=>a(rt.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:Ni("pb-4 pt-0",e),children:t})}));jc.displayName=rt.Content.displayName;const Uc=n.forwardRef(({className:e,...t},r)=>a(nt.Root,{ref:r,className:Ni("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Uc.displayName=nt.Root.displayName;const Oc=n.forwardRef(({className:e,...t},r)=>a(nt.Image,{ref:r,className:Ni("aspect-square h-full w-full",e),...t}));Oc.displayName=nt.Image.displayName;const Bc=n.forwardRef(({className:e,...t},r)=>a(nt.Fallback,{ref:r,className:Ni("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));Bc.displayName=nt.Fallback.displayName;const $c=n.forwardRef(({...e},t)=>a("nav",{ref:t,"aria-label":"breadcrumb",...e}));$c.displayName="Breadcrumb";const qc=n.forwardRef(({className:e,...t},r)=>a("ol",{ref:r,className:Ni("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",e),...t}));qc.displayName="BreadcrumbList";const Vc=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Ni("inline-flex items-center gap-1.5",e),...t}));Vc.displayName="BreadcrumbItem";const Wc=n.forwardRef(({asChild:e,className:t,...r},n)=>a(e?g:"a",{ref:n,className:Ni("transition-colors hover:text-foreground",t),...r}));Wc.displayName="BreadcrumbLink";const Hc=n.forwardRef(({className:e,...t},r)=>a("span",{ref:r,role:"link","aria-disabled":"true","aria-current":"page",className:Ni("font-normal text-foreground",e),...t}));Hc.displayName="BreadcrumbPage";const Gc=({children:e,className:t,...r})=>a("li",{role:"presentation","aria-hidden":"true",className:Ni("[&>svg]:h-3.5 [&>svg]:w-3.5",t),...r,children:e??a(F,{})});Gc.displayName="BreadcrumbSeparator";const Kc=({className:e,...r})=>t("span",{role:"presentation","aria-hidden":"true",className:Ni("flex h-9 w-9 items-center justify-center",e),...r,children:[a(be,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Mais"})]});Kc.displayName="BreadcrumbEllipsis";const Yc=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"}}),Qc=n.forwardRef(({className:e,orientation:t,...r},n)=>a("div",{ref:n,className:Ni(Yc({orientation:t}),e),...r}));function Xc({className:e,classNames:t,showOutsideDays:r=!0,...n}){return a(it,{showOutsideDays:r,className:Ni("p-3 pointer-events-auto",e),locale:Jn,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:Ni(ki({variant:"outline"}),"z-10 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),button_next:Ni(ki({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:Ni(ki({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?ie:F,{className:"h-4 w-4"})},...n})}Qc.displayName="ButtonGroup",Xc.displayName="Calendar";const Jc={Root:function({children:e,className:t}){return a("div",{className:Ni("space-y-4",t),children:e})},Item:function({children:e,onClick:t,className:r}){return a(Ii,{className:Ni("transition-colors",t&&"cursor-pointer hover:bg-muted/50",r),onClick:t,children:a(Li,{className:"p-4",children:e})})},Field:function({label:e,value:r,className:n}){return t("div",{className:Ni("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 Zc({date:e,onDateChange:r,placeholder:n,disabled:i=!1,className:s,disabledDates:o}){const{t:l}=La(),d=n??l("select_date");return t(ao,{children:[a(to,{asChild:!0,children:t(Si,{variant:"outline",disabled:i,className:Ni("w-full justify-start text-left font-normal",!e&&"text-muted-foreground",s),children:[a(xe,{className:"mr-2 h-4 w-4"}),e?_(e,"d 'de' MMMM 'de' yyyy",{locale:Jn}):a("span",{children:d})]})}),a(ro,{className:"w-auto p-0",align:"start",children:a(Xc,{mode:"single",selected:e,onSelect:r,disabled:o,initialFocus:!0,className:"pointer-events-auto"})})]})}const eu=({shouldScaleBackground:e=!0,...t})=>a(st.Root,{shouldScaleBackground:e,...t});eu.displayName="Drawer";const au=st.Trigger,tu=st.Portal,ru=st.Close,nu=n.forwardRef(({className:e,...t},r)=>a(st.Overlay,{ref:r,className:Ni("fixed inset-0 z-50 bg-black/80",e),...t}));nu.displayName=st.Overlay.displayName;const iu=n.forwardRef(({className:e,children:r,...n},i)=>t(tu,{children:[a(nu,{}),t(st.Content,{ref:i,className:Ni("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]})]}));iu.displayName="DrawerContent";const su=({className:e,...t})=>a("div",{className:Ni("grid gap-1.5 p-4 text-center sm:text-left",e),...t});su.displayName="DrawerHeader";const ou=({className:e,...t})=>a("div",{className:Ni("mt-auto flex flex-col gap-2 p-4",e),...t});ou.displayName="DrawerFooter";const lu=n.forwardRef(({className:e,...t},r)=>a(st.Title,{ref:r,className:Ni("text-lg font-semibold leading-none tracking-tight",e),...t}));lu.displayName=st.Title.displayName;const du=n.forwardRef(({className:e,...t},r)=>a(st.Description,{ref:r,className:Ni("text-sm text-muted-foreground",e),...t}));du.displayName=st.Description.displayName;const cu={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))]"},uu={xs:"gap-1",sm:"gap-2",md:"gap-4",lg:"gap-6",xl:"gap-8"};function mu({children:e,cols:t="auto-fit",gap:r="md",className:n}){return a("div",{className:Ni("grid",cu[t],uu[r],n),children:e})}const pu=ot.Root,hu=ot.Trigger,fu=n.forwardRef(({className:e,align:t="center",sideOffset:r=4,...n},i)=>a(ot.Content,{ref:i,align:t,sideOffset:r,className:Ni("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}));fu.displayName=ot.Content.displayName;const gu=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-slot":"input-group",className:Ni("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}));gu.displayName="InputGroup";const vu=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"}}),bu=n.forwardRef(({className:e,align:t,...r},n)=>a("div",{ref:n,"data-slot":"input-group-addon",className:Ni(vu({align:t}),e),...r}));bu.displayName="InputGroupAddon";const xu=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"}}),yu=n.forwardRef(({className:e,size:t,variant:r="ghost",...n},i)=>a(Si,{ref:i,"data-slot":"input-group-button",variant:r,className:Ni(xu({size:t}),"rounded-none first:rounded-l-md last:rounded-r-md",e),...n}));yu.displayName="InputGroupButton";const Nu=n.forwardRef(({className:e,...t},r)=>a(Ei,{ref:r,"data-slot":"input-group-control",className:Ni("flex-1 border-0 bg-transparent shadow-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));Nu.displayName="InputGroupInput";const wu=n.forwardRef(({className:e,...t},r)=>a(Es,{ref:r,"data-slot":"input-group-control",className:Ni("flex-1 border-0 bg-transparent shadow-none resize-none","focus-visible:ring-0 focus-visible:ring-offset-0",e),...t}));wu.displayName="InputGroupTextarea";const _u=n.forwardRef(({className:e,...t},r)=>a("h1",{ref:r,className:Ni("scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl",e),...t}));_u.displayName="H1";const Cu=n.forwardRef(({className:e,...t},r)=>a("h2",{ref:r,className:Ni("scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0",e),...t}));Cu.displayName="H2";const ku=n.forwardRef(({className:e,...t},r)=>a("h3",{ref:r,className:Ni("scroll-m-20 text-2xl font-semibold tracking-tight",e),...t}));ku.displayName="H3";const Su=n.forwardRef(({className:e,...t},r)=>a("h4",{ref:r,className:Ni("scroll-m-20 text-xl font-semibold tracking-tight",e),...t}));Su.displayName="H4";const Au=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Ni("leading-7 [&:not(:first-child)]:mt-6",e),...t}));Au.displayName="P";const Eu=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Ni("text-xl text-muted-foreground",e),...t}));Eu.displayName="Lead";const Du=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,className:Ni("text-lg font-semibold",e),...t}));Du.displayName="Large";const Pu=n.forwardRef(({className:e,...t},r)=>a("small",{ref:r,className:Ni("text-sm font-medium leading-none",e),...t}));Pu.displayName="Small";const Iu=n.forwardRef(({className:e,...t},r)=>a("p",{ref:r,className:Ni("text-sm text-muted-foreground",e),...t}));Iu.displayName="Muted";const Tu=n.forwardRef(({className:e,...t},r)=>a("code",{ref:r,className:Ni("relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",e),...t}));Tu.displayName="InlineCode";const Ru=n.forwardRef(({className:e,...t},r)=>a("blockquote",{ref:r,className:Ni("mt-6 border-l-2 pl-6 italic",e),...t}));Ru.displayName="Blockquote";const Mu=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Ni("my-6 ml-6 list-disc [&>li]:mt-2",e),...t}));Mu.displayName="List";const Lu=n.forwardRef(({className:e,children:r,...n},i)=>t(lt.Root,{ref:i,className:Ni("relative z-10 flex max-w-max flex-1 items-center justify-center",e),...n,children:[r,a($u,{})]}));Lu.displayName=lt.Root.displayName;const zu=n.forwardRef(({className:e,...t},r)=>a(lt.List,{ref:r,className:Ni("group flex flex-1 list-none items-center justify-center space-x-1",e),...t}));zu.displayName=lt.List.displayName;const Fu=lt.Item,ju=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"),Uu=n.forwardRef(({className:e,children:r,...n},i)=>t(lt.Trigger,{ref:i,className:Ni(ju(),"group",e),...n,children:[r," ",a(E,{className:"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180","aria-hidden":"true"})]}));Uu.displayName=lt.Trigger.displayName;const Ou=n.forwardRef(({className:e,...t},r)=>a(lt.Content,{ref:r,className:Ni("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}));Ou.displayName=lt.Content.displayName;const Bu=lt.Link,$u=n.forwardRef(({className:e,...t},r)=>a("div",{className:Ni("absolute left-0 top-full flex justify-center"),children:a(lt.Viewport,{className:Ni("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})}));$u.displayName=lt.Viewport.displayName;const qu=n.forwardRef(({className:e,...t},r)=>a(lt.Indicator,{ref:r,className:Ni("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 Vu({items:e,maxItems:n=3,className:i}){const s=e.length>n?[e[0],...e.slice(-(n-1))]:e,o=e.length>n;return a($c,{className:i,children:a(qc,{children:s.map((e,n)=>{const i=o&&1===n;return t(Vc,{children:[!(0===n)&&a(Gc,{}),i&&t(r,{children:[a(Kc,{}),a(Gc,{})]}),e.isCurrentPage?a(Hc,{children:e.label}):a(Wc,{asChild:!0,children:a(Qa,{to:e.href||"/",children:e.label})})]},e.label)})})})}function Wu(){const e=Ka();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,s=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ");t.push({label:s,href:i?void 0:r,isCurrentPage:i})}),t})()}qu.displayName=lt.Indicator.displayName;const Hu=({className:e,...t})=>a("nav",{role:"navigation","aria-label":"pagination",className:Ni("mx-auto flex w-full justify-center",e),...t});Hu.displayName="Pagination";const Gu=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,className:Ni("flex flex-row items-center gap-1",e),...t}));Gu.displayName="PaginationContent";const Ku=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,className:Ni("",e),...t}));Ku.displayName="PaginationItem";const Yu=({className:e,isActive:t,size:r="icon",...n})=>a("a",{"aria-current":t?"page":void 0,className:Ni(ki({variant:t?"outline":"ghost",size:r}),e),...n});Yu.displayName="PaginationLink";const Qu=({className:r,...n})=>t(Yu,{"aria-label":e.t("go_to_previous_page"),size:"default",className:Ni("gap-1 pl-2.5",r),...n,children:[a(ie,{className:"h-4 w-4"}),a("span",{children:"Previous"})]});Qu.displayName="PaginationPrevious";const Xu=({className:r,...n})=>t(Yu,{"aria-label":e.t("go_to_next_page"),size:"default",className:Ni("gap-1 pr-2.5",r),...n,children:[a("span",{children:"Next"}),a(F,{className:"h-4 w-4"})]});Xu.displayName="PaginationNext";const Ju=({className:e,...r})=>t("span",{"aria-hidden":!0,className:Ni("flex h-9 w-9 items-center justify-center",e),...r,children:[a(be,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"More pages"})]});Ju.displayName="PaginationEllipsis";const Zu=n.forwardRef(({className:e,value:t,...r},n)=>a(dt.Root,{ref:n,className:Ni("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...r,children:a(dt.Indicator,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Zu.displayName=dt.Root.displayName;const em=n.forwardRef(({className:e,...t},r)=>a(ct.Root,{className:Ni("grid gap-2",e),...t,ref:r}));em.displayName=ct.Root.displayName;const am=n.forwardRef(({className:e,...t},r)=>a(ct.Item,{ref:r,className:Ni("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(ct.Indicator,{className:"flex items-center justify-center",children:a(j,{className:"h-2.5 w-2.5 fill-current text-current"})})}));am.displayName=ct.Item.displayName;const tm=({className:e,...t})=>a(ut.PanelGroup,{className:Ni("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),rm=ut.Panel,nm=({withHandle:e,className:t,...r})=>a(ut.PanelResizeHandle,{className:Ni("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(ee,{className:"h-2.5 w-2.5"})})}),im=wa.Root,sm=wa.Trigger,om=wa.Close,lm=wa.Portal,dm=n.forwardRef(({className:e,...t},r)=>a(wa.Overlay,{className:Ni("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}));dm.displayName=wa.Overlay.displayName;const cm=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"}}),um=n.forwardRef(({side:e="right",className:r,children:n,...i},s)=>t(lm,{children:[a(dm,{}),t(wa.Content,{ref:s,className:Ni(cm({side:e}),r),...i,children:[n,t(wa.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(A,{className:"h-4 w-4"}),a("span",{className:"sr-only",children:"Close"})]})]})]}));um.displayName=wa.Content.displayName;const mm=({className:e,showSeparator:r=!1,children:n,...i})=>t("div",{className:Ni("flex flex-col flex-shrink-0",e),...i,children:[a("div",{className:"flex flex-col text-left",children:n}),r&&a(Fi,{className:"mt-2"})]});mm.displayName="SheetHeader";const pm=({className:e,...t})=>a("div",{className:Ni("flex-1 min-h-0 overflow-auto py-4 px-1 -mx-1",e),...t});pm.displayName="SheetBody";const hm=({className:e,children:r,...n})=>t("div",{className:"flex-shrink-0 pt-4",children:[a(Fi,{className:"mb-4"}),a("div",{className:Ni("flex flex-row justify-end gap-2",e),...n,children:r})]});hm.displayName="SheetFooter";const fm=n.forwardRef(({className:e,...t},r)=>a(wa.Title,{ref:r,className:Ni("text-lg font-semibold text-foreground",e),...t}));fm.displayName=wa.Title.displayName;const gm=n.forwardRef(({className:e,...t},r)=>a(wa.Description,{ref:r,className:Ni("text-sm text-muted-foreground",e),...t}));gm.displayName=wa.Description.displayName;const vm="sidebar:state",bm=n.createContext(null);function xm(){const e=n.useContext(bm);if(!e)throw new Error("useSidebar must be used within a SidebarProvider.");return e}const ym=n.forwardRef(({defaultOpen:e=!0,open:t,onOpenChange:r,className:i,style:s,children:o,...l},d)=>{const c=ml(),[u,m]=n.useState(!1),[p,h]=n.useState(()=>{if("undefined"!=typeof window){const a=localStorage.getItem(vm);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(vm,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(bm.Provider,{value:x,children:a(Qs,{delayDuration:0,children:a("div",{className:Ni("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",...s},ref:d,...l,children:o})})})});ym.displayName="SidebarProvider";const Nm=n.forwardRef(({side:e="left",variant:r="sidebar",collapsible:n="offcanvas",className:i,children:s,...o},l)=>{const{isMobile:d,state:c,openMobile:u,setOpenMobile:m}=xm();return"none"===n?a("div",{className:Ni("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",i),ref:l,...o,children:s}):d?a(im,{open:u,onOpenChange:m,...o,children:t(um,{"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(fm,{className:"sr-only",children:"Menu de Navegação"}),a("div",{className:"flex h-full w-full flex-col",children:s})]})}):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:Ni("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:Ni("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),...o,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:s})})]})});Nm.displayName="Sidebar";const wm=n.forwardRef(({className:e,onClick:r,...n},i)=>{const{toggleSidebar:s}=xm();return t(Si,{ref:i,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:Ni("h-7 w-7",e),onClick:e=>{r?.(e),s()},...n,children:[a(ye,{}),a("span",{className:"sr-only",children:"Toggle Sidebar"})]})});wm.displayName="SidebarTrigger";const _m=n.forwardRef(({className:e,...t},r)=>{const{toggleSidebar:n}=xm();return a("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:Ni("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})});_m.displayName="SidebarRail";const Cm=n.forwardRef(({className:e,...t},r)=>a("main",{ref:r,className:Ni("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}));Cm.displayName="SidebarInset";const km=n.forwardRef(({className:e,...t},r)=>a(Ei,{ref:r,"data-sidebar":"input",className:Ni("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",e),...t}));km.displayName="SidebarInput";const Sm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"header",className:Ni("flex flex-col gap-2 p-2",e),...t}));Sm.displayName="SidebarHeader";const Am=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"footer",className:Ni("flex flex-col gap-2 p-2",e),...t}));Am.displayName="SidebarFooter";const Em=n.forwardRef(({className:e,...t},r)=>a(Fi,{ref:r,"data-sidebar":"separator",className:Ni("mx-2 w-auto bg-sidebar-border",e),...t}));Em.displayName="SidebarSeparator";const Dm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"content",className:Ni("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",e),...t}));Dm.displayName="SidebarContent";const Pm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group",className:Ni("relative flex w-full min-w-0 flex-col p-2",e),...t}));Pm.displayName="SidebarGroup";const Im=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"div",{ref:n,"data-sidebar":"group-label",className:Ni("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}));Im.displayName="SidebarGroupLabel";const Tm=n.forwardRef(({className:e,asChild:t=!1,...r},n)=>a(t?g:"button",{ref:n,"data-sidebar":"group-action",className:Ni("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}));Tm.displayName="SidebarGroupAction";const Rm=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"group-content",className:Ni("w-full text-sm",e),...t}));Rm.displayName="SidebarGroupContent";const Mm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu",className:Ni("flex w-full min-w-0 flex-col gap-1",e),...t}));Mm.displayName="SidebarMenu";const Lm=n.forwardRef(({className:e,...t},r)=>a("li",{ref:r,"data-sidebar":"menu-item",className:Ni("group/menu-item relative",e),...t}));Lm.displayName="SidebarMenuItem";const zm=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"}}),Fm=n.forwardRef(({asChild:e=!1,isActive:r=!1,variant:n="default",size:i="default",tooltip:s,className:o,...l},d)=>{const c=e?g:"button",{isMobile:u,state:m}=xm(),p=a(c,{ref:d,"data-sidebar":"menu-button","data-size":i,"data-active":r,className:Ni(zm({variant:n,size:i}),o),...l});return s?("string"==typeof s&&(s={children:s}),t(Xs,{children:[a(Js,{asChild:!0,children:p}),a(Zs,{side:"right",align:"center",hidden:"collapsed"!==m||u,...s})]})):p});Fm.displayName="SidebarMenuButton";const jm=n.forwardRef(({className:e,asChild:t=!1,showOnHover:r=!1,...n},i)=>a(t?g:"button",{ref:i,"data-sidebar":"menu-action",className:Ni("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}));jm.displayName="SidebarMenuAction";const Um=n.forwardRef(({className:e,...t},r)=>a("div",{ref:r,"data-sidebar":"menu-badge",className:Ni("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}));Um.displayName="SidebarMenuBadge";const Om=n.forwardRef(({className:e,showIcon:r=!1,...i},s)=>{const o=n.useMemo(()=>`${Math.floor(40*Math.random())+50}%`,[]);return t("div",{ref:s,"data-sidebar":"menu-skeleton",className:Ni("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":o}})]})});Om.displayName="SidebarMenuSkeleton";const Bm=n.forwardRef(({className:e,...t},r)=>a("ul",{ref:r,"data-sidebar":"menu-sub",className:Ni("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}));Bm.displayName="SidebarMenuSub";const $m=n.forwardRef(({...e},t)=>a("li",{ref:t,...e}));$m.displayName="SidebarMenuSubItem";const qm=n.forwardRef(({asChild:e=!1,size:t="md",isActive:r,className:n,...i},s)=>a(e?g:"a",{ref:s,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:Ni("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}));qm.displayName="SidebarMenuSubButton";const Vm=n.forwardRef(({className:e,value:r,defaultValue:n,...i},s)=>{const o=r||n||[0];return t(mt.Root,{ref:s,value:r,defaultValue:n,className:Ni("relative flex w-full touch-none select-none items-center",e),...i,children:[a(mt.Track,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:a(mt.Range,{className:"absolute h-full bg-primary"})}),o.map((e,t)=>a(mt.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 Wm({children:e,className:t}){return a("div",{className:Ni("flex flex-col h-full",t),children:a(bo,{className:"flex-1",children:a("div",{className:"space-y-6 p-6",children:e})})})}function Hm({title:e,description:r,actions:n,className:i}){return t("div",{className:Ni("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(Fi,{})]})}function Gm({children:e,className:t}){return a("div",{className:Ni("space-y-6",t),children:e})}Vm.displayName=mt.Root.displayName;const Km=pt.Menu,Ym=pt.Group,Qm=pt.Portal,Xm=pt.Sub,Jm=pt.RadioGroup,Zm=n.forwardRef(({className:e,...t},r)=>a(pt.Root,{ref:r,className:Ni("flex h-10 items-center space-x-1 rounded-md border bg-background p-1",e),...t}));Zm.displayName=pt.Root.displayName;const ep=n.forwardRef(({className:e,...t},r)=>a(pt.Trigger,{ref:r,className:Ni("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}));ep.displayName=pt.Trigger.displayName;const ap=n.forwardRef(({className:e,inset:r,children:n,...i},s)=>t(pt.SubTrigger,{ref:s,className:Ni("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(F,{className:"ml-auto h-4 w-4"})]}));ap.displayName=pt.SubTrigger.displayName;const tp=n.forwardRef(({className:e,...t},r)=>a(pt.SubContent,{ref:r,className:Ni("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}));tp.displayName=pt.SubContent.displayName;const rp=n.forwardRef(({className:e,align:t="start",alignOffset:r=-4,sideOffset:n=8,...i},s)=>a(pt.Portal,{children:a(pt.Content,{ref:s,align:t,alignOffset:r,sideOffset:n,className:Ni("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})}));rp.displayName=pt.Content.displayName;const np=n.forwardRef(({className:e,inset:t,...r},n)=>a(pt.Item,{ref:n,className:Ni("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}));np.displayName=pt.Item.displayName;const ip=n.forwardRef(({className:e,children:r,checked:n,...i},s)=>t(pt.CheckboxItem,{ref:s,className:Ni("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(pt.ItemIndicator,{children:a(P,{className:"h-4 w-4"})})}),r]}));ip.displayName=pt.CheckboxItem.displayName;const sp=n.forwardRef(({className:e,children:r,...n},i)=>t(pt.RadioItem,{ref:i,className:Ni("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(pt.ItemIndicator,{children:a(j,{className:"h-2 w-2 fill-current"})})}),r]}));sp.displayName=pt.RadioItem.displayName;const op=n.forwardRef(({className:e,inset:t,...r},n)=>a(pt.Label,{ref:n,className:Ni("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...r}));op.displayName=pt.Label.displayName;const lp=n.forwardRef(({className:e,...t},r)=>a(pt.Separator,{ref:r,className:Ni("-mx-1 my-1 h-px bg-muted",e),...t}));lp.displayName=pt.Separator.displayName;const dp=({className:e,...t})=>a("span",{className:Ni("ml-auto text-xs tracking-widest text-muted-foreground",e),...t});dp.displayname="MenubarShortcut";const cp={light:"",dark:".dark"},up=n.createContext(null);function mp(){const e=n.useContext(up);if(!e)throw new Error("useChart must be used within a <ChartContainer />");return e}const pp=n.forwardRef(({id:e,className:r,children:i,config:s,...o},l)=>{const d=n.useId(),c=`chart-${e||d.replace(/:/g,"")}`;return a(up.Provider,{value:{config:s},children:t("div",{"data-chart":c,ref:l,className:Ni("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),...o,children:[a(hp,{id:c,config:s}),a(ht.ResponsiveContainer,{children:i})]})})});pp.displayName="Chart";const hp=({id:e,config:t})=>{const r=Object.entries(t).filter(([,e])=>e.theme||e.color);return r.length?a("style",{dangerouslySetInnerHTML:{__html:Object.entries(cp).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},fp=ht.Tooltip,gp=n.forwardRef(({active:e,payload:i,className:s,indicator:o="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}=mp(),x=n.useMemo(()=>{if(l||!i?.length)return null;const[e]=i,t=xp(b,e,`${g||e?.dataKey||e?.name||"value"}`),r=g||"string"!=typeof c?t?.label:b[c]?.label||c;return u?a("div",{className:Ni("font-medium",m),children:u(r,i)}):r?a("div",{className:Ni("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"!==o;return t("div",{ref:v,className:Ni("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",s),children:[y?null:x,a("div",{className:"grid gap-1.5",children:i.map((e,n)=>{const i=`${f||e.name||e.dataKey||"value"}`,s=xp(b,e,i),l=h||e.payload?.fill||e.color;return a("div",{className:Ni("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground","dot"===o&&"items-center"),children:p&&void 0!==e?.value&&e.name?p(e.value,e.name,e,n,e.payload):t(r,{children:[s?.icon?a(s.icon,{}):!d&&a("div",{className:Ni("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":"dot"===o,"w-1":"line"===o,"w-0 border-[1.5px] border-dashed bg-transparent":"dashed"===o,"my-0.5":y&&"dashed"===o}),style:{"--color-bg":l,"--color-border":l}}),t("div",{className:Ni("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:s?.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)})})]})});gp.displayName="ChartTooltip";const vp=ht.Legend,bp=n.forwardRef(({className:e,hideIcon:r=!1,payload:n,verticalAlign:i="bottom",nameKey:s},o)=>{const{config:l}=mp();return n?.length?a("div",{ref:o,className:Ni("flex items-center justify-center gap-4","top"===i?"pb-3":"pt-3",e),children:n.map(e=>{const n=`${s||e.dataKey||"value"}`,i=xp(l,e,n);return t("div",{className:Ni("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 xp(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]}bp.displayName="ChartLegend";const yp=({onClick:e,isActive:t,disabled:r,children:n,title:i})=>a("button",{type:"button",onClick:e,disabled:r,title:i,className:Ni("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}),Np=()=>a("div",{className:"w-px h-5 bg-border mx-1"}),wp=({value:r,onChange:i,disabled:o,placeholder:d=e.t("write_content_here"),minHeight:c="300px",showModeToggle:u=!0,showVariableHint:m=!0,className:p})=>{const{t:h}=La(),[f,g]=s("visual"),v=It({extensions:[Rt.configure({heading:{levels:[1,2,3]}}),Mt,Lt.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),zt,Ft,jt.configure({multicolor:!0})],content:r||"",editable:!o,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:Ni("space-y-2",p),children:[u&&t("div",{className:"flex justify-between items-center",children:[t("div",{className:"flex gap-1",children:[t(Si,{type:"button",size:"sm",variant:"visual"===f?"default":"outline",onClick:()=>g("visual"),disabled:o,children:[a(Ne,{className:"h-3.5 w-3.5 mr-1"}),"Editor Visual"]}),t(Si,{type:"button",size:"sm",variant:"code"===f?"default":"outline",onClick:()=>g("code"),disabled:o,children:[a(we,{className:"h-3.5 w-3.5 mr-1"}),"Código HTML"]}),t(Si,{type:"button",size:"sm",variant:"preview"===f?"default":"outline",onClick:()=>g("preview"),disabled:o,children:[a(_e,{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(yp,{onClick:()=>v.chain().focus().toggleHeading({level:1}).run(),isActive:v.isActive("heading",{level:1}),disabled:o,title:e.t("heading_1"),children:a(Ce,{className:"h-4 w-4"})}),a(yp,{onClick:()=>v.chain().focus().toggleHeading({level:2}).run(),isActive:v.isActive("heading",{level:2}),disabled:o,title:e.t("heading_2"),children:a(ke,{className:"h-4 w-4"})}),a(yp,{onClick:()=>v.chain().focus().toggleHeading({level:3}).run(),isActive:v.isActive("heading",{level:3}),disabled:o,title:e.t("heading_3"),children:a(Se,{className:"h-4 w-4"})}),a(Np,{}),a(yp,{onClick:()=>v.chain().focus().toggleBold().run(),isActive:v.isActive("bold"),disabled:o,title:e.t("bold"),children:a(Ae,{className:"h-4 w-4"})}),a(yp,{onClick:()=>v.chain().focus().toggleItalic().run(),isActive:v.isActive("italic"),disabled:o,title:e.t("italic"),children:a(Ee,{className:"h-4 w-4"})}),a(yp,{onClick:()=>v.chain().focus().toggleUnderline().run(),isActive:v.isActive("underline"),disabled:o,title:"Sublinhado",children:a(De,{className:"h-4 w-4"})}),a(yp,{onClick:()=>v.chain().focus().toggleStrike().run(),isActive:v.isActive("strike"),disabled:o,title:"Riscado",children:a(Pe,{className:"h-4 w-4"})}),a(Np,{}),a(yp,{onClick:()=>v.chain().focus().toggleBulletList().run(),isActive:v.isActive("bulletList"),disabled:o,title:"Lista",children:a(X,{className:"h-4 w-4"})}),a(yp,{onClick:()=>v.chain().focus().toggleOrderedList().run(),isActive:v.isActive("orderedList"),disabled:o,title:h("ordered_list"),children:a(Ie,{className:"h-4 w-4"})}),a(Np,{}),a(yp,{onClick:()=>v.chain().focus().toggleHighlight().run(),isActive:v.isActive("highlight"),disabled:o,title:"Destacar",children:a(Te,{className:"h-4 w-4"})}),a(yp,{onClick:b,isActive:v.isActive("link"),disabled:o,title:"Link",children:a(Re,{className:"h-4 w-4"})}),a(Np,{}),a(yp,{onClick:()=>v.chain().focus().unsetAllMarks().clearNodes().run(),disabled:o,title:h("clear_formatting"),children:a(Me,{className:"h-4 w-4"})}),a(Np,{}),a(yp,{onClick:()=>v.chain().focus().undo().run(),disabled:o||!v.can().undo(),title:"Desfazer",children:a(Le,{className:"h-4 w-4"})}),a(yp,{onClick:()=>v.chain().focus().redo().run(),disabled:o||!v.can().redo(),title:"Refazer",children:a(ze,{className:"h-4 w-4"})})]}),a(Tt,{editor:v,className:Ni("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:o,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 _p({image:e,title:t,className:r}){return a("div",{className:Ni("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(Fe,{className:"w-16 h-16 text-muted-foreground"})})})}function Cp({steps:e,currentStepIndex:r,onStepSelect:n,stepLabel:i,className:s}){const{t:o}=La(),l=e.length,d=(r+1)/l*100;return t("div",{className:Ni("flex items-center gap-3",s),children:[t(Ls,{children:[a(zs,{asChild:!0,children:t(Si,{variant:"ghost",size:"sm",className:"h-8 px-2 text-sm",children:[i," ",r+1,"/",l,a(E,{className:"h-3 w-3 ml-1"})]})}),a(qs,{align:"start",children:e.map((e,a)=>t(Vs,{onClick:()=>n(a),className:Ni(a===r&&"bg-accent"),children:[a+1,". ",e.title]},e.id))})]}),a(Zu,{value:d,className:"w-32 h-2"})]})}function kp({currentStepIndex:e,totalSteps:r,onBack:n,onNext:i,onComplete:s,backButtonText:o,continueButtonText:l,finishButtonText:d,className:c}){const{t:u}=La(),m=0===e,p=e===r-1;return t("div",{className:Ni("flex items-center gap-2",c),children:[!m&&t(Si,{variant:"outline",onClick:n,size:"sm",children:[a(je,{className:"h-4 w-4 mr-2"}),o]}),t(Si,{onClick:p?s:i,size:"sm",children:[p?d:l,!p&&a(Ue,{className:"h-4 w-4 ml-2"})]})]})}const Sp=n.forwardRef(({open:r,onOpenChange:i,steps:s,onComplete:o,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=s[w],k=s.length;return C?a(Yi,{open:r,onOpenChange:i,children:t(as,{ref:b,size:p,variant:"informative",className:Ni("p-0 gap-0 overflow-hidden",v),children:[t(Ji,{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(A,{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(_p,{image:C.image,title:C.title}),a(is,{className:"text-xl font-semibold",children:C.title}),a(ss,{className:"text-muted-foreground",children:C.description})]})}),t("div",{className:"flex-shrink-0",children:[a(Fi,{}),t("div",{className:"p-4 flex flex-wrap items-center justify-between gap-2",children:[h&&k>1?a(Cp,{steps:s,currentStepIndex:w,onStepSelect:e=>{_(e)},stepLabel:m}):a("div",{}),a(kp,{currentStepIndex:w,totalSteps:k,onBack:()=>{w>0&&_(w-1)},onNext:()=>{w<k-1&&_(w+1)},onComplete:()=>{o?.(),i(!1)},backButtonText:c,continueButtonText:d,finishButtonText:u})]})]})]})}):null});function Ap({label:e,onClick:r,icon:n,actions:i=[],variant:s="default",size:o="default",disabled:l=!1,loading:d=!1,menuAlign:c="end",className:u}){const{t:m}=La(),p=l||d;if(!(i.length>0))return t(Si,{variant:s,size:o,disabled:p,onClick:r,className:u,children:[d?a(I,{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:Ni("inline-flex rounded-md shadow-sm",u),children:[t(Si,{variant:s,size:o,disabled:p,onClick:r,className:"rounded-r-none border-r-0 focus:z-10",children:[d?a(I,{className:"mr-2 h-4 w-4 animate-spin"}):n?a(n,{className:"mr-2 h-4 w-4"}):null,e]}),t(Ls,{children:[a(zs,{asChild:!0,children:a(Si,{variant:s,size:o,disabled:p,className:Ni("rounded-l-none focus:z-10",{sm:"w-7 min-w-7 px-0",default:"w-8 min-w-8 px-0",lg:"w-9 min-w-9 px-0"}[o]),"aria-label":m("more_options"),children:a(E,{className:{sm:"h-3 w-3",default:"h-4 w-4",lg:"h-4 w-4"}[o]})})}),a(qs,{align:c,className:"min-w-[160px]",children:i.map(e=>{const r=e.icon;return t(Vs,{onClick:e.onClick,disabled:e.disabled,className:Ni("destructive"===e.variant&&"text-destructive focus:text-destructive"),children:[r&&a(r,{className:"mr-2 h-4 w-4"}),e.label]},e.id)})})]})]})}var Ep,Dp;Sp.displayName="OnboardingDialog",(Dp=Ep||(Ep={})).CSV="csv",Dp.PDF="pdf",Dp.XLSX="xlsx",Dp.PNG="png",Dp.JPEG="jpeg",Dp.SVG="svg";const Pp=[{value:Ep.CSV,label:"CSV",icon:a(Oe,{className:"h-5 w-5"})},{value:Ep.PDF,label:"PDF",icon:a(Oe,{className:"h-5 w-5"})},{value:Ep.XLSX,label:"XLSX",icon:a(Be,{className:"h-5 w-5"})}],Ip=[{value:Ep.PNG,label:"PNG",icon:a($e,{className:"h-5 w-5"})},{value:Ep.JPEG,label:"JPEG",icon:a(qe,{className:"h-5 w-5"})},{value:Ep.SVG,label:"SVG",icon:a(qe,{className:"h-5 w-5"})},{value:Ep.PDF,label:"PDF",icon:a(Oe,{className:"h-5 w-5"})}];function Tp({open:e,onOpenChange:r,onExport:n,mode:i="table",options:o,title:l,description:d,cancelLabel:c="Cancelar",exportLabel:u="Exportar"}){const{t:m}=La(),[p,h]=s(""),f=o??("chart"===i?Ip:Pp),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(Yi,{open:e,onOpenChange:b,children:t(as,{className:"sm:max-w-md",variant:"form",isDirty:!!p,children:[a(ts,{children:a(is,{children:g})}),t("div",{className:"py-4",children:[a("p",{className:"text-sm text-muted-foreground mb-4",children:v}),a(em,{value:p,onValueChange:h,className:"gap-3",children:f.map(e=>t("div",{className:"flex items-center space-x-3",children:[a(am,{value:e.value,id:`export-${e.value}`}),t(Pi,{htmlFor:`export-${e.value}`,className:Ni("flex items-center gap-2 cursor-pointer font-normal",p===e.value&&"font-medium"),children:[e.icon,e.label]})]},e.value))})]}),t(ns,{children:[a(Si,{variant:"outline",onClick:()=>b(!1),children:c}),a(Si,{onClick:()=>{p&&(n(p),r(!1),h(""))},disabled:!p,children:u})]})]})})}const Rp=f(({value:e,onChange:r,onTimeChange:i,label:s,error:o,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:Ni("grid gap-1.5",c),children:[s&&a(Pi,{htmlFor:h,children:s}),t("div",{className:"relative",children:[a(Ei,{ref:p,id:h,type:"time",value:e??"",onChange:f,onKeyDown:g,min:"00:00",max:"23:59",step:60,className:Ni("pr-9",o&&"border-destructive focus-visible:ring-destructive"),...m}),a(Ve,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none"})]}),o&&a("p",{className:"text-sm text-destructive",children:o})]})});function Mp({open:r,onOpenChange:n,onConfirm:i,onGenerateCode:o,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]=s(""),[_,C]=s(!1),[k,S]=s(!1),[A,E]=s(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(o){S(!0),E(null);try{await o()}catch{E(e.t("esign_resend_error"))}finally{S(!1)}}},[o]),I=e=>{e||(w(""),E(null)),n(e)},T=b?We:He,R=b?"Senha":e.t("verification_code"),M=b?e.t("enter_password"):e.t("enter_code");return a(Yi,{open:r,onOpenChange:I,children:t(as,{className:"sm:max-w-md",variant:"form",isDirty:!!N,children:[a(ts,{children:t(is,{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(Ge,{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(Pi,{htmlFor:"signature-input",children:R}),a(Ei,{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:Ni(A&&"border-destructive focus-visible:ring-destructive")}),A&&a("p",{className:"text-sm text-destructive",children:A})]}),!b&&t(Si,{variant:"ghost",size:"sm",onClick:P,disabled:k,className:"text-primary",children:[a(ce,{className:Ni("h-4 w-4 mr-1",k&&"animate-spin")}),g]})]}),t(ns,{children:[a(Si,{variant:"outline",onClick:()=>I(!1),disabled:_,children:f}),a(Si,{onClick:D,disabled:!N.trim()||_,children:_?"Validando...":h})]})]})})}function Lp({currentStep:e,totalSteps:r,onStepChange:i,stepLabels:s,canGoToStep:o,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)&&(!!o&&!o(a));return t("div",{className:Ni("flex items-center gap-3",l),children:[t(Ls,{children:[a(zs,{asChild:!0,children:t(Si,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-sm text-muted-foreground hover:text-foreground",children:["Etapa ",e,"/",r,a(E,{className:"h-3 w-3 ml-1"})]})}),a(qs,{align:"start",children:c.map(r=>t(Vs,{onClick:()=>{var a;(a=r)<e?i(a):o&&!o(a)||i(a)},disabled:u(r),className:Ni("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,"."]}),s?.[r-1]||`Etapa ${r}`,r===e&&a(P,{className:"h-4 w-4 ml-auto"})]},r))})]}),a(Zu,{value:e/r*100,className:Ni("h-2",d)})]})}function zp({open:r,onOpenChange:n,currentStep:i,onStepChange:s,steps:o,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}=La(),E=o.length,D=i>=E,I=i<=1;return a(Yi,{open:r,onOpenChange:n,children:t(as,{size:b,variant:g,isDirty:v,unsavedChangesTitle:x,unsavedChangesDescription:y,cancelText:N,leaveWithoutSavingText:w,className:Ni("!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:o.map((e,r)=>{const n=r+1,o=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?s(e):l&&!l(e)||s(e))})(n),disabled:!c,className:Ni("flex items-center gap-2 py-3 px-2 rounded-md text-left transition-colors text-xs",o&&"bg-primary-foreground/20 font-semibold",!o&&c&&"hover:bg-primary-foreground/10 cursor-pointer",!c&&"opacity-40 cursor-not-allowed"),children:[a("span",{className:Ni("flex items-center justify-center h-7 w-7 rounded-full text-xs font-bold flex-shrink-0 transition-colors",o&&"bg-primary-foreground text-primary",d&&!o&&"bg-primary-foreground/30 text-primary-foreground",!o&&!d&&"border-2 border-primary-foreground/40 text-primary-foreground/60"),children:d&&!o?a(P,{className:"h-3.5 w-3.5"}):n}),a("span",{className:Ni("line-clamp-2",o&&"text-primary-foreground",!o&&"text-primary-foreground/70"),children:e})]},n)})})]}),t("div",{className:"flex flex-col flex-1 min-w-0",children:[t(ts,{className:"p-6 pb-0",children:[t("p",{className:"text-xs text-muted-foreground sm:hidden mb-1",children:["Etapa ",i," de ",E]}),a(is,{children:c}),u&&a("p",{className:"text-sm text-muted-foreground mt-1",children:u})]}),a(rs,{className:"px-6",children:d}),!k&&a(ns,{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:[!I&&a(Si,{variant:"outline",onClick:()=>s(i-1),children:f}),a(Si,D?{onClick:m,disabled:C,children:p}:{onClick:()=>s(i+1),disabled:C,children:h})]})]})})]})]})})}function Fp(e){const a=Lo.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 jp(e,a,t){let r=await fetch(e,a);if(401===r.status){if(await Vo.handleApiError({status:401})){const n={...a,headers:Fp(t)};r=await fetch(e,n)}}return r}function Up(e){const[a,t]=s([]),[r,n]=s(0),[i,o]=s(!1);m(()=>{if(!e)return;let a=!1;const r=`${or().replace(/\/?$/,"/")}api/common/v1/updates/listUpdatesNotification`;return async function(){o(!0);try{const i=Fp(e),s=await jp(r,{method:"GET",headers:i},e);if(!s.ok)return;const o=await s.json();!a&&o.data?.[0]&&(t(o.data[0].updates??[]),n(o.data[0].valueBadge??0))}catch(i){}finally{a||o(!1)}}(),()=>{a=!0}},[e]);const d=l(async()=>{if(!e||r<=0||0===a.length)return;const t=a[0].id,i=`${or().replace(/\/?$/,"/")}api/common/v1/Updates/userVisualized/3/undefined`;n(0);try{const a=Fp(e),r=JSON.stringify({id:t,idUpdateType:3});await jp(i,{method:"POST",headers:a,body:r},e)}catch(s){}},[e,r,a]);return{updates:a,badgeCount:r,loading:i,markAsVisualized:d}}Rp.displayName="Timepicker";const Op=i.forwardRef(({updates:r,badgeCount:n,onOpen:i,onViewAll:s},o)=>{const l=void 0===r,d=ll(),c=d?.alias??null,u=Up(l?c:null),m=l?u.updates??[]:r,p=l?u.badgeCount??0:n??0,h=i??(l?u.markAsVisualized:void 0),f=s??(l&&c?()=>{const e=`https://apps4.qualiex.com/common/${c}/up/view`;window.open(e,"_blank","noopener,noreferrer")}:void 0);return t(ao,{children:[a(to,{asChild:!0,children:t(Si,{ref:o,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(Ke,{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(ro,{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(Ke,{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(Si,{variant:"ghost",size:"sm",className:"w-full justify-between text-primary hover:text-primary",onClick:f,children:["Ver todas as atualizações",a(Ue,{className:"h-[18px] w-[18px]"})]})})]})]})});var Bp,$p,qp,Vp;Op.displayName="UpdatesNotification",($p=Bp||(Bp={}))[$p.none=0]="none",$p[$p.image=1]="image",$p[$p.video=2]="video",$p[$p.audio=3]="audio",$p[$p.wopi=4]="wopi",$p[$p.onlineEditor=5]="onlineEditor",$p[$p.report=6]="report",(Vp=qp||(qp={}))[Vp.SimplePrint=0]="SimplePrint",Vp[Vp.ManagedCopy=1]="ManagedCopy",Vp[Vp.NonManagedCopy=2]="NonManagedCopy";const Wp={".jpg":Bp.image,".jpeg":Bp.image,".png":Bp.image,".bmp":Bp.image,".gif":Bp.image,".svg":Bp.image,".webp":Bp.image,".wav":Bp.audio,".mp3":Bp.audio,".mp4":Bp.video,".webm":Bp.video,".ogg":Bp.video,".pdf":Bp.wopi,".ods":Bp.wopi,".xls":Bp.wopi,".xlsb":Bp.wopi,".xlsm":Bp.wopi,".xlsx":Bp.wopi,".doc":Bp.wopi,".docm":Bp.wopi,".docx":Bp.wopi,".dot":Bp.wopi,".dotm":Bp.wopi,".dotx":Bp.wopi,".odt":Bp.wopi,".odp":Bp.wopi,".pot":Bp.wopi,".potm":Bp.wopi,".potx":Bp.wopi,".pps":Bp.wopi,".ppsm":Bp.wopi,".ppsx":Bp.wopi,".ppt":Bp.wopi,".pptm":Bp.wopi,".pptx":Bp.wopi,".gdocs":Bp.onlineEditor,".gsheets":Bp.onlineEditor};function Hp(e){const{t:a}=La();return e?Wp[e.toLowerCase()]??Bp.none:Bp.none}function Gp(e){const{t:a}=La();return{".gdocs":"document",".gsheets":"spreadsheets"}[e.toLowerCase()]||"document"}const Kp={".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 Yp(e){const{t:a}=La();return Kp[e?.toLowerCase()]||""}function Qp(e){const{t:a}=La(),{viewerUrl:t,wopiUrl:r,fileId:n,token:i,extension:s,language:o="pt-br"}=e,l=Yp(s);if(!l)return null;return`${t}${l}ui=${o}&rs=${o}&access_token=${i}&WOPISrc=${encodeURIComponent(`${r}${n}`)}`}function Xp({open:e,onOpenChange:n,template:i,viewerType:s,isLoading:o=!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}=La(),S=u(null),E=s??Hp(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(Yi,{open:e,onOpenChange:n,children:t(as,{className:Ni("max-w-[95vw] max-h-[95vh] p-6 gap-0 [&>button.absolute]:hidden",(E===Bp.wopi||E===Bp.report)&&"w-[90vw]",C),children:[t("div",{className:"flex items-center justify-between mb-4 min-h-[35px]",children:[a("h2",o?{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:[!o&&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(Ye,{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:Jp(w)}),a("span",{children:"segundos"})]}):t(Si,{variant:"default",size:"sm",disabled:D,onClick:()=>y?.(),className:"mr-2.5",children:[a(He,{className:"h-4 w-4 mr-1"}),N?"Confirmando...":k("terms_confirm_reading")]})}),E!==Bp.none&&h&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>g?.(f),children:a(Qe,{className:Ni("h-4 w-4",f&&"fill-accent text-accent")})})}),a(Zs,{children:f?"Desfavoritar":"Favoritar"})]}),E!==Bp.none&&d&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>c?.(),children:a(Xe,{className:"h-4 w-4"})})}),a(Zs,{children:"Download"})]})]}),t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:D,onClick:()=>n(!1),children:a(A,{className:"h-4 w-4"})})}),a(Zs,{children:"Fechar"})]})]})]}),a("div",{className:Ni("flex flex-col items-center justify-center min-h-[160px] w-full",o&&"relative -top-5",E===Bp.none&&"min-h-[124px]",E===Bp.image&&"max-h-[85vh]",(E===Bp.wopi||E===Bp.report)&&"min-w-[77vw] min-h-[80vh]"),children:o?a(Ts,{className:"h-14 w-14"}):t(r,{children:[(E===Bp.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?"})]}),E===Bp.image&&a("img",{loading:"eager",src:i.url,alt:i.name,className:"max-w-full max-h-[85vh] object-contain"}),E===Bp.video&&a("video",{controls:!0,autoPlay:!0,src:i.url,className:"w-full h-full"}),E===Bp.audio&&a("audio",{controls:!0,autoPlay:!0,src:i.url}),(E===Bp.wopi||E===Bp.report)&&t("div",{className:"relative w-full h-[79.5vh]",children:[a(Ts,{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})]})]})}),!o&&E===Bp.none&&t("div",{className:"flex justify-end gap-2 mt-4 pt-4 border-t border-border",children:[a(Si,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),d&&a(Si,{variant:"default",onClick:()=>c?.(),children:"Download"})]})]})})}function Jp(e){const{t:a}=La(),t=e%60;return`${Math.floor(e/60)}min ${t<10?"0":""}${t}`}function Zp({open:e,onOpenChange:r,identifier:n,fileName:i,mode:o="edit",type:d="document",onClose:c,className:u}){const[p,h]=s(!0),f=function(e,a="edit",t="document"){return`https://docs.google.com/${t}/d/${e}/${a}?usp=drivesdk?embedded=true&rm=demo`}(n,o,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(Yi,{open:e,onOpenChange:r,children:t(as,{className:Ni("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(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:g,children:a(A,{className:"h-4 w-4"})})}),a(Zs,{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(Ts,{className:"h-14 w-14"}):t("div",{className:"relative w-full h-[79.5vh]",children:[a(Ts,{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 eh({open:e,onOpenChange:r,url:n,title:i,className:s,minHeight:o="250px"}){const{t:d}=La(),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(Yi,{open:e,onOpenChange:r,children:t(as,{className:Ni("max-w-[95vw] max-h-[95vh] w-[90vw] p-6 gap-0 [&>button.absolute]:hidden",s),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(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:c,children:a(A,{className:"h-4 w-4"})})}),a(Zs,{children:"Fechar"})]})]}),a("iframe",{src:n,className:"border-none w-full",style:{minHeight:o},title:i||d("embedded_content")})]})})}function ah({term:n,open:i,onClose:o,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]=s(!1),g=l(()=>{d(n.id)},[d,n.id]);return t(r,{children:[a(Yi,{open:i&&!h,onOpenChange:e=>!e&&o(),children:t(as,{className:"sm:max-w-md",children:[a(ts,{children:t(is,{className:"flex items-center gap-2",children:[a(He,{className:"h-5 w-5 text-primary"}),c]})}),t("div",{className:"space-y-4",children:[n.description&&a(bo,{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(Si,{variant:"link",className:"px-0 text-primary",onClick:()=>f(!0),children:[a(me,{className:"mr-1 h-4 w-4"}),p]})]}),t(ns,{className:"gap-2 sm:gap-0",children:[a(Si,{variant:"ghost",onClick:o,children:u}),a(Si,{onClick:g,children:m})]})]})}),h&&a(th,{term:n,open:h,onClose:()=>f(!1),viewOnly:!0})]})}function th({term:r,open:n,onClose:i,onSign:s,viewOnly:d=!1,title:c=e.t("terms_of_use"),signLabel:u=e.t("terms_read_agree")}){const m=o(()=>r.file?function(e,a=""){const{t:t}=La(),r=atob(e),n=[];for(let s=0;s<r.length;s+=512){const e=r.slice(s,s+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():s?.(r.id)},[r,s,p]),f=!d&&!r.hasUserSignature&&s;return a(Yi,{open:n,onOpenChange:e=>!e&&p(),children:t(as,{className:Ni("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(Oe,{className:"h-5 w-5 text-primary"}),c]}),t("div",{className:"flex items-center gap-2",children:[f&&a(Si,{size:"sm",onClick:h,children:u}),a(Si,{variant:"ghost",size:"icon",onClick:p,children:a(A,{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 rh(e){const{t:a}=La();return e.split(" ").slice(0,2).map(e=>e[0]?.toUpperCase()??"").join("")}function nh(e){const{t:a}=La();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function ih({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]=s(!1),[_,C]=s(""),[k,S]=s(void 0),A=o(()=>new Set(i),[i]),E=o(()=>{let e=r;if(k&&(e=e.filter(e=>e.groupIds?.includes(k))),_){const a=nh(_);e=e.filter(e=>nh(e.name).includes(a)||nh(e.email??"").includes(a))}return e},[r,k,_]),D=o(()=>N?E:r.filter(e=>A.has(e.id)),[N,E,r,A]),P=i.length,I=o(()=>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:Ni("rounded-md border bg-muted/30",y),children:[(!c||P>0)&&t("div",{className:Ni("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(vs,{value:k??"__all__",onValueChange:e=>S("__all__"===e?void 0:e),children:[a(ys,{className:"w-[200px] h-9 text-sm",children:a(xs,{placeholder:e.t("approval_user_group")})}),t(_s,{children:[a(ks,{value:"__all__",children:e.t("team_all_groups")}),n.map(e=>a(ks,{value:e.id,children:e.name},e.id))]})]}),t("div",{className:"relative flex-1",children:[a(O,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Ei,{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(Je,{className:"h-4 w-4 mr-2"}),v]}),N&&E.length>0&&t("div",{className:"flex items-center gap-2 mb-2",children:[a(As,{checked:I,onCheckedChange:e=>R(!!e)}),a("span",{className:"text-sm",children:g})]}),D.length>0&&a(bo,{style:{maxHeight:u},className:"pr-2",children:a("div",{className:"space-y-0.5",children:D.map(e=>t("div",{className:Ni("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(As,{checked:A.has(e.id),onCheckedChange:()=>T(e.id),onClick:e=>e.stopPropagation()}),t(Uc,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(Oc,{src:e.avatar,alt:e.name}),a(Bc,{className:"text-xs",children:rh(e.name)})]}),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))})}),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 sh(e){const{t:a}=La();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function oh(e){const{t:a}=La(),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 lh({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]=s(n[0]?.id??""),[k,S]=s(""),[D,I]=s([]),[T,R]=s(!1),M=o(()=>oh(i[_]),[i,_]),L=o(()=>function(e){const{t:a}=La(),t=new Set;if(!e)return t;for(const r of e)r.inheritedIds?.forEach(e=>t.add(e));return t}(i[_]),[i,_]),z=o(()=>r.filter(e=>M.has(e.id)),[r,M]),F=o(()=>{const e=sh(k);return r.filter(a=>!M.has(a.id)&&!(e&&!sh(a.name).includes(e)))},[r,M,k]),j=o(()=>{const e={};for(const a of n)e[a.id]=oh(i[a.id]).size;return e},[n,i]),U=l(e=>{C(e),I([]),S("")},[]),B=l(e=>{I(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),$=l(()=>{if(0===D.length)return;const e=[...i[_]??[]];for(const a of D){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}),I([]),S(""),R(!1)},[D,i,_,r,d]),q=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:Ni("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:Ni("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(vs,{value:_,onValueChange:U,children:[a(ys,{className:"h-9 text-sm",children:a(xs,{})}),a(_s,{children:n.map(e=>a(ks,{value:e.id,children:t("span",{className:"flex items-center gap-2",children:[e.icon,e.name,j[e.id]>0&&a(Ps,{variant:"secondary",className:"ml-1 text-xs px-1.5 py-0",children:j[e.id]})]})},e.id))})]})]}),!c&&t("div",{className:"flex gap-2",children:[t(ao,{open:T,onOpenChange:R,children:[a(to,{asChild:!0,children:t(Si,{variant:"outline",role:"combobox",className:"flex-1 justify-between h-9 text-sm font-normal text-muted-foreground",children:[D.length>0?`${D.length} selecionado${D.length>1?"s":""}`:v,a(E,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t(ro,{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(O,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Ei,{className:"pl-8 h-8 text-sm",placeholder:g,value:k,onChange:e=>S(e.target.value)})]})}),a(bo,{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=D.includes(e.id);return t("div",{className:Ni("flex items-center gap-3 rounded-sm px-2 py-1.5 text-sm cursor-pointer hover:bg-accent",r&&"bg-accent/50"),onClick:()=>B(e.id),children:[a("div",{className:Ni("flex h-4 w-4 items-center justify-center rounded-sm border border-primary",r&&"bg-primary text-primary-foreground"),children:r&&a(P,{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(Si,{size:"sm",className:"h-9 gap-1",disabled:0===D.length,onClick:$,children:[a(Y,{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:Ni("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(Ps,{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:()=>q(e.id),children:a(A,{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 dh,ch;(ch=dh||(dh={}))[ch.WaitingProcessing=1]="WaitingProcessing",ch[ch.Processing=2]="Processing",ch[ch.Completed=3]="Completed",ch[ch.Error=4]="Error",ch[ch.Expired=5]="Expired";const uh={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 mh(e){const{t:a}=La();return(e??"").normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase()}function ph(e){const{t:a}=La();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=ph,labels:c,className:u}){const{t:m}=La(),p={...uh,...c},[h,f]=s(""),[g,v]=s(!1),[b,x]=s(""),[y,N]=s(""),[w,_]=s(null),C=o(()=>{if(!h)return e;const a=mh(h);return e.filter(e=>mh(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:Ni("space-y-3",u),children:Array.from({length:5}).map((e,t)=>a(ho,{className:"h-12 w-full"},t))}):t(r,{children:[t("div",{className:Ni("space-y-3",u),children:[t("div",{className:"relative max-w-sm",children:[a(O,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Ei,{className:"pl-8 h-9 text-sm",placeholder:p.searchPlaceholder,value:h,onChange:e=>f(e.target.value)})]}),a(bo,{className:"rounded-md border",children:t(pl,{children:[a(hl,{children:t(vl,{children:[a(bl,{className:"min-w-[140px]",children:p.report}),a(bl,{className:"min-w-[150px]",children:p.status}),a(bl,{className:"min-w-[160px]",children:p.requestDate}),a(bl,{className:"min-w-[160px]",children:p.lastUpdate}),a(bl,{className:"min-w-[160px]",children:p.expirationDate}),a(bl,{className:"min-w-[140px]"})]})}),a(fl,{children:0===C.length?a(vl,{children:a(xl,{colSpan:6,className:"text-center text-muted-foreground py-8",children:p.noResults})}):C.map(e=>{const r=function(e){const{t:a}=La();return new Date>new Date(e.expirationDate)&&e.statusId===dh.Completed?dh.Expired:e.statusId}(e),n=function(e,t){const{t:r}=La();switch(e){case dh.WaitingProcessing:return{label:t.statusWaiting,icon:a(aa,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50"};case dh.Processing:return{label:t.statusProcessing,icon:a(ce,{className:"h-3.5 w-3.5 animate-spin"}),variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50"};case dh.Completed:return{label:t.statusCompleted,icon:a(ea,{className:"h-3.5 w-3.5"}),variant:"outline",className:"text-emerald-600 border-emerald-300 bg-emerald-50"};case dh.Error:return{label:t.statusError,icon:a(U,{className:"h-3.5 w-3.5"}),variant:"danger"};case dh.Expired:return{label:t.statusExpired,icon:a(Ze,{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===dh.Completed,s=r===dh.Expired;return t(vl,{children:[a(xl,{className:"font-medium",children:e.reportName}),a(xl,{children:t(Ps,{variant:n.variant,className:Ni("gap-1",n.className),children:[n.icon,n.label]})}),a(xl,{className:"text-sm",children:d(new Date(e.requestDate))}),a(xl,{className:"text-sm",children:d(new Date(e.lastUpdate))}),a(xl,{className:Ni("text-sm",s&&"text-destructive"),children:d(new Date(e.expirationDate))}),a(xl,{children:t(Si,{variant:"ghost",size:"sm",className:"gap-1.5",disabled:!i||w===e.id,onClick:()=>k(e),children:[w===e.id?a(I,{className:"h-4 w-4 animate-spin"}):a(_e,{className:"h-4 w-4"}),p.viewReport]})})]},e.id)})})]})})]}),a(eh,{open:g,onOpenChange:v,url:b,title:y})]})}function fh({reportApiUrl:e,parameters:t={},minHeight:r="80vh",...n}){const i=o(()=>{const a=`${e}/api/reports/v1/Viewer/InitViewer`,r=new URLSearchParams(t).toString();return r?`${a}?${r}`:a},[e,t]);return a(eh,{...n,url:i,minHeight:r})}var gh,vh,bh,xh,yh,Nh,wh,_h,Ch,kh,Sh,Ah,Eh,Dh,Ph,Ih,Th,Rh,Mh,Lh,zh,Fh,jh,Uh,Oh,Bh,$h,qh,Vh,Wh,Hh,Gh,Kh,Yh,Qh,Xh,Jh,Zh,ef,af,tf,rf,nf,sf,of,lf,df,cf,uf,mf,pf;(vh=gh||(gh={})).Count="valuecount",vh.Sum="sum",vh.Average="average",vh.DistinctCount="valuecount_distict",vh.Max="max",vh.Min="min",(bh||(bh={})).ViewAllAnalysis="nes3j6wn",(yh=xh||(xh={})).RegisterDashboards="EeKs7CYA",yh.RemoveDashboards="3GKZYOQ9",yh.ViewAllDashboards="wYBdQNvZ",yh.EditDashboards="bMFcbwv4",(wh=Nh||(Nh={}))[wh.Default=1]="Default",wh[wh.Compact=2]="Compact",(Ch=_h||(_h={}))[Ch.FiveSeconds=1]="FiveSeconds",Ch[Ch.TenSeconds=2]="TenSeconds",Ch[Ch.FifteenSeconds=3]="FifteenSeconds",Ch[Ch.ThirtySeconds=4]="ThirtySeconds",Ch[Ch.OneMinute=5]="OneMinute",Ch[Ch.ThreeMinutes=6]="ThreeMinutes",Ch[Ch.FiveMinutes=7]="FiveMinutes",Ch[Ch.TenMinutes=8]="TenMinutes",(Sh=kh||(kh={}))[Sh.Day=1]="Day",Sh[Sh.Month=2]="Month",Sh[Sh.Year=3]="Year",(Eh=Ah||(Ah={}))[Eh.Ascending=1]="Ascending",Eh[Eh.Descending=2]="Descending",(Ph=Dh||(Dh={}))[Ph.Label=1]="Label",Ph[Ph.Value=2]="Value",(Th=Ih||(Ih={}))[Th.LastSevenDays=1]="LastSevenDays",Th[Th.LastWeek=2]="LastWeek",Th[Th.LastMonth=3]="LastMonth",Th[Th.PreviousQuarter=4]="PreviousQuarter",Th[Th.PreviousSemester=5]="PreviousSemester",Th[Th.LastYear=6]="LastYear",Th[Th.SpecificPeriod=7]="SpecificPeriod",Th[Th.CurrentMonth=8]="CurrentMonth",Th[Th.CurrentSemester=9]="CurrentSemester",Th[Th.CurrentWeek=10]="CurrentWeek",Th[Th.CurrentYear=11]="CurrentYear",(Mh=Rh||(Rh={}))[Mh.Text=1]="Text",Mh[Mh.Area=2]="Area",Mh[Mh.Bar=3]="Bar",Mh[Mh.Column=4]="Column",Mh[Mh.StackedColumn=5]="StackedColumn",Mh[Mh.Line=6]="Line",Mh[Mh.List=7]="List",Mh[Mh.Numeric=8]="Numeric",Mh[Mh.Pareto=9]="Pareto",Mh[Mh.Pie=10]="Pie",Mh[Mh.RiskMatrix=11]="RiskMatrix",Mh[Mh.Burndown=12]="Burndown",Mh[Mh.PerformanceColumns=13]="PerformanceColumns",Mh[Mh.EvolutionLine=14]="EvolutionLine",(zh=Lh||(Lh={}))[zh.NotUpdate=1]="NotUpdate",zh[zh.FiveMinutes=2]="FiveMinutes",zh[zh.TenMinutes=3]="TenMinutes",zh[zh.FifteenMinutes=4]="FifteenMinutes",zh[zh.ThirtyMinutes=5]="ThirtyMinutes",zh[zh.OneHour=6]="OneHour",(jh=Fh||(Fh={}))[jh.NormalPage=1]="NormalPage",jh[jh.Carousel=2]="Carousel",(Oh=Uh||(Uh={}))[Oh.General=0]="General",Oh[Oh.Share=1]="Share",($h=Bh||(Bh={}))[$h.NotShared=1]="NotShared",$h[$h.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",$h[$h.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(Vh=qh||(qh={})).PtBr="pt-br",Vh.EnUs="en",Vh.EsEs="es",(Hh=Wh||(Wh={}))[Hh.Quantity=0]="Quantity",Hh[Hh.AllRisksList=1]="AllRisksList",(Kh=Gh||(Gh={}))[Kh.Five=5]="Five",Kh[Kh.Ten=10]="Ten",Kh[Kh.Fifteen=15]="Fifteen",Kh[Kh.Twenty=20]="Twenty",Kh[Kh.All=0]="All",Kh[Kh.Custom=-1]="Custom",(Qh=Yh||(Yh={}))[Qh.AlphabeticalAsc=1]="AlphabeticalAsc",Qh[Qh.AlphabeticalDesc=2]="AlphabeticalDesc",Qh[Qh.CountAsc=3]="CountAsc",Qh[Qh.CountDesc=4]="CountDesc",Qh[Qh.DateAsc=5]="DateAsc",Qh[Qh.DateDesc=6]="DateDesc",(Jh=Xh||(Xh={}))[Jh.Loading=0]="Loading",Jh[Jh.Loaded=1]="Loaded",Jh[Jh.Error=3]="Error",Jh[Jh.NoData=4]="NoData",Jh[Jh.Unavailable=5]="Unavailable",(ef=Zh||(Zh={}))[ef.Quantity=1]="Quantity",ef[ef.Percentage=2]="Percentage",ef[ef.QuantityPercentage=3]="QuantityPercentage",(tf=af||(af={}))[tf.Program=1]="Program",tf[tf.Project=2]="Project",tf[tf.Action=3]="Action",tf[tf.PerformanceProject=4]="PerformanceProject",tf[tf.PerformanceAction=5]="PerformanceAction",(nf=rf||(rf={})).OccurrenceActionPlans="xebGnSSq",nf.OccurrenceGeneral="UFws4AvH",nf.PlansActionPlans="Kux6CcVC",nf.PlansProgramProjects="UWjrp6Dw",nf.PlansIdeas="3g7vNm2w",nf.RisksGeneral="PZ4b6FhP",nf.RisksActionPlans="xZErDg57",nf.RisksAnalysis="UxsioMbH",nf.RisksIncidences="gNt5IJ2F",nf.MetrologyGeneral="4MfEPbRY",nf.MetrologyActivities="hdFM9XQW",nf.MetrologyServiceOrders="cIrVPdMv",nf.DecisionsGeneral="CopsnHDB",nf.DecisionsItems="qLFAayjx",nf.DecisionsActionPlans="RiQFpxdb",nf.FlowGeneral="AFV98JoG",nf.AuditGeneral="gON8LJPi",nf.AuditPlans="SsCNVOvr",nf.AuditPlansItems="OpPkCCFm",nf.AuditActionPlans="P1oGePhh",nf.CommonGeneral="VVfEzgMQ",nf.ActionPlans="C6Z4MgGa",nf.SuppliersEvaluations="fSCeS4mH",nf.SuppliersGeneral="8qPThkrD",nf.SuppliersEvaluationsCriteria="RiSIStdY",nf.SuppliersDocuments="Riua4jMa",nf.SuppliersMaterialsServices="UpEkatXH",nf.DocumentsGeneral="FRhhEX2J",nf.DocumentsPhysicalCopies="PZLtJ23h",nf.DocumentsObsolete="XDjbga14",nf.FmeaGeneral="aPwf4uPr",nf.FmeaActionPlans="vQ8PMrVX",(of=sf||(sf={}))[of.NotShared=1]="NotShared",of[of.SharedWithAllCollaborators=2]="SharedWithAllCollaborators",of[of.SharedWithUsersGroupsPlacesCollaborators=3]="SharedWithUsersGroupsPlacesCollaborators",(df=lf||(lf={}))[df.All=1]="All",df[df.OnlyMine=2]="OnlyMine",df[df.Favorites=3]="Favorites",(uf=cf||(cf={}))[uf.Current=1]="Current",uf[uf.Inherent=2]="Inherent",(pf=mf||(mf={}))[pf.Default=1]="Default",pf[pf.Pastel=2]="Pastel",pf[pf.Vibrant=3]="Vibrant",pf[pf.Earth=4]="Earth",pf[pf.Ocean=5]="Ocean",pf[pf.Floral=6]="Floral",pf[pf.Night=7]="Night",pf[pf.Winter=8]="Winter",pf[pf.Spring=9]="Spring",pf[pf.Summer=10]="Summer",pf[pf.Fall=11]="Fall",pf[pf.Gray=12]="Gray",pf[pf.Brown=13]="Brown",pf[pf.Blue=14]="Blue",pf[pf.Yellow=15]="Yellow",pf[pf.Green=16]="Green",pf[pf.Purple=17]="Purple",pf[pf.Orange=18]="Orange",pf[pf.Pink=19]="Pink",pf[pf.Red=20]="Red";const hf={jan:1,fev:2,mar:3,abr:4,mai:5,jun:6,jul:7,ago:8,set:9,out:10,nov:11,dez:12},ff={advancedFilter:"analysisDashboardsListFilter"},gf=["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"],vf=["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 bf(e){return e?.sort((e,a)=>{if(!e?.items?.length||!a?.items?.length)return 0;return xf(e.items[0]?.keyDate)-xf(a.items[0]?.keyDate)})}function xf(e){if(!e)return 0;const[a,t]=e.split("/"),r=hf[a?.toLowerCase()]??0;return 12*(parseInt(t)||0)+r}function yf(e){return null==e?.value||""===e.value.trim()}function Nf(e){const a=e.split("/"),t=a[a.length-1];return`${a.slice(0,-1).join("/")}/${encodeURIComponent(t.replace(/[!@#$%^&*()_+={}[\]|\\;:'",.<>?/`~]/g,""))}`}function wf(e){for(const a of vf)if(e[a])return e[a];return null}function _f(e){return e?Cf(e).join("&"):null}function Cf(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(...Cf({[t]:e}))}):"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r||a.push(`${t}=${r}`))}return a}const kf=/^-?\d+(,\d{3})*(\.\d+)?$/;function Sf(e){return!!kf.test(e)&&!isNaN(parseFloat(e.replace(/,/g,"")))}function Af(e){const a=e.replace(/[^\d,.-]/g,"").replace(/\./g,"").replace(",",".");return parseFloat(a)}const Ef=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"});function Df(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 Pf=new Set([Rh.Text]),If=new Set([Rh.Text,Rh.Numeric,Rh.RiskMatrix,Rh.Burndown,Rh.PerformanceColumns]),Tf=new Set([Rh.Text,Rh.RiskMatrix,Rh.Burndown,Rh.PerformanceColumns]);function Rf({config:e,viewOnly:n=!1,complement:i,complementPosition:d="before-options",queryUrlBuilder:c,onRefresh:u,onExport:m,onToggleOnlyMine:p,className:h}){const{t:f}=La(),[g,v]=s(e.onlyMine??!1),b=Pf.has(e.typeId),x=!If.has(e.typeId),y=!Tf.has(e.typeId),N=o(()=>{if(!e.jsonRules||e.typeId===Rh.PerformanceColumns)return!1;try{const a=JSON.parse(e.jsonRules);return a?.rules?.rules?.length>0}catch{return!1}},[e.jsonRules,e.typeId]),w=o(()=>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:Ni("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(Xs,{children:[a(Js,{asChild:!0,children:a("span",{className:"block truncate",children:e.title})}),a(Zs,{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(Ls,{children:[a(zs,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",className:"h-6 w-6",children:a(ta,{className:"h-3.5 w-3.5"})})}),t(qs,{align:"end",className:"w-48",children:[e.canUpdate&&t(Vs,{onClick:()=>e.onEdit?.(e.id),children:[a(H,{className:"mr-2 h-3.5 w-3.5"}),"Editar"]}),!b&&t(Vs,{onClick:u,children:[a(ce,{className:"mr-2 h-3.5 w-3.5"}),"Atualizar"]}),x&&t(Vs,{disabled:e.noData,onClick:m,children:[a(Xe,{className:"mr-2 h-3.5 w-3.5"}),"Exportar"]}),!b&&t(Vs,{disabled:!e.openQueryEnabled,onClick:()=>window.open(w,"_blank"),children:[a(me,{className:"mr-2 h-3.5 w-3.5"}),"Abrir consulta"]}),y&&t(r,{children:[a(Ks,{}),t(Vs,{onClick:_,children:[g&&a(P,{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(Ks,{}),t(Vs,{onClick:()=>e.onDuplicate?.(e.id),children:[a(ue,{className:"mr-2 h-3.5 w-3.5"}),"Duplicar"]}),t(Vs,{className:"text-destructive",onClick:()=>e.onRemove?.(e.id),children:[a(W,{className:"mr-2 h-3.5 w-3.5"}),"Remover"]})]})]})]}),"after-options"===d&&i]})]})}function Mf({config:e,queryUrl:r,className:n}){return t("div",{className:Ni("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",n),children:[a(le,{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 Lf({panelType:e,className:r}){const n=e===Rh.Burndown;return t("div",{className:Ni("flex flex-1 flex-col items-center justify-center gap-2 p-4",r),children:[a(Ts,{className:"h-10 w-10 text-muted-foreground/40"}),n&&a("p",{className:"text-sm text-muted-foreground",children:"Aguarde, processando dados..."})]})}function zf({hasRemovedColumn:r=!1,className:n}){return t("div",{className:Ni("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 Ff({onRemove:e,className:r}){return t("div",{className:Ni("flex flex-1 flex-col items-center justify-center gap-1 p-4 text-center",r),children:[a(le,{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 jf={[gh.Count]:e.t("dashboard_distinct_count").replace("distinta","").trim()||"Count",[gh.Sum]:"Sum",[gh.Average]:e.t("dashboard_average"),[gh.DistinctCount]:e.t("dashboard_distinct_count"),[gh.Max]:e.t("dashboard_max_value"),[gh.Min]:e.t("dashboard_min_value")};function Uf({config:e,state:r,value:n,label:i,viewOnly:s=!1,onClick:o,onRefresh:l,queryUrl:d,queryUrlBuilder:c,className:u}){const{t:m}=La(),p=i??jf[e.aggregationType??""]??"",h=function(e,a){if(null==e)return"—";const t=gf.includes(a.field),r=a.aggregationType===gh.Count||a.aggregationType===gh.DistinctCount;return t&&!r?Ef.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:Ni("flex h-full flex-col",u),children:[a(Rf,{config:e,viewOnly:s,onRefresh:l,queryUrlBuilder:c}),r===Xh.Loading&&a(Lf,{}),r===Xh.Loaded&&t("div",{className:Ni("flex flex-1 flex-col items-center justify-center",o&&"cursor-pointer hover:bg-muted/20 transition-colors"),onClick:o,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===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),r===Xh.Error&&a(Mf,{config:e,queryUrl:d}),r===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}function Of({config:e,state:r,htmlContent:n,viewOnly:i=!1,onRefresh:s,queryUrl:o,queryUrlBuilder:l,className:d}){const c=n??e.textTypeString??"";return t("div",{className:Ni("flex h-full flex-col",d),children:[a(Rf,{config:e,viewOnly:i,onRefresh:s,queryUrlBuilder:l}),r===Xh.Loading&&a(Lf,{}),r===Xh.Loaded&&a("div",{className:"flex-1 overflow-auto px-3 py-2 prose prose-sm max-w-none text-foreground",dangerouslySetInnerHTML:{__html:c}}),r===Xh.Error&&a(Mf,{config:e,queryUrl:o})]})}function Bf({config:e,state:r,data:n=[],columns:i=[],viewOnly:s=!1,onRowClick:d,onRefresh:c,onExport:u,queryUrl:m,queryUrlBuilder:p,enableRowLinks:h=!0,className:f}){const g=o(()=>i.filter(e=>!1!==e.visible),[i]),v=l(e=>{if(d)d(e);else if(h){const a=wf(e);a&&window.open(Nf(a),"_blank")}},[d,h]);return t("div",{className:Ni("flex h-full flex-col",f),children:[a(Rf,{config:e,viewOnly:s,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===Xh.Loading&&a(Lf,{}),r===Xh.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&&!!wf(e);return a("tr",{className:Ni("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):$f(e[t.columnName],t)},t.columnName))},t)})})]})}),r===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),r===Xh.Error&&a(Mf,{config:e,queryUrl:m}),r===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}function $f(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 qf=["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 Vf({config:e,variant:r,state:n,data:i=[],series:s,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:qf,x=o(()=>s?.length?s:[{dataKey:"value",name:e.title}],[s,e.title]),y="bar"===r,N="stacked-column"===r,w=o(()=>{if(c)return e=>c.replace("{value}",e.toLocaleString("pt-BR"))},[c]);return t("div",{className:Ni("flex h-full flex-col",v),children:[a(Rf,{config:e,viewOnly:u,onRefresh:p,onExport:h,queryUrlBuilder:g}),n===Xh.Loading&&a(Lf,{}),n===Xh.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(ft,{width:"100%",height:"100%",children:Wf({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===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),n===Xh.Error&&a(Mf,{config:e,queryUrl:f}),n===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}function Wf({variant:e,data:r,series:n,colors:i,categoryKey:s,isHorizontalBar:o,isStacked:l,yAxisTickFormatter:d,tooltipFormatter:c,onPointClick:u}){const m={tick:{fontSize:11},tickLine:!1,axisLine:!1},p=a(gt,{dataKey:o?void 0:s,type:o?"number":"category",...m,angle:o?0:-45,textAnchor:o?"middle":"end",height:o?void 0:60,tickFormatter:o?d:void 0}),h=a(vt,{dataKey:o?s:void 0,type:o?"category":"number",...m,width:o?100:60,tickFormatter:o?void 0:d}),f=a(bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),g=a(xt,{formatter:c,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),v=n.length>1?a(yt,{wrapperStyle:{fontSize:"11px"}}):null,b=u?(e,a)=>u(r[a],a):void 0;return"bar"===e||"column"===e||"stacked-column"===e?t(Nt,{data:r,layout:o?"vertical":"horizontal",margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(wt,{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(_t,{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(Ct,{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(kt,{data:r,margin:{top:5,right:10,left:0,bottom:5},children:[f,p,h,g,v,n.map((e,t)=>a(St,{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 Hf=["#1f78b4","#33a02c","#e31a1c","#ff7f00","#6a3d9a","#b15928","#a6cee3","#b2df8a","#fb9a99","#fdbf6f","#cab2d6","#ffff99"];function Gf({config:e,state:r,data:n=[],colors:i,viewOnly:s=!1,onSliceClick:l,onRefresh:d,onExport:c,queryUrl:u,queryUrlBuilder:m,className:p}){const h=i?.length?i:e.hexColors?.length?e.hexColors:Hf,f=o(()=>n.map(e=>({...e,name:String(e.key??""),value:e.value??0})),[n]),g=o(()=>f.reduce((e,a)=>e+(a.value??0),0),[f]);return t("div",{className:Ni("flex h-full flex-col",p),children:[a(Rf,{config:e,viewOnly:s,onRefresh:d,onExport:c,queryUrlBuilder:m}),r===Xh.Loading&&a(Lf,{}),r===Xh.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(ft,{width:"100%",height:"100%",children:t(At,{children:[a(Et,{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(Dt,{fill:h[t%h.length]},t))}),a(xt,{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(yt,{wrapperStyle:{fontSize:"11px"}})]})})}),r===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),r===Xh.Error&&a(Mf,{config:e,queryUrl:u}),r===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}function Kf({config:e,state:r,data:n=[],barColor:i,lineColor:s="#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=o(()=>{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:Ni("flex h-full flex-col",h),children:[a(Rf,{config:e,viewOnly:l,onRefresh:c,onExport:u,queryUrlBuilder:p}),r===Xh.Loading&&a(Lf,{}),r===Xh.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(ft,{width:"100%",height:"100%",children:t(Pt,{data:v,margin:{top:5,right:30,left:0,bottom:5},children:[a(bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(gt,{dataKey:"key",tick:{fontSize:11},angle:-45,textAnchor:"end",height:60}),a(vt,{yAxisId:"left",tick:{fontSize:11},tickLine:!1,axisLine:!1}),a(vt,{yAxisId:"right",orientation:"right",tick:{fontSize:11},tickLine:!1,axisLine:!1,tickFormatter:e=>`${e}%`,domain:[0,100]}),a(xt,{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(yt,{wrapperStyle:{fontSize:"11px"}}),a(wt,{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(St,{yAxisId:"right",type:"monotone",dataKey:"cumulativePercent",name:"% Acumulado",stroke:s,strokeWidth:2,dot:{r:3,fill:s}})]})})}),r===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),r===Xh.Error&&a(Mf,{config:e,queryUrl:m}),r===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}function Yf({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:s,executedColor:o="hsl(var(--primary))",plannedColor:l="hsl(var(--chart-2))",viewOnly:d=!1,onRefresh:c,queryUrl:u,queryUrlBuilder:m,className:p}){const{t:h}=La(),f=i??h("dashboard_work_done"),g=s??h("dashboard_work_planned");return t("div",{className:Ni("flex h-full flex-col",p),children:[a(Rf,{config:e,viewOnly:d,onRefresh:c,queryUrlBuilder:m}),r===Xh.Loading&&a(Lf,{panelType:Rh.Burndown}),r===Xh.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(ft,{width:"100%",height:"100%",children:t(_t,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(gt,{dataKey:"date",tick:{fontSize:10},angle:-45,textAnchor:"end",height:50}),a(vt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`,domain:[0,100]}),a(xt,{formatter:e=>`${e}%`,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(yt,{wrapperStyle:{fontSize:"11px"}}),a(Ct,{type:"monotone",dataKey:"executedPercentage",name:f,stroke:o,fill:o,fillOpacity:.2,strokeWidth:2,dot:{r:3}}),a(Ct,{type:"monotone",dataKey:"plannedPercentage",name:g,stroke:l,fill:l,fillOpacity:.1,strokeWidth:2,dot:{r:3}})]})})}),r===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),r===Xh.Error&&a(Mf,{config:e,queryUrl:u}),r===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}function Qf({config:e,state:r,data:n=[],executedLabel:i,plannedLabel:s,executedColor:o="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}=La(),g=i??f("dashboard_work_done"),v=s??f("dashboard_work_planned");return t("div",{className:Ni("flex h-full flex-col",h),children:[a(Rf,{config:e,viewOnly:d,onRefresh:u,queryUrlBuilder:p}),r===Xh.Loading&&a(Lf,{}),r===Xh.Loaded&&a("div",{className:"flex-1 min-h-0 p-2",children:a(ft,{width:"100%",height:"100%",children:t(Nt,{data:n,margin:{top:5,right:10,left:0,bottom:5},children:[a(bt,{strokeDasharray:"3 3",className:"stroke-border/50"}),a(gt,{dataKey:"name",tick:{fontSize:10},angle:-45,textAnchor:"end",height:60}),a(vt,{tick:{fontSize:11},tickFormatter:e=>`${e}%`}),a(xt,{formatter:e=>"number"==typeof e?`${e}%`:e,contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"6px",fontSize:"12px"}}),a(yt,{wrapperStyle:{fontSize:"11px"}}),a(wt,{dataKey:"executedWork",name:g,fill:o,radius:[2,2,0,0],onClick:c?(e,a)=>c(n[a],a):void 0,cursor:c?"pointer":void 0}),a(wt,{dataKey:"plannedWork",name:v,fill:l,radius:[2,2,0,0]})]})})}),r===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),r===Xh.Error&&a(Mf,{config:e,queryUrl:m}),r===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}function Xf({config:e,state:r,rule:n,risks:i=[],matrixViewType:s=Wh.Quantity,viewOnly:l=!1,onCellClick:d,onRiskClick:c,onRefresh:u,queryUrl:m,queryUrlBuilder:p,className:h}){const f=o(()=>[...n?.parametersY??[]].sort((e,a)=>a.position-e.position),[n?.parametersY]),g=n?.parametersX??[],v=o(()=>{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:Ni("flex h-full flex-col",h),children:[a(Rf,{config:e,viewOnly:l,onRefresh:u,queryUrlBuilder:p}),r===Xh.Loading&&a(Lf,{}),r===Xh.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,o)=>{const l=((e,a)=>v[`${a.position}-${e.position}`]??[])(i,e),u=((e,a)=>n?.colorMatrix?.[a]?.[e]??"hsl(var(--muted))")(o,r);return t("div",{className:Ni("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:[s===Wh.Quantity&&l.length>0&&t("span",{className:"text-xs font-semibold",children:[l.length," risco",1!==l.length?"s":""]}),s===Wh.AllRisksList&&l.map(e=>t(Xs,{children:[a(Js,{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(Zs,{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===Xh.NoData&&a(zf,{hasRemovedColumn:e.hasRemovedColumn}),r===Xh.Error&&a(Mf,{config:e,queryUrl:m}),r===Xh.Unavailable&&a(Ff,{onRemove:()=>e.onRemove?.(e.id)})]})}const Jf=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[Jf.Translate.toString(e),Jf.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:a,duration:t,easing:r}=e;return a+" "+t+"ms "+r}}});function Zf(e){switch(e){case Rh.Bar:case Rh.Column:case Rh.Pie:case Rh.List:case Rh.Line:case Rh.Area:case Rh.Text:case Rh.StackedColumn:return{x:4,y:2};case Rh.Pareto:case Rh.RiskMatrix:case Rh.Burndown:case Rh.PerformanceColumns:return{x:8,y:2};case Rh.Numeric:return{x:1,y:1};default:return{x:2,y:2}}}function eg(e){switch(Number(e)){case Rh.Area:case Rh.Bar:case Rh.Column:case Rh.Line:case Rh.Numeric:case Rh.Pie:case Rh.Text:return{x:1,y:1};default:return{x:2,y:2}}}function ag({panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:s,children:l}){const{attributes:d,listeners:c,setNodeRef:u,transform:m,transition:p,isDragging:h}=Ht({id:e.id,disabled:!s}),f=o(()=>({gridColumn:`${e.col+1} / span ${e.sizeX}`,gridRow:`${e.row+1} / span ${e.sizeY}`,minHeight:e.sizeY*n+(e.sizeY-1)*i+"px",transform:Jf.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:Ni("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:Ni("dashboard-panel-drag-handle",s&&"cursor-grab active:cursor-grabbing"),...s?c:{}}),a("div",{className:"h-full",children:l})]})}function tg({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]=s(e);o(()=>{f(e)},[e]);const g=Ut(Ot(Bt,{activationConstraint:{distance:8}})),v=o(()=>0===h.length?1:Math.max(...h.map(e=>e.row+e.sizeY)),[h]),b=o(()=>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],s={...i[r]},o={...i[n]},l=s.col,d=s.row;s.col=o.col,s.row=o.row,o.col=l,o.row=d,i[r]=s,i[n]=o,f(i),m?.(i)},[h,m]),y=o(()=>({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:Ni("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($t,{sensors:g,collisionDetection:qt,onDragEnd:x,children:a(Vt,{items:b,strategy:Wt,children:a("div",{style:y,className:Ni("relative w-full",c&&"bg-muted/30",p),children:h.map(e=>a(ag,{panel:e,columns:r,cellHeight:n,cellGap:i,allowDragging:d,children:u(e.id)},e.id))})})})}const rg={[Rh.Bar]:"bar",[Rh.Column]:"column",[Rh.StackedColumn]:"stacked-column",[Rh.Area]:"area",[Rh.Line]:"line",[Rh.EvolutionLine]:"evolution-line"};function ng({config:e,state:r,data:n,numericValue:i,listColumns:s,cartesianData:o,cartesianSeries:l,burndownData:d,performanceData:c,matrixRule:u,matrixRisks:m,onPanelClick:p}){const h=rg[e.typeId];if(h)return a(Vf,{config:e,variant:h,state:r,data:o,series:l});switch(e.typeId){case Rh.Numeric:return a(Uf,{config:e,state:r,value:i});case Rh.Text:return a(Of,{config:e,state:r});case Rh.List:return a(Bf,{config:e,state:r,data:n,columns:s??[]});case Rh.Pie:return a(Gf,{config:e,state:r,data:n});case Rh.Pareto:return a(Kf,{config:e,state:r,data:n});case Rh.Burndown:return a(Yf,{config:e,state:r,data:d});case Rh.PerformanceColumns:return a(Qf,{config:e,state:r,data:c});case Rh.RiskMatrix:return a(Xf,{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 ig({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}=La(),[A,E]=s(!1),D=e.idViewType===Fh.Carousel,P=o(()=>r,[r,D,i]),I=o(()=>P.map(e=>{const a=eg(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:Xh.Loaded};return t("div",{className:"flex flex-col h-full",children:[a(Rf,{config:n,onRefresh:()=>{}}),a("div",{className:"flex-1 min-h-0 p-2",children:a(ng,{config:n,...i})})]})},[P,T,m,d,x,y,N]);return t("div",{className:Ni("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:Ni("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:Ni("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:Ni("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:Ni("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(tg,{panels:I,allowDragging:d,showGridLines:d,renderPanel:M,onLayoutChange:w})})]})}function sg(e,a=qh.PtBr){const{t:t}=La();switch(a){case qh.EnUs:return e.titleEnUs||e.titlePtBr||e.titleEsEs;case qh.EsEs:return e.titleEsEs||e.titleEnUs||e.titlePtBr;default:return e.titlePtBr||e.titleEnUs||e.titleEsEs}}function og(e){const{t:a}=La();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}const lg=[{value:lf.All,label:"Todos"},{value:lf.OnlyMine,label:e.t("dashboard_my")},{value:lf.Favorites,label:"Favoritos"}];function dg({dashboards:e,limit:n,isLoading:i=!1,language:d=qh.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}=La(),[S,A]=s(""),[E,D]=s(lf.All),[P,I]=s(null),T=l(e=>{A(e),N?.(e)},[N]),R=l(e=>{D(e),w?.(e)},[w]),M=o(()=>{let a=e;if(S){const e=S.toLowerCase();a=a.filter(a=>a.code?.toLowerCase().includes(e)||sg(a,d).toLowerCase().includes(e)||a.responsibleName?.toLowerCase().includes(e))}switch(E){case lf.OnlyMine:break;case lf.Favorites:a=a.filter(e=>e.isFavorite)}return a},[e,S,E,d]);return t("div",{className:Ni("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:Ni("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:Ni("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:lg.map(e=>a("button",{onClick:()=>R(e.value),disabled:i,className:Ni("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:Ni("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:Ni("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:sg(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:og(e.lastModified)}),a("td",{className:"px-3 py-2",children:a("span",{className:Ni("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 cg=[{value:Lh.NotUpdate,label:e.t("dashboard_no_refresh")},{value:Lh.FiveMinutes,label:"5 minutos"},{value:Lh.TenMinutes,label:"10 minutos"},{value:Lh.FifteenMinutes,label:"15 minutos"},{value:Lh.ThirtyMinutes,label:"30 minutos"},{value:Lh.OneHour,label:"1 hora"}],ug=[{value:Fh.NormalPage,label:e.t("dashboard_normal_page")},{value:Fh.Carousel,label:"Carrossel"}],mg=[{value:_h.FiveSeconds,label:"5 segundos"},{value:_h.TenSeconds,label:"10 segundos"},{value:_h.FifteenSeconds,label:"15 segundos"},{value:_h.ThirtySeconds,label:"30 segundos"},{value:_h.OneMinute,label:"1 minuto"},{value:_h.ThreeMinutes,label:"3 minutos"},{value:_h.FiveMinutes,label:"5 minutos"},{value:_h.TenMinutes,label:"10 minutos"}],pg=[{value:Bh.NotShared,label:e.t("dashboard_not_shared"),description:e.t("dashboard_only_responsible")},{value:Bh.SharedWithAllCollaborators,label:e.t("dashboard_shared_unit"),description:e.t("dashboard_all_access")},{value:Bh.SharedWithUsersGroupsPlacesCollaborators,label:e.t("dashboard_select_groups"),description:e.t("dashboard_select_groups")}],hg=[{key:"pt-br",label:"PT-BR"},{key:"en",label:"EN-US"},{key:"es",label:"ES-ES"}];function fg({dashboard:e,initialTab:r=Uh.General,isSaving:n=!1,isQualitfy:i=!1,users:d=[],groups:c=[],places:u=[],collaborators:m=[],onSave:p,onCancel:h,className:f}){const{t:g}=La(),v=!!e,[b,x]=s(r),[y,N]=s({"pt-br":!!e?.titlePtBr||!v,en:!!e?.titleEnUs,es:!!e?.titleEsEs}),[w,_]=s(e?.titlePtBr??""),[C,k]=s(e?.titleEnUs??""),[S,A]=s(e?.titleEsEs??""),[E,D]=s(e?.responsibleId??""),[P,I]=s(e?.isActive??!0),[T,R]=s(e?.idUpdateTime??Lh.NotUpdate),[M,L]=s(e?.idViewType??Fh.NormalPage),[z,F]=s(e?.idPageTime??_h.FifteenSeconds),[j,U]=s(e?.idShare??Bh.NotShared),[O,B]=s(e?.groups??[]),[$,q]=s(e?.places??[]),[V,W]=s(e?.collaborators??[]),H=M===Fh.Carousel,G=y["pt-br"]||y.en||y.es,K=o(()=>!!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:j,groups:j===Bh.SharedWithUsersGroupsPlacesCollaborators?O:[],places:j===Bh.SharedWithUsersGroupsPlacesCollaborators?$:[],collaborators:j===Bh.SharedWithUsersGroupsPlacesCollaborators?V:[]})},[K,n,p,y,w,C,S,E,P,T,M,z,H,j,O,$,V]);return t("div",{className:Ni("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:Ni("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(Uh.General),className:Ni("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===Uh.General?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"Geral"}),a("button",{onClick:()=>x(Uh.Share),className:Ni("px-4 py-2.5 text-sm font-medium border-b-2 transition-colors",b===Uh.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===Uh.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:hg.map(e=>a("button",{onClick:()=>Y(e.key),className:Ni("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:Ni("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:Ni("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:Ni("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:Ni("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:Ni("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:cg.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:Ni("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:Ni("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:Ni("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:ug.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:Ni("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:mg.map(e=>a("option",{value:e.value,children:e.label},e.value))})]})]})]}),b===Uh.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:pg.map(r=>t("label",{className:Ni("flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors",j===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:j===r.value,onChange:()=>U(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))}),j===Bh.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:Ni("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);q(a)},className:Ni("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 (",V.length,")"]}),a("select",{multiple:!0,value:V,onChange:e=>{const a=Array.from(e.target.selectedOptions,e=>e.value);W(a)},className:Ni("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 gg({dashboards:e,limit:r,generalView:n,language:i=qh.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:j,onQuickFilterChange:U,onSetGeneralView:O,viewState:B,onViewStateChange:$,listToolbarExtra:q,viewToolbarActions:V,className:W}){const[H,G]=s({mode:"list"}),K=B??H,Y=l(e=>{$?$(e):G(e)},[$]),Q=o(()=>"view"===K.mode||"edit"===K.mode||"share"===K.mode?e.find(e=>e.id===K.dashboardId)??null:null,[e,K]),[X,J]=s(!1),[Z,ee]=s(g[0]?.id);m(()=>{g.length>0&&!Z&&ee(g[0]?.id)},[g,Z]),m(()=>{if("view"!==K.mode||!Q||Q.idViewType!==Fh.Carousel||g.length<=1)return;const e=function(e){switch(e){case _h.FiveSeconds:return 5e3;case _h.TenSeconds:return 1e4;case _h.FifteenSeconds:return 15e3;case _h.ThirtySeconds:return 3e4;case _h.OneMinute:return 6e4;case _h.ThreeMinutes:return 18e4;case _h.FiveMinutes:return 3e5;case _h.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]),se=l(e=>{"edit"===K.mode||"share"===K.mode?D?.(K.dashboardId,e):E?.(e)},[K,E,D]),oe=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:Ni("flex flex-col h-full",W),children:["list"===K.mode&&a(dg,{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:j,onQuickFilterChange:U,toolbarExtra:q,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(ig,{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:V,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(fg,{users:b,groups:x,places:y,collaborators:N,isSaving:w,onSave:se,onCancel:oe,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:oe,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(fg,{dashboard:Q,initialTab:"share"===K.mode?Uh.Share:Uh.General,users:b,groups:x,places:y,collaborators:N,isSaving:w,isQualitfy:!!Q.isStandard&&!h,onSave:se,onCancel:oe,className:"flex-1"})]})]})}const vg=({manager:n,columns:i,onEdit:s,onView:o,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}=ll(),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)}),j=D||"grid",U="list"===j,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"}[U?1:A],B=L&&z?a(ad,{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:j,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(wl,{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(Al,{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:Ni("grid gap-4",O),children:n.entities.map(e=>{const m=(e=>{const{t:a}=La();return U&&I?I(e):!U&&T?T(e):E?E(e):null})(e);return t(Pl,{children:[a(Il,{asChild:!0,children:m?a("div",{className:"cursor-pointer",onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):s?.(e)},children:m}):a(Ii,{className:Ni("overflow-hidden cursor-pointer hover:bg-muted/50 transition-colors",p&&n.selectedIds.includes(e.id)&&"bg-muted ring-2 ring-primary",U&&"flex-row"),onClick:a=>{a.stopPropagation(),p?n.selectItem(e.id):s?.(e)},children:t(Li,{className:Ni("p-4",U&&"flex items-center gap-4 w-full"),children:[p&&a("div",{className:Ni(U?"":"pt-0.5"),onClick:e=>e.stopPropagation(),children:a(td,{checked:n.selectedIds.includes(e.id),onCheckedChange:()=>n.selectItem(e.id)})}),U?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)))}),(s||o||c)&&a("div",{onClick:e=>e.stopPropagation(),children:c?c(e):a(Hl,{onEdit:s?()=>s(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(td,{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:Ni("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))),(s||o||c)&&a("div",{className:"mt-3 pt-3 border-t flex justify-end",onClick:e=>e.stopPropagation(),children:c?c(e):a(Hl,{onEdit:s?()=>s(e):void 0,onDelete:d?()=>d(e):void 0,onToggleStatus:l?()=>l(e):void 0,isActive:e.is_actived,customActions:u?u(e):[]})})]})]})]})})}),a(jl,{className:"w-[160px]",children:a(Wl,{onEdit:s?()=>s(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 bg({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:D,onToggleExpand:P,defaultExpandAll:I=!1}){const{t:T}=La(),R=h||T("no_items_found",T("no_items_found_empty")),[M,L]=s(()=>I?new Set(e.map(e=>e.id)):new Set),z=void 0!==D,j=z?new Set(D):M,U=l(e=>{z&&P?P(e):L(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[z,P]),{columnWidths:O,isDragging:B,activeColumn:$,handleMouseDown:q}=Yl({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}),V=id({enabled:_&&!!C,onReorder:C??(()=>{})}),W=o(()=>{if(N)return r.map(e=>`${O[String(e.key)]??e.width??e.minWidth??150}px`);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,O]);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(ho,{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:R})})});const H=(g?1:0)+(S?1:0)+r.length+(m?1:0);return a("div",{className:"flex-1 overflow-auto "+(B?"select-none":""),children:t(pl,{className:f,children:[a(hl,{className:"sticky top-0 bg-background z-10",children:t(vl,{children:[S&&a(bl,{className:"w-[40px]"}),g&&a(bl,{className:"w-[40px]",children:a(As,{checked:y,onCheckedChange:x,"aria-label":T("select_all","Selecionar todos")})}),r.map((e,r)=>{const i=N&&!1!==e.resizable,s=$===String(e.key),o=_&&!!C,l=o?V.getDragProps(r):{},u=V.dragFromIndex===r,m=V.dragOverIndex===r&&V.dragFromIndex!==r;return t(bl,{className:Ni(e.className,"relative transition-opacity",e.sortable&&"cursor-pointer",o&&V.isDragging&&"cursor-grabbing",u&&"opacity-50",m&&"border-l-2 border-primary"),style:{width:W[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?te:re,{size:14,className:"ml-1"}))]}):a("span",{className:"font-medium",children:e.header}),i&&a(Dl,{direction:"horizontal",onMouseDown:a=>q(String(e.key),a),isDragging:s})]},String(e.key));var p}),m&&a(bl,{className:"w-[80px] text-right",children:T("actions","Ações")})]})}),a(fl,{children:e.map(e=>{const n=S&&j.has(e.id);return t(i.Fragment,{children:[t(vl,{onClick:()=>u?.(e),className:(u?"cursor-pointer":"")+" relative",children:[S&&a(xl,{className:"w-[40px] px-2",children:a("button",{onClick:a=>{a.stopPropagation(),U(e.id)},className:"p-1 rounded-sm hover:bg-muted transition-colors","aria-label":n?T("collapse_row","Recolher linha"):T("expand_row","Expandir linha"),children:a(n?E:F,{size:16,className:"text-muted-foreground"})})}),g&&a(xl,{children:a(As,{checked:v.includes(e.id),onCheckedChange:()=>b?.(e.id),onClick:e=>e.stopPropagation(),"aria-label":`${T("select_all","Selecionar todos")} ${e.id}`})}),r.map(t=>a(xl,{className:t.className,children:a(El,{children:t.render?t.render(e):String(e[t.key]??"-")})},String(t.key))),m&&a(xl,{className:"text-right",onClick:e=>e.stopPropagation(),children:m(e)})]}),n&&A&&a(vl,{className:"bg-muted/30 hover:bg-muted/30",children:a(xl,{colSpan:H,className:"p-0",children:a("div",{className:"animate-accordion-down overflow-hidden",children:A(e)})})})]},e.id)})})]})})}function xg({onEdit:e,onDelete:r,onToggleStatus:n,isActive:i=!0,canEdit:s=!0,canDelete:l=!0,customActions:d=[],renderAs:c="dropdown",variant:u="default"}){const{t:m}=La(),p=o(()=>{const a=[];return e&&s&&a.push({key:"edit",icon:$,label:m("edit","Editar"),onClick:e,variant:"default"}),n&&a.push({key:"toggle-status",icon:i?q:V,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:W,label:m("remove","Remover"),onClick:r,variant:"destructive"}),a},[e,r,n,i,s,l,d,m]);return 0===p.length?null:"dropdown"===c?a(Qs,{delayDuration:200,children:t(Ls,{children:[a(zs,{asChild:!0,children:a(Si,{variant:"ghost",size:"compact"===u?"sm":"default",className:"compact"===u?"h-7 px-2":"",children:a(S,{size:"compact"===u?14:16})})}),a(qs,{align:"end",className:"bg-background border border-border shadow-lg min-w-[120px]",children:p.map(e=>e.disabled?t(eo,{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(Vs,{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(Si,{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 yg({searchValue:e="",onSearchChange:r,customFilters:n=[],onClearFilters:i,showClearButton:s=!0,layout:o="horizontal"}){const{t:l}=La(),d=e||n.length>0;return t("div",{className:`flex ${"vertical"===o?"flex-col":"flex-row items-center"} gap-2 w-full`,children:[r&&t("div",{className:"relative flex-1 min-w-[200px]",children:[a(O,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Ei,{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"===o?"w-full":"",children:e},t)),s&&d&&i&&t(Si,{variant:"ghost",size:"sm",onClick:i,className:"h-9 px-3 whitespace-nowrap",children:[a(A,{size:14,className:"mr-1"}),l("clear_filters","Limpar filtros")]})]})}function Ng(e,a){const{t:t}=La(),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 wg({children:e,itemId:t,enableDrag:r,onDragStartCell:n,onDragEndCell:i,onDragOverCell:s,onDropCell:o,className:l}){return a(xl,{draggable:r,onDragStart:r?e=>n(t,e):void 0,onDragEnd:r?i:void 0,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDragEnter:e=>{e.preventDefault(),e.stopPropagation(),s(t,e)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),o(t,e)},className:l,children:e})}function _g({item:e,level:n,columns:i,nameKey:s,iconComponent:o,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,D=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(vl,{className:Ni(c&&"cursor-pointer",A&&"group",D&&"opacity-40",P&&"ring-2 ring-primary ring-inset bg-primary/5"),onClick:c?()=>c(e):void 0,children:[a(wg,{...T,children:t("div",{className:"flex items-center gap-2",style:{paddingLeft:`${S}px`},children:[p&&a(As,{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?E:F,{className:"h-4 w-4"})}):a("div",{className:"w-6 shrink-0"}),o??a(fe,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a("span",{className:"truncate",children:String(e[s]??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],s=r.render?r.render(e,n):null!=i?String(i):"—";return a(wg,{...T,className:Ni("text-center",r.className),children:r.hoverContent?t(pu,{openDelay:200,children:[a(hu,{asChild:!0,children:a("span",{className:"cursor-default underline decoration-dotted underline-offset-4 text-foreground",children:s})}),a(fu,{side:"bottom",align:"center",className:"w-auto max-w-xs",children:r.hoverContent(e)})]}):s},String(r.key))}),u&&a(wg,{...T,className:"text-right",children:a("div",{onClick:e=>e.stopPropagation(),className:Ni("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(_g,{item:e,level:n+1,columns:i,nameKey:s,iconComponent:o,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 Cg({onDrop:r,isDragOver:n,onDragOver:i,onDragLeave:s,label:o}){return t("div",{className:Ni("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:s,onDrop:r,children:[a(ra,{className:"h-4 w-4"}),o??e.t("leadership_make_root_short")]})}function kg({data:r,columns:n,nameKey:o,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]=s(null),[M,L]=s(null),[z,F]=s(!1),[j,U]=s(1),O=u(null),B=u([]),$=u(null),q=i.useMemo(()=>new Set(w??[]),[w]),V=i.useMemo(()=>{if(!T||!r)return new Set;const e=B.current.length>0?B.current:[T],a=function(e,a){const{t:t}=La(),r=new Set;for(const n of a)Ng(e,n).forEach(e=>r.add(e));return r}(r,e);return e.forEach(e=>a.add(e)),a},[T,r]),W=u(V);W.current=V;const H=l(()=>{O.current=null,B.current=[],$.current=null,R(null),L(null),F(!1),U(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=q.has(e)&&q.size>1?Array.from(q):[e];O.current=e,B.current=t,$.current=null,R(e),U(t.length),a.dataTransfer.effectAllowed="move",a.dataTransfer.setData("text/plain",e),a.dataTransfer.setData("application/x-tree-ids",JSON.stringify(t))},[q]),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(fe,{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:Ni("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(Cg,{onDrop:X,isDragOver:z,onDragOver:J,onDragLeave:()=>F(!1),label:D}),t(pl,{children:[a(hl,{children:t(vl,{children:[a(bl,{className:"text-left",style:{minWidth:I},children:t("div",{className:"flex items-center gap-2",children:[N&&a(As,{checked:k??!1,onCheckedChange:()=>C?.()}),d]})}),n.map(e=>a(bl,{className:Ni("text-center",e.className),style:e.width?{width:e.width}:void 0,children:e.header},String(e.key))),f&&a(bl,{className:"text-right",style:{width:P},children:g})]})}),a(fl,{children:r.map(e=>a(_g,{item:e,level:0,columns:n,nameKey:o,iconComponent:c,expandedIds:m,onToggleExpand:p,onRowClick:h,renderActions:f,rowActionsVariant:v,enableSelection:N,selectedIds:q,onSelectItem:_,enableRowDrag:S,draggedId:T,dragOverId:M,onDragStartCell:K,onDragEndCell:H,onDragOverCell:Y,onDropCell:Q,dragCount:j},e.id))})]})]})}function Sg(e){const a=Ga();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 Ag(e,a){const t=Sg({basePath:e,newPath:a.newPath,editPath:a.editPath});return{useCustomRouting:!0,onNew:t.onNew,onEdit:t.onEdit}}const Eg=[{value:"pt-BR",label:"Português (Brasil)"},{value:"en-US",label:"English (US)"},{value:"es-ES",label:"Español"}],Dg=({open:e,onOpenChange:r,user:n,userPhotoUrl:i,userInitials:o})=>{const{t:l,i18n:d}=La(),c=u(null),[m,p]=s(null),[h,f]=s(d.language||"pt-BR"),g=m||i,v=e=>{e||(p(null),f(d.language||"pt-BR")),r(e)};return a(Yi,{open:e,onOpenChange:v,children:t(as,{className:"sm:max-w-md",children:[a(ts,{children:a(is,{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",children:t(Uc,{className:"w-16 h-16",children:[g&&a(Oc,{src:g,alt:n.name||""}),a(Bc,{className:"bg-primary text-primary-foreground font-semibold text-lg",children:o})]})}),t("div",{children:[t(Si,{variant:"outline",size:"sm",onClick:()=>c.current?.click(),children:[a(na,{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(Pi,{children:l("language","Idioma")}),t(vs,{value:h,onValueChange:f,children:[a(ys,{children:a(xs,{})}),a(_s,{children:Eg.map(e=>a(ks,{value:e.value,children:e.label},e.value))})]})]})]}),t(ns,{children:[a(Si,{variant:"outline",onClick:()=>v(!1),children:l("cancel","Cancelar")}),a(Si,{onClick:()=>{h!==d.language&&d.changeLanguage(h),r(!1)},children:l("save","Salvar")})]})]})})},Pg="true"===import.meta.env.VITE_SHOW_EDIT_PROFILE,Ig=i.memo(({variant:e="card",className:n="",selectedUnit:l,onUnitChange:d})=>{const{t:c}=La(),{user:u,companies:m,alias:p,isAuthenticated:h,logout:f,switchUnit:g}=ll(),{role:v}=kc(),b=v?.name||null,x=m?.[0]||null,y=p?m?.find(e=>e.alias===p):x,N=m||[],w=l||y||x||x,_=o(()=>{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=o(()=>{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,D]=s(!1);if(!h||!u)return null;return"dropdown"===e?t(r,{children:[t(Ls,{children:[a(zs,{asChild:!0,children:a(Si,{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(Uc,{className:"w-8 h-8 border border-primary-foreground/30",children:[_&&a(Oc,{src:_,alt:u.name||c("user_photo")}),a(Bc,{className:"bg-primary-foreground/20 text-primary-foreground font-semibold text-xs",children:C||a(fe,{className:"h-4 w-4"})})]}),a(E,{className:"h-4 w-4"})]})})}),t(qs,{className:"w-56 bg-background border border-border shadow-lg z-50",align:"end",children:[t(Us,{children:[t(Bs,{children:[a(ce,{className:"mr-2 h-4 w-4"}),"Alterar Unidade"]}),a($s,{children:S.map(e=>t(Vs,{onClick:()=>k(e),className:e.alias===w?.alias?"bg-muted":"",children:[a(he,{className:"mr-2 h-4 w-4"}),e.name,e.alias===w?.alias&&a(Ps,{variant:"outline",className:"ml-2 text-xs",children:"Atual"})]},e.alias))})]}),Pg&&t(r,{children:[a(Ks,{}),t(Vs,{onClick:()=>D(!0),children:[a(ia,{className:"mr-2 h-4 w-4"}),c("edit_profile","Editar Perfil")]})]}),a(Ks,{}),t(Vs,{onClick:f,children:[a(ge,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]}),Pg&&a(Dg,{open:A,onOpenChange:D,user:u,userPhotoUrl:_,userInitials:C})]}):t(Ii,{className:n,children:[a(Ti,{children:a(Ri,{className:"text-lg",children:c("user_info")})}),t(Li,{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(Uc,{className:"w-10 h-10",children:[_&&a(Oc,{src:_,alt:u.name||c("user_photo")}),a(Bc,{className:"bg-primary text-primary-foreground text-white font-semibold text-sm",children:C||a(fe,{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(he,{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(Ps,{variant:e.alias===w?.alias?"default":"secondary",className:"text-xs cursor-pointer",onClick:()=>k(e),children:e.name},e.alias)),S.length>3&&t(Ps,{variant:"outline",className:"text-xs",children:["+",S.length-3]})]})]})]}),{}),a(Fi,{}),t(Si,{variant:"outline",onClick:f,size:"sm",className:"w-full",children:[a(ge,{className:"mr-2 h-4 w-4"}),"Sair"]})]})]})}),Tg=d({});function Rg({children:e,config:t}){const r=o(()=>{const e=er(),a=t?.appName?e?`${t.appName} (Dev)`:t.appName:void 0;return{navigation:t?.navigation,appName:a}},[t?.navigation,t?.appName]);return a(Tg.Provider,{value:r,children:e})}function Mg(){return c(Tg)}function Lg(){const e=Ka(),{navigation:a}=Mg();return zg(a,e.pathname)}function zg(e,a){if(!e)return"Página";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||"Página"}function Fg(e,a){const[t,r]=s(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 jg({appName:e}){const[n,i]=s(!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:hr.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(E,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return t(r,{children:[s," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(E,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]})]})})(e)})})]}),a(Ac,{open:n,onOpenChange:i})]})}const Ug=p(function({actions:r}){const n=Ka(),i=Ga(),{navigation:o,appName:d}=Mg(),c=zg(o,n.pathname),{metadata:u,headerActions:p}=Wd(),{setOpenMobile:h}=xm(),{companies:f,alias:g,isSearchVisible:v,clearSearch:b,refreshData:x,switchUnit:y}=ll(),N=g?f?.find(e=>e.alias===g)||f?.[0]||null:f?.[0]||null,[w,_]=Wa(),C=l(e=>{const{pathname:a,search:t,hash:r}=n;if(g){const n=a.split("/"),s=n.indexOf(g);if(s>=0)return n[s]=e.alias,void i(n.join("/")+t+r)}y(e)},[g,n,i,y]),[k,S]=s(()=>w.get("search")||""),[E,D]=Fg(k,rr.debounceDelay);m(()=>{if(!v)return;const e=new URLSearchParams(w);E?(e.set("search",E),e.set("page","1")):e.delete("search"),_(e)},[E,_,v]);const P=o?.find(e=>e.path===n.pathname)||o?.find(e=>n.pathname.startsWith(e.path+"/")),I=u.title||c,T=u.subtitle||P?.complementaryText||e.t("item_details");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(Si,{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(sa,{size:20})}),a("div",{className:"hidden md:flex items-center flex-shrink-0",children:a(jg,{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(F,{className:"h-3 w-3"}),e.href?a(Qa,{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(O,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4"}),a(Ei,{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(Si,{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(A,{size:14})})]}),a(Si,{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(ce,{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(Si,{variant:"ghost",size:"sm",className:"h-8 px-3 text-primary-foreground hover:text-primary-foreground hover:bg-primary-foreground/10",onClick:e=>xi(import.meta.env.VITE_WIKI_URL,e),title:e.t("open_wiki"),children:"Wiki"}),a(Op,{}),a("div",{className:"text-sm",children:a(Ig,{variant:"dropdown",selectedUnit:N,onUnitChange:C})})]})]})})}),Og=({key:e,enabled:a,checkFn:t,staleTime:r=3e5,gcTime:n=6e5})=>Ba({queryKey:["permission",e],queryFn:t,enabled:a,staleTime:r,gcTime:n,retry:0,refetchOnWindowFocus:!1});function Bg({config:e,isCollapsed:n=!1,isDisabled:i=!1,className:s}){const{t:o}=La(),{actions:l,triggerLabel:d="Criar",triggerIcon:c=Y,variant:u="button"}=e;if(!l||0===l.length)return null;if("split-button"===u){const e=l[0],r=e.icon||c,o=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(Si,{onClick:e.onClick,disabled:i||e.disabled,className:Ni("justify-center px-2 w-full",s),variant:"outline",size:"default",children:a(r,{className:"h-4 w-4 shrink-0"})});return t(Xs,{children:[a(Js,{asChild:!0,children:n}),a(Zs,{side:"right",children:a("p",{children:e.label})})]})}return a(Ap,{label:e.label,onClick:e.onClick,icon:r,actions:o,variant:"outline",disabled:i||e.disabled,className:Ni("w-full",s),menuAlign:"start"})}const m=(e,i,s=!1)=>t(r,{children:[e,!n&&i&&a("span",{className:"truncate",children:i}),!n&&s&&a(E,{className:"ml-auto h-4 w-4 shrink-0"})]});if(!(l.length>1)){const e=l[0],r=e.icon||c,o=i||e.disabled,d=a(Si,{onClick:e.onClick,disabled:o,className:Ni("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:m(a(r,{className:"h-4 w-4 shrink-0"}),e.label)});return n?t(Xs,{children:[a(Js,{asChild:!0,children:d}),a(Zs,{side:"right",children:a("p",{children:e.label})})]}):d}const p=a(Si,{disabled:i,className:Ni("w-full gap-2 justify-start",n&&"justify-center px-2",s),variant:"outline",size:"default",children:m(a(c,{className:"h-4 w-4 shrink-0"}),d,!0)});return t(Ls,{children:[a(zs,{asChild:!0,children:n?t(Xs,{children:[a(Js,{asChild:!0,children:p}),a(Zs,{side:"right",children:a("p",{children:d})})]}):p}),a(qs,{align:"start",side:n?"right":"bottom",className:"w-56 bg-popover",children:l.map(e=>{const r=e.icon;return t(Vs,{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 $g="forlogic-sidebar-pinned",qg=()=>{try{const e=localStorage.getItem($g);return!!e&&JSON.parse(e)}catch{return!1}};function Vg({direction:e="right",minWidth:a=224,maxWidth:t=384,defaultWidth:r=290,storageKey:n="sidebar-width",onResize:i,isOpen:o=!0}={}){const[d,c]=s(()=>{if("undefined"==typeof window)return r;const e=localStorage.getItem(n);return e?parseInt(e):r}),[p,h]=s(!1),f=u(null);m(()=>{const e=document.querySelector(".sidebar-container");e&&e instanceof HTMLElement&&(o?e.style.setProperty("--sidebar-width",`${d}px`):e.style.setProperty("--sidebar-width","290px"))},[d,o]);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)},s=()=>{h(!1),c(e=>(localStorage.setItem(n,e.toString()),e))};return document.addEventListener("mousemove",r),document.addEventListener("mouseup",s),()=>{document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",s)}},[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 Wg=d(void 0);function Hg({children:e}){const[t,r]=s(new Set),[n,i]=s(!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=o(()=>t.size>0||n,[t,n]),p=o(()=>({openModals:t,hasOpenModal:m,registerModal:d,unregisterModal:c,setHasOpenModal:u}),[t,m,d,c,u]);return a(Wg.Provider,{value:p,children:e})}function Gg(){const e=c(Wg);return e||{openModals:new Set,hasOpenModal:!1,registerModal:()=>{},unregisterModal:()=>{},setHasOpenModal:()=>{}}}function Kg(){const{hasOpenModal:e}=Gg();return e}function Yg({config:e,customContent:r,resizable:n=!1,minWidth:i=224,maxWidth:o=384}={}){const{t:d}=La(),{open:c,setOpen:u,setOpenMobile:p}=xm(),h=Ka(),{alias:f,user:g}=ll(),{appName:v}=Mg(),{hasOpenModal:b}=Gg(),[x,y]=s(qg),N=ml(),w=!!N||c,_=l(()=>{N&&p(!1)},[N,p]),C=n?Vg({minWidth:i,maxWidth:o,storageKey:"app-sidebar-width",isOpen:c}):null;m(()=>{u(!!x)},[x,u]);const k=e=>h.pathname===e||h.pathname.startsWith(e+"/");return t(Nm,{collapsible:"icon",className:Ni("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(Qs,{children:a(Bg,{config:e.moduleActions,isCollapsed:!w,isDisabled:b})})}),a(Dm,{className:Ni(e?.moduleActions&&e.moduleActions.actions.length>0?"pt-0":"pt-3"),children:r||a(Pm,{className:"p-0",children:a(Rm,{children:a(Mm,{className:"gap-1",children:a(Qs,{children:e?.navigation?.map((e,r)=>{if("separator"===e.type)return a(Em,{className:"my-2"},`sep-${r}`);const n=({item:e,index:r})=>{const i=`${e.path}-${r}-${f??"noalias"}-${g?.id??"nouser"}`,{data:s=!0,isLoading:o}=Og({key:i,enabled:Boolean(e.permissionCheck&&f&&g?.id),checkFn:e.permissionCheck||(()=>Promise.resolve(!0))}),l=e.permissionCheck&&!s,c=o?I:l?We:e.icon;l?d("restricted_access"):e.complementaryText;return e.children&&e.children.length>0?w?a(oc,{defaultOpen:!0,className:"group/collapsible",children:t(Lm,{children:[a(lc,{asChild:!0,children:a(Fm,{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(F,{className:"ml-auto h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-90"})]})})}),a(dc,{children:a(Bm,{children:e.children.map((e,t)=>a(n,{item:e,index:t},e.path))})})]})},e.path):a(Lm,{children:t(Xs,{children:[a(Js,{asChild:!0,children:a("div",{className:Ni("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(Zs,{side:"right",children:a("p",{children:e.label})})]})},e.path):a(Lm,{children:l||o?t(Xs,{children:[a(Js,{asChild:!0,children:w?a(Fm,{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 "+(o?"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 "+(o?"animate-spin":"")})})}),a(Zs,{side:"right",children:a("p",{children:o?"Verificando acesso...":d("restricted_access")})})]}):w?a(Fm,{asChild:!0,isActive:k(e.path),size:"default",children:t(Qa,{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(Xs,{children:[a(Js,{asChild:!0,children:a(Qa,{to:e.path,onClick:_,className:Ni("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(Zs,{side:"right",children:a("p",{children:e.label})})]})},e.path)};return a(n,{item:e,index:r},e.path)})})})})})}),!N&&a("div",{className:Ni("mt-auto pb-4 pt-2 flex",c?"justify-end":"justify-center"),children:t(Xs,{children:[a(Js,{asChild:!0,children:a("button",{onClick:()=>{const e=!x;y(e),(e=>{try{localStorage.setItem($g,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?ie:F,{className:"h-3.5 w-3.5 text-primary-foreground"})})}),a(Zs,{side:"right",children:a("p",{children:c?"Recolher":"Expandir"})})]})}),n&&C&&w&&a("div",{ref:C.dragRef,onMouseDown:C.handleMouseDown,className:Ni("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 Qg=p(function({children:e,sidebar:r,sidebarConfig:n,showHeader:i=!0}){const s=o(()=>r||a(Yg,{config:n}),[r,n]),d=o(()=>({"--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(Rg,{config:n,children:a(Vd,{children:a(ym,{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(Ug,{})}),t("div",{className:"sidebar-container flex flex-1 overflow-hidden",children:[s,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 Xg({open:e,appName:n}){const[i,o]=s(!1);return t(r,{children:[a(Sm,{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:()=>o(!0),children:a("img",{src:hr.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:()=>o(!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(E,{size:12,className:"inline-block align-middle ml-1 opacity-60 text-primary-foreground"})]});const i=n[n.length-1],s=n.slice(0,-1).join(" ");return t(r,{children:[s," ",t("span",{className:"whitespace-nowrap",children:[i," ",a(E,{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:()=>o(!0),children:a("img",{src:hr.smallLogo,alt:"Logo",className:"h-6 w-auto object-contain"})})})}),a(Ac,{open:i,onOpenChange:o})]})}function Jg({title:e,subtitle:r,children:n,className:i,hasHeader:s=!0}){const o=e||r;return t("div",{className:Ni("bg-white dark:bg-card","rounded-lg","shadow-sm","border border-border/40","overflow-visible",i),children:[s&&o&&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:Ni("p-6",!s&&o&&"pt-4"),children:n})]})}function Zg({breadcrumbs:e,children:r,className:i}){return t("div",{className:Ni("bg-neutral-100 dark:bg-neutral-900","h-full overflow-y-auto","p-6",i),children:[e&&e.length>0&&a($c,{className:"mb-4",children:a(qc,{children:e.map((r,i)=>{const s=i===e.length-1;return t(n.Fragment,{children:[i>0&&a(Gc,{}),a(Vc,{children:s||!r.href?a(Hc,{children:r.label}):r.asChild&&r.children?a(Wc,{asChild:!0,children:r.children}):a(Wc,{asChild:!0,children:a(Qa,{to:r.href||"/",children:r.label})})})]},`${r.label}-${i}`)})})}),a("div",{className:"space-y-6",children:r})]})}const ev=(e={})=>{const{enabled:a=!0}=e,{alias:t}=ll();return Ba({queryKey:["active-modules",t],queryFn:async()=>{if(!t)return[];const e=Oo(),{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(!qo.handleError(r))throw r;return[]}return a||[]},enabled:a&&!!t})};function av({rowIds:e,defaultHeight:a=48,minHeight:t=32,maxHeight:r=120,storageKey:n,onResize:i,enabled:o=!0}){const[d,c]=s(()=>{if(!o||"undefined"==typeof window)return{};if(n){const e=localStorage.getItem(n);if(e)try{return JSON.parse(e)}catch{}}return{}}),[p,h]=s(!1),[f,g]=s(null),v=u(0),b=u(0),x=l(e=>d[e]??a,[d,a]),y=l((e,t)=>{o&&(t.preventDefault(),t.stopPropagation(),h(!0),g(e),v.current=t.clientY,b.current=d[e]??a)},[o,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 tv(e){const{steps:a,initialStep:t=0,initialData:r={},onComplete:n,onCancel:i}=e,[d,c]=s(t),[u,m]=s(r),[p,h]=s(!1),[f,g]=s(!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]),_=o(()=>w(),[w,u]),C=o(()=>!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 rv(...e){return Object.assign({},...e)}const nv=()=>{const{locale:e,timezone:a}=rc(),t=ri;return{formatDatetime:r=>gi(r,t,a,e),formatDate:t=>vi(t,e,a),locale:e,timezone:a,datetimeFormat:t}};class iv{static async sendEmail(e){const a=Oo(),{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 sv=iv;function ov({open:e,onOpenChange:r,placeId:n,placeName:i,onMakeManager:l,onMakeMembers:d,currentManagerId:c,currentMemberIds:u=[]}){const{t:m}=La(),[p,h]=s([]),[f,g]=s(!1),[v,b]=s(""),{data:x=[],isLoading:y}=gd({enabled:e}),N=o(()=>{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(Yi,{open:e,onOpenChange:r,children:t(as,{className:"max-w-2xl",variant:"form",children:[a(ts,{showSeparator:!0,children:t(is,{className:"flex items-center gap-2",children:[a(Je,{className:"h-5 w-5"}),"Gerenciar Acessos - ",i]})}),t(rs,{children:[t("div",{className:"relative mb-4",children:[a(O,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),a(Ei,{placeholder:"Pesquisar...",value:v,onChange:e=>b(e.target.value),className:"pl-9"})]}),a(bo,{className:"h-[400px] pr-4",children:y?a("div",{className:"space-y-2",children:[...Array(5)].map((e,t)=>a(ho,{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(Je,{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:Ni("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(As,{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(oa,{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(ns,{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(Si,{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(oa,{className:"h-4 w-4 mr-2"}),"Tornar Gestor"]}),C&&d&&t(Si,{onClick:async()=>{if(d&&0!==p.length){g(!0);try{await d(p,n),h([])}finally{g(!1)}}},disabled:f,children:[a(la,{className:"h-4 w-4 mr-2"}),"Tornar ",p.length>1?"Membros":"Membro"]})]})]})})}function lv({place:e,level:r=0,manageAccessConfig:n}){const{t:i}=La(),[o,l]=s(!1),[d,c]=s(!1),u=e.subPlaces&&e.subPlaces.length>0,m=e.isActive??!0,p=e.usersCount??0;return t("div",{children:[t(oc,{open:o,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(lc,{className:"flex items-center gap-2 flex-1",children:[a(F,{className:Ni("h-4 w-4 transition-transform shrink-0",o&&"rotate-90")}),a(he,{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(he,{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(Je,{className:"h-3.5 w-3.5 text-muted-foreground"}),a("span",{className:"text-sm text-muted-foreground",children:p})]}),a(Ps,{variant:m?"default":"secondary",className:"text-xs",children:m?"Ativo":"Inativo"}),n&&a(xg,{customActions:[{label:i("manage_access"),icon:da,onClick:()=>c(!0),variant:"default"}],renderAs:"dropdown",variant:"compact"})]})]}),u&&a(dc,{children:e.subPlaces.map(e=>a(lv,{place:e,level:r+1,manageAccessConfig:n},e.id))})]}),0===r&&a(Fi,{}),n&&a(ov,{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 dv({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(lv,{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(he,{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 cv=new class{get baseUrl(){return or()}async makeApiCall(e,a,t){const r=Vo.validateToken();if(!r.valid)throw new Error(r.message||"Token inválido");const n=Lo.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 s=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json",Accept:"application/json","un-alias":t}});if(!s.ok){const e=new Error(`API call failed: ${s.status}`);throw e.status=s.status,e}return s.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 Vo.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 zo.handleError(r instanceof Error?r:"Erro ao buscar locais após renovação de token",!0),[]}return zo.handleError(t instanceof Error?t.message:"Erro ao buscar locais",!0),[]}}};function uv(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 mv(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 pv(e){const a=[],t=e=>{a.push(e),e.children.forEach(t)};return e.forEach(t),a}function hv(){const{alias:a,isAuthenticated:t}=ll(),r=Lo.getAccessToken(),{data:n=[]}=gd({enabled:!0});return Ba({queryKey:["leadership",a],queryFn:async()=>{if(!r||!a)throw new Error("Usuário não autenticado ou unidade não selecionada");const t=Oo(),{data:i,error:s}=await t.schema("common").from("leaders").select("*").eq("is_removed",!1).eq("alias",a);if(s)throw new Error("Erro ao buscar hierarquia de liderança");if(!i||0===i.length)return[];const o={};n.forEach(e=>{o[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:o[a.id_user]?.name||e.t("inactive_user"),email:o[a.id_user]?.email||"",subordinatesCount:t.length,subordinateNames:t.map(e=>o[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=o[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=>o[e.id_user]?.name||"[Usuário inativo]").sort((e,a)=>e.localeCompare(a))})}),mv(l)},enabled:!!r&&!!a&&t&&n.length>0})}import.meta.env.VITE_SUPABASE_URL,import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;const fv="common";function gv(){const{alias:e}=ll(),a=Oa(),t=Oo(),{t:r}=La();return $a({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 Nv(t,e,a.id_user,a.id_leader);const{data:n,error:i}=await t.schema(fv).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 vv(){const{alias:e}=ll(),a=Oa(),t=Oo(),{t:r}=La();return $a({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(fv).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 Nv(t,e,d.id_user,a.id_leader)}const s=a.users.map(t=>({alias:e,id_user:t.id_user,id_leader:a.id_leader,is_active:!0,is_removed:!1})),{data:o,error:l}=await t.schema(fv).from("leaders").insert(s).select();if(l)throw l;return o},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 bv(){const{alias:e}=ll(),a=Oa(),t=Oo(),{t:r}=La();return $a({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{data:n}=await t.schema(fv).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 Nv(t,e,n.id_user,a.id_leader,a.id);const{data:i,error:s}=await t.schema(fv).from("leaders").update({id_leader:a.id_leader}).eq("id",a.id).eq("alias",e).select().single();if(s)throw s;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 xv(){const{alias:e}=ll(),a=Oa(),t=Oo(),{t:r}=La();return $a({mutationFn:async a=>{if(!e)throw new Error(r("unit_not_selected","Unidade não selecionada"));const{error:n}=await t.schema(fv).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 yv(){const{alias:e}=ll(),a=Oa(),t=Oo(),{t:r}=La();return $a({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),s=await Promise.all([t.schema(fv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).eq("id_leader",a),t.schema(fv).from("leaders").select("id, id_user, id_leader").eq("alias",e).eq("is_removed",!1).in("id_user",i.length?i:["__none__"])]),[{data:o,error:l},{data:d,error:c}]=s;if(l)throw l;if(c)throw c;const u=o||[],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 Nv(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 Nv(t,e,y.id_user,a)}const b=[];if(h.length){const a=h.map(e=>e.id);b.push(t.schema(fv).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(fv).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(fv).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 Nv(a,t,r,n,i){const{data:s,error:o}=await a.schema(fv).from("leaders").select("id, id_user, id_leader").eq("alias",t).eq("is_removed",!1);if(o)throw o;const l=i?s.filter(e=>e.id!==i):s,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 wv=function(e,a){for(var t={};e.length;){var r=e[0],n=r.code,i=r.message,s=r.path.join(".");if(!t[s])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];t[s]={message:o.message,type:o.code}}else t[s]={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[s].types,d=l&&l[r.code];t[s]=Ea(s,a,t,n,d?[].concat(d,r.message):r.message)}e.shift()}return t},_v=function(e,a,t){return void 0===t&&(t={}),function(r,n,i){try{return Promise.resolve(function(n,s){try{var o=Promise.resolve(e["sync"===t.mode?"parse":"parseAsync"](r,a)).then(function(e){return i.shouldUseNativeValidation&&Kt({},i),{errors:{},values:t.raw?r:e}})}catch(l){return s(l)}return o&&o.then?o.then(void 0,s):o}(0,function(e){if(function(e){return Array.isArray(null==e?void 0:e.errors)}(e))return{values:{},errors:Yt(wv(e.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)};throw e}))}catch(s){return Promise.reject(s)}}};const Cv=Gt.object({id_leader:Gt.string().nullable(),id_users:Gt.array(Gt.string()).min(1,e.t("leadership_select_subordinates"))}),kv=Gt.object({id_leader:Gt.string().nullable(),id_users:Gt.array(Gt.string())});function Sv({value:r,onChange:n,excludeUserIds:i=[],error:o}){const{data:l=[],isLoading:d}=gd(),[c,p]=s(""),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||"",s=a.userName||a.userEmail||"";return i.localeCompare(s)});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(I,{className:"h-6 w-6 animate-spin"}),a("span",{className:"ml-2",children:"Carregando dados..."})]}:{className:"space-y-2",children:[a(Ei,{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(As,{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(Pi,{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)"]}),o&&a("p",{className:"text-sm text-destructive",children:o})]})}function Av({leader:n,prefilledLeaderId:i,onSuccess:o}){const{t:l}=La(),{alias:d}=ll(),c=!!n,u=n?.id.startsWith("virtual-"),p=vv(),h=gv(),f=bv(),g=yv(),v=xv(),{data:b=[]}=hv(),{data:x=[]}=gd(),[y,N]=s(""),w=pv(b).map(e=>e.id_user),_=c?pv(b).filter(e=>e.id_leader===n.id_user).map(e=>e.id_user):[],C=Da({resolver:_v(c?kv:Cv),defaultValues:{id_leader:i||(c?n?.id_leader:null)||null,id_users:c?_:[]}});m(()=>{if(n){const e=pv(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})}o?.()}catch(a){}}),className:"space-y-4",children:[c&&t("div",{children:[a(Pi,{children:e.t("leader")}),a(Ei,{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(Pi,{children:l("leadership_immediate_superior")}),t(vs,{value:S||"none",onValueChange:e=>C.setValue("id_leader","none"===e?null:e),children:[a(ys,{children:a(xs,{placeholder:"Selecione..."})}),t(_s,{children:[a("div",{className:"sticky top-0 z-10 bg-background p-2 border-b",children:a(Ei,{placeholder:"Buscar superior...",value:y,onChange:e=>N(e.target.value),onKeyDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),className:"h-8"})}),t(bo,{className:"h-[200px]",children:[a(ks,{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(ks,{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(Pi,{children:"Subordinados *"}),a(Sv,{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(Si,{type:"submit",disabled:k||!c&&0===A.length,children:k&&!v.isPending?t(r,{children:[a(I,{className:"mr-2 h-4 w-4 animate-spin"}),c?"Atualizando...":"Salvando..."]}):c?"Atualizar":"Criar"}),c&&!S&&0===A.length&&t(ji,{children:[a(Ui,{asChild:!0,children:a(Si,{type:"button",variant:"destructive",disabled:k,className:"ml-auto",children:v.isPending?t(r,{children:[a(I,{className:"mr-2 h-4 w-4 animate-spin"}),"Removendo..."]}):t(r,{children:[a(W,{className:"mr-2 h-4 w-4"}),"Remover"]})})}),t($i,{children:[t(qi,{children:[a(Wi,{children:l("confirm_removal")}),a(Hi,{children:"Tem certeza que deseja remover este líder? Esta ação não pode ser desfeita."})]}),t(Vi,{children:[a(Ki,{children:l("cancel")}),a(Gi,{onClick:async()=>{if(n)try{await v.mutateAsync(n.id),o?.()}catch(e){}},children:l("remove")})]})]})]})]})]})}function Ev({open:e,onOpenChange:r,leader:n,prefilledLeaderId:i,title:s}){return a(Yi,{open:e,onOpenChange:r,children:t(as,{variant:"form",className:"sm:max-w-[500px]",children:[a(ts,{showSeparator:!0,children:a(is,{children:s})}),a(rs,{children:a(Av,{leader:n,prefilledLeaderId:i,onSuccess:()=>r(!1)})})]})})}const Dv="leadership-expanded-nodes",Pv=(e,a)=>{const{t:t}=La();try{localStorage.setItem(`${Dv}-${e}`,JSON.stringify(Array.from(a)))}catch{}};function Iv({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}=ll(),{data:g,isLoading:v,error:b,refetch:x}=hv(),y=bv(),N=gv(),[w,_]=s(()=>f?(e=>{try{const a=localStorage.getItem(`${Dv}-${e}`);if(a)return new Set(JSON.parse(a))}catch{}return new Set})(f):new Set),[C,k]=s([]),[S,A]=s(new Set),[D,P]=s(!0),[I,T]=s(!1),[R,M]=s(),[L,z]=s(null),j=o(()=>g?pv(g):[],[g]),U=o(()=>j.map(e=>e.id),[j]),O=U.length>0&&C.length===U.length,B=j.filter(e=>e.children.length>0).every(e=>w.has(e.id));m(()=>{if(g&&g.length>0&&f){if(!localStorage.getItem(`${Dv}-${f}`)){const e=g.map(e=>e.id),a=new Set(e);_(a),Pv(f,a)}}},[g,f]);const $=l(e=>{_(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),f&&Pv(f,t),t})},[f]),q=l(()=>{if(B){const e=new Set;_(e),f&&Pv(f,e)}else{const e=new Set(j.filter(e=>e.children.length>0).map(e=>e.id));_(e),f&&Pv(f,e)}},[B,j,f]),V=l(e=>{k(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])},[]),W=l(()=>{k(O?[]:U)},[O,U]),G=l(e=>{A(a=>{const t=new Set(a);return t.has(e)?t.delete(e):t.add(e),t})},[]),K=l(e=>j.find(a=>a.id===e),[j]),Q=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 s=a?K(a):null;y.mutate({id:r.id,id_leader:s?.id_user||null})},[d,n,i,K,y,N]),X=l((e,a)=>{c?c(e,a):(e.forEach(e=>Q(e,a)),k([]))},[c,Q]),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=o(()=>[{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(fe,{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(Ge,{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(Si,{onClick:()=>x(),children:e.t("try_again")})]})});const ne=j.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(Si,{size:"sm",onClick:Z,children:[a(Y,{className:"h-4 w-4 mr-2"}),"Definir Líder"]}),a(Si,{size:"sm",variant:"outline",onClick:q,children:t(r,B?{children:[a(E,{className:"h-4 w-4 mr-1"}),"Colapsar"]}:{children:[a(F,{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(Je,{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(kg,{data:g||[],columns:re,nameKey:"name",nameHeader:p,expandedIds:w,onToggleExpand:$,iconComponent:a(Je,{className:"h-4 w-4 text-muted-foreground shrink-0"}),rowActionsVariant:"inline",enableRowDrag:!0,enableSelection:!0,selectedIds:C,onSelectItem:V,onSelectAll:W,isAllSelected:O,onMoveNode:Q,onMoveNodes:X,rootDropLabel:h,emptyMessage:e.t("leadership_no_hierarchy"),renderActions:e=>a(Si,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>J(e),children:a(H,{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(D?E:F,{className:"h-4 w-4 text-muted-foreground shrink-0"}),a(la,{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"})]}),D&&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:Ni("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(As,{checked:S.has(e.id),onCheckedChange:()=>G(e.id),onClick:e=>e.stopPropagation(),className:"shrink-0"}),a("span",{className:"text-muted-foreground shrink-0 select-none",children:"⠿"}),a(fe,{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(Ev,{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 Tv(e){const[a,t]=s(!1),{uploadFunction:r,deleteFunction:n,defaultOptions:i,onSuccess:o,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"}),o?.(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 Rv(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 Mv(e,a){const t=Rv(e);if(!t)return e;return`https://www.youtube.com/embed/${t}${a?"?autoplay=1&mute=1":""}`}function Lv(e){const a=e.match(/vimeo\.com\/(?:video\/)?(\d+)/);return a?a[1]:null}function zv(e,a){const t=Lv(e);if(!t)return e;return`https://player.vimeo.com/video/${t}${a?"?autoplay=1&muted=1":""}`}function Fv(e){if(!e)return;const a=e.match(/src="([^"]+)"/);return a?a[1]:void 0}function jv(e){return e?/youtube|youtu\.be/.test(e)?"youtube":/vimeo/.test(e)?"vimeo":"file":"file"}function Uv(e,a,t){switch(a||jv(e)){case"youtube":return Mv(e,t);case"vimeo":return zv(e,t);default:return e}}function Ov({value:n,onChange:i,onSubmit:l,onCancel:d,uploadFunction:c,deleteFunction:m,uploadOptions:p}){const{t:h}=La(),[f,g]=s(n||{inputType:"url",controls:!0}),v=u(null),b=u(null),{upload:x,uploading:y}=Tv({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["video/*"],maxSize:104857600}}),{upload:N,uploading:w}=Tv({uploadFunction:c,deleteFunction:m,defaultOptions:{...p,allowedTypes:["image/*"],maxSize:5242880}}),_=o(()=>jv(f.videoUrl||Fv(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(Pi,{children:h("input_type")}),t(vs,{value:f.inputType||"url",onValueChange:e=>k("inputType",e),children:[a(ys,{children:a(xs,{})}),t(_s,{children:[a(ks,{value:"url",children:"URL"}),a(ks,{value:"upload",children:h("file_upload")}),a(ks,{value:"embed",children:h("embed_code")})]})]})]}),"upload"===f.inputType&&c&&t("div",{className:"space-y-2",children:[a(Pi,{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(Si,{type:"button",variant:"outline",onClick:()=>v.current?.click(),disabled:y,children:t(r,y?{children:[a(I,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ca,{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(Pi,{children:h("embed_code")}),a(Es,{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(Pi,{children:"Thumbnail"}),t("div",{className:"flex gap-2",children:[a(Ei,{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(Si,{type:"button",variant:"outline",onClick:()=>b.current?.click(),disabled:w,children:t(r,w?{children:[a(I,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ca,{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(Pi,{htmlFor:"title",children:"Título"}),a(Ei,{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(As,{id:"autoplay",checked:f.autoplay||!1,onCheckedChange:e=>k("autoplay",!0===e)}),a(Pi,{htmlFor:"autoplay",className:"cursor-pointer",children:"Autoplay"})]}),t("div",{className:"flex items-center gap-2",children:[a(As,{id:"controls",checked:!1!==f.controls,onCheckedChange:e=>k("controls",!0===e)}),a(Pi,{htmlFor:"controls",className:"cursor-pointer",children:"Controles"})]})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:"Preview"}),a("div",{className:"border rounded-lg p-4 bg-muted/30",children:(()=>{const r=f.videoUrl||Fv(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"===_?Mv(r,f.autoplay):zv(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(Si,{variant:"outline",onClick:d,children:"Cancelar"}),a(Si,{onClick:()=>{f.videoUrl||f.embedCode?l(f):C.error("Erro",{description:h("no_video_selected")})},disabled:!(f.videoUrl||f.embedCode),children:"Salvar"})]})]})}function Bv({content:r,className:n="",style:i}){const s=r.videoUrl||Fv(r.embedCode)||"";if(!s)return null;const o=jv(s);return a(Ii,{className:`overflow-hidden my-4 ${n}`,style:i,children:t(Li,{className:"p-0",children:["file"===o?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:s}),"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"===o?Mv(s,r.autoplay):zv(s,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 $v({value:e,onChange:n,onSubmit:i,onCancel:o,uploadFunction:l,deleteFunction:d,uploadOptions:c}){const{t:m}=La(),[p,h]=s(e||{alignment:"center",allowDownload:!1}),f=u(null),{upload:g,uploading:v}=Tv({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(Pi,{children:"URL"}),t("div",{className:"flex gap-2",children:[a(Ei,{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(Si,{type:"button",variant:"outline",onClick:()=>f.current?.click(),disabled:v,children:t(r,v?{children:[a(I,{className:"mr-2 h-4 w-4 animate-spin"}),"Enviando..."]}:{children:[a(ca,{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(Pi,{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(Pi,{htmlFor:"caption",children:"Legenda"}),a(Es,{id:"caption",placeholder:"Legenda",value:p.caption||"",onChange:e=>b("caption",e.target.value),rows:2})]}),t("div",{className:"space-y-2",children:[a(Pi,{htmlFor:"alt",children:m("alt_text")}),a(Ei,{id:"alt",placeholder:m("alt_text"),value:p.alt||"",onChange:e=>b("alt",e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:"Alinhamento"}),t(vs,{value:p.alignment||"center",onValueChange:e=>b("alignment",e),children:[a(ys,{children:a(xs,{})}),t(_s,{children:[a(ks,{value:"left",children:"Esquerda"}),a(ks,{value:"center",children:"Centro"}),a(ks,{value:"right",children:"Direita"})]})]})]}),t("div",{className:"grid grid-cols-2 gap-4",children:[t("div",{className:"space-y-2",children:[a(Pi,{htmlFor:"width",children:"Largura"}),a(Ei,{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(Pi,{htmlFor:"height",children:"Altura"}),a(Ei,{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(As,{id:"allowDownload",checked:p.allowDownload||!1,onCheckedChange:e=>b("allowDownload",!0===e)}),a(Pi,{htmlFor:"allowDownload",className:"cursor-pointer",children:"Permitir download"})]}),t("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[a(Si,{variant:"outline",onClick:o,children:"Cancelar"}),a(Si,{onClick:()=>{p.imageUrl?i(p):C.error("Erro",{description:m("no_image_selected")})},disabled:!p.imageUrl,children:"Salvar"})]})]})}function qv({content:e,className:r="",style:n}){const{t:i}=La();if(!e.imageUrl)return null;const s={left:"justify-start",center:"justify-center",right:"justify-end"}[e.alignment||"center"];return a("div",{className:`flex ${s} 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(Xe,{className:"h-4 w-4"}),"Baixar imagem"]})]})})}function Vv(e,a){return e/a}function Wv(e,a,t,r){const n=Vv(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 Hv(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 Gv(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 Kv(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function Yv(){const{alias:e}=ll(),[a,t]=s(null),[r,n]=s(!0);m(()=>{if(!e)return void n(!1);let a=!1;return(async()=>{n(!0);try{const r=Oo(),{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=Oo(),{data:i,error:s}=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(s)throw s;return t(i),i},[e])}}const Qv=import.meta.env.VITE_SUPABASE_URL,Xv=import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY;async function Jv(e,a,t){const r=Lo.getSupabaseToken(),n={"Content-Type":"application/json",apikey:Xv};r&&(n.Authorization=`Bearer ${r}`);const i=await fetch(`${Qv}/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 Zv={async createEnvelopeWithSigner(e){const a="d4sign"===e.provider?"d4sign":"clicksign",t="d4sign"===e.provider?"create_and_send":"create_envelope_with_signer";return(await Jv(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 Jv(a,"get_signed_document",{envelope_id:e.envelopeId,document_id:e.documentId})).json()}};let eb=null;function ab(){return window.Clicksign?Promise.resolve():eb||(eb=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)}),eb)}const tb="clicksign-container";function rb({signerId:e,environment:r="sandbox",onSign:n,onError:i,onClose:o}){const{t:l}=La(),d=u(null),[c,p]=s(!0),[h,f]=s(null);return m(()=>{let a=!1;return d.current&&(d.current.unmount(),d.current=null),f(null),p(!0),ab().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(tb),t.on("loaded",function(){p(!1)}),t.on("signed",function(){n?.()}),t.on("resized",function(e){const a=e,t=document.getElementById(tb);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(){o?.()}),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(I,{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:tb,style:{height:"600px"}})]})}function nb({documentKey:r,signerEmail:n,signerName:i,keySigner:o,environment:d,onSign:c,onError:p}){const h=u(null),[f,g]=s("loading"),[v,b]=s(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 o&&e.set("key_signer",o),`${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(jd,{variant:"danger",className:"my-4",children:[a(Ud,{children:e.t("sign_doc_load_error")}),a(Od,{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(I,{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 ib({file:r,onDocumentSigned:n,onError:i,showEventLog:o=!1}){const{user:d,alias:c}=ll(),{config:p,isLoading:h}=Yv(),{t:f}=La(),[g,v]=s(null),[b,x]=s(!1),[y,N]=s(null),[w,_]=s("sandbox"),[k,S]=s("clicksign"),[A,E]=s(null),[D,P]=s(null),[T,R]=s(!1),[M,L]=s(0),[z,F]=s(!1),[j,U]=s([]),O=u(null),B=u(null),$=l(e=>{o&&U(a=>[...a,`[${(new Date).toLocaleTimeString()}] ${e}`])},[o]),q=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 s=await Zv.createEnvelopeWithSigner({alias:c,contentBase64:n,filename:a.name,signerEmail:d.email||"",signerName:d.name||"",provider:t});$(`Envelope criado: ${s.envelope_id}`),E({envelope_id:s.envelope_id,document_id:s.document_id,signer_email:s.signer_email,key_signer:s.signer_id}),_(s.environment),S(s.provider||t),"d4sign"===t?($("Documento enviado para D4Sign. Abrindo widget de assinatura..."),await new Promise(e=>setTimeout(e,2e3)),N(s.document_id),C.success(f("sign_doc_sent","Documento enviado! Assine abaixo."))):s.signer_id?($(`Signer ID obtido: ${s.signer_id}. Aguardando processamento (3s)...`),await new Promise(e=>setTimeout(e,3e3)),N(s.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,q(r))},[r,c,d,h,q]);const V=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 Zv.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 V())},[$,n,A,y,c,w,k,V]);if(!c)return a(Ii,{className:"border-amber-200 bg-amber-50",children:a(Li,{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=()=>o&&j.length>0?a("div",{className:"bg-muted p-3 rounded-md text-xs font-mono space-y-1 max-h-40 overflow-auto",children:j.map((e,t)=>a("div",{children:e},t))}):null;return A&&!y&&(D||T||z)?t("div",{className:"space-y-4",children:[a(Ii,{className:"border-green-200 bg-green-50",children:t(Li,{className:"flex flex-col items-center gap-4 py-8",children:[a(ea,{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})]}),T?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(I,{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(Si,{asChild:!0,variant:"default",className:"gap-2",children:t("a",{href:D,target:"_blank",rel:"noopener noreferrer",children:[a(Xe,{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(Si,{variant:"secondary",className:"gap-2",onClick:V,children:[a(ce,{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(nb,{documentKey:y,signerEmail:A?.signer_email||d?.email||"",signerName:d?.name,keySigner:A?.key_signer,environment:w,onSign:W,onError:i}):a(rb,{signerId:y,environment:w,onSign:W,onError:i}),a(G,{})]}):r&&(b||h)?a(Ii,{children:t(Li,{className:"flex items-center justify-center gap-3 py-10",children:[a(I,{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?q(a):C.error(f("sign_select_pdf","Selecione um arquivo PDF"))}}),a(Ii,b?{children:t(Li,{className:"flex items-center justify-center gap-3 py-10",children:[a(I,{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(Li,{className:"flex flex-col items-center justify-center py-10 gap-3",children:[a(ca,{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 sb({onSaved:e}){const{config:r,isLoading:n,saveConfig:i}=Yv(),{t:o}=La(),[l,d]=s(""),[c,u]=s("sandbox"),[p,h]=s(!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(I,{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(oe,{className:"h-4 w-4"}),a("span",{children:o("sign_configured",o("sign_configured_unit"))})]}:{className:"flex items-center gap-2 text-sm text-amber-600",children:[a(U,{className:"h-4 w-4"}),a("span",{children:o("sign_not_configured",o("sign_not_configured_unit"))})]}),t(Ii,{children:[a(Ti,{children:a(Ri,{className:"text-base",children:o("sign_digital_config")})}),a(Li,{children:t("form",{onSubmit:async a=>{if(a.preventDefault(),l.trim()){h(!0);try{await i(l.trim(),c),C.success(o("sign_config_saved",o("sign_config_saved_success"))),e?.()}catch(t){C.error(o("sign_config_save_error",o("sign_config_save_err")))}finally{h(!1)}}else C.error(o("sign_api_key_required",o("sign_api_key_info")))},className:"space-y-4",children:[t("div",{className:"space-y-2",children:[a(Pi,{htmlFor:"sign-api-key",children:"API Key"}),a(Ei,{id:"sign-api-key",type:"password",placeholder:o("sign_api_key_placeholder",o("sign_api_key_input")),value:l,onChange:e=>d(e.target.value)})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:o("sign_environment","Ambiente")}),t(vs,{value:c,onValueChange:e=>u(e),children:[a(ys,{children:a(xs,{})}),t(_s,{children:[a(ks,{value:"sandbox",children:"Sandbox (Testes)"}),a(ks,{value:"production",children:"Produção"})]})]})]}),t(Si,{type:"submit",disabled:p,children:[p&&a(I,{className:"mr-2 h-4 w-4 animate-spin"}),r?o("sign_update_config",o("sign_update_config_btn")):o("sign_save_config",o("sign_save_config_btn"))]})]})})]})]})}var ob,lb,db,cb,ub,mb,pb,hb,fb,gb;(lb=ob||(ob={}))[lb.waitingStart=1]="waitingStart",lb[lb.running=2]="running",lb[lb.effectivenessCheck=3]="effectivenessCheck",lb[lb.done=4]="done",lb[lb.suspended=5]="suspended",lb[lb.canceled=6]="canceled",(cb=db||(db={}))[cb.low=0]="low",cb[cb.medium=1]="medium",cb[cb.high=2]="high",(mb=ub||(ub={}))[mb.plan=2]="plan",mb[mb.occurrence=3]="occurrence",mb[mb.risk=4]="risk",mb[mb.decisions=5]="decisions",mb[mb.audit=6]="audit",mb[mb.strategyExtension=7]="strategyExtension",mb[mb.standardization=8]="standardization",mb[mb.supplier=9]="supplier",mb[mb.auditItems=10]="auditItems",(hb=pb||(pb={}))[hb.currentProgress=1]="currentProgress",hb[hb.cumulativeProgress=2]="cumulativeProgress",(gb=fb||(fb={})).uploading="uploading",gb.waiting="waiting",gb.done="done",gb.error="error",gb.canceled="canceled",gb.duplicateItem="duplicateItem";const vb={[ob.waitingStart]:"#D6D6D6",[ob.running]:"#DAE9F4",[ob.effectivenessCheck]:"#1B75BB29",[ob.done]:"#DDEECA",[ob.suspended]:"#FFF2D6",[ob.canceled]:"#F4433629"},bb={[ob.waitingStart]:"#666666",[ob.running]:"#1B75BB",[ob.effectivenessCheck]:"#1B75BB",[ob.done]:"#4CAF50",[ob.suspended]:"#FF9800",[ob.canceled]:"#F44336"},xb={[ob.waitingStart]:"waiting-start",[ob.running]:"running",[ob.effectivenessCheck]:"effectiveness-check",[ob.done]:"done",[ob.suspended]:"suspended",[ob.canceled]:"canceled"};function yb(){return{[ob.waitingStart]:e.t("ap_status_waiting_start"),[ob.running]:e.t("ap_status_running"),[ob.effectivenessCheck]:e.t("ap_status_effectiveness_check"),[ob.done]:e.t("ap_status_done"),[ob.suspended]:e.t("ap_status_suspended"),[ob.canceled]:e.t("ap_status_canceled")}}const Nb=new Proxy({},{get:(e,a)=>{if("symbol"==typeof a)return;return yb()[a]}});function wb(){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 _b=[{id:"immediate",label:"Imediata"},{id:"corrective",label:"Corretiva"},{id:"preventive",label:"Preventiva"},{id:"improvement",label:"Oportunidade de Melhoria"},{id:"standardization",label:"Padronização"}];function Cb(){return[{id:db.low,label:e.t("ap_priority_low"),color:"#4CAF50"},{id:db.medium,label:e.t("ap_priority_medium"),color:"#FF9800"},{id:db.high,label:e.t("ap_priority_high"),color:"#F44336"}]}const kb=[{id:db.low,label:"Baixa",color:"#4CAF50"},{id:db.medium,label:"Média",color:"#FF9800"},{id:db.high,label:"Alta",color:"#F44336"}],Sb=[ob.done,ob.canceled],Ab=[ob.waitingStart,ob.running,ob.effectivenessCheck,ob.suspended];function Eb(e){const{actionPlan:a,isNew:t=!1,config:r,onSave:n,onCancel:i,onDelete:o,onChangeStatus:d}=e,[c,u]=s({formData:a||{},isLoading:e.isLoading||!1,isSaving:!1,activeTab:"general",isFormDisabled:!1});m(()=>{a&&u(e=>({...e,formData:a,isFormDisabled:r?.disableFields||Sb.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(o&&c.formData.id){u(e=>({...e,isLoading:!0}));try{await o(c.formData.id)}finally{u(e=>({...e,isLoading:!1}))}}},[o,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}}function Db({status:e,labels:t,className:r}){const n=t?.[e]||Nb[e]||"",i=vb[e]||"#D6D6D6",s=bb[e]||"#666666";return a("span",{className:Ni("inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold",r),style:{backgroundColor:i,color:s},children:n})}function Pb({formData:e,updateField:r,disabled:n=!1,users:s=[],places:o=[],actionTypes:l,causes:d=[],parentActions:c=[],config:u}){const{t:m}=La(),p=u?.requiredFields,h=l||_b,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(Pi,{className:Ni(g("name")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Nome"}),a(Ei,{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(Pi,{className:Ni(g("responsibleWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Responsável"}),t(vs,{value:e.responsibleId||"",onValueChange:e=>r("responsibleId",e),disabled:n,children:[a(ys,{children:a(xs,{placeholder:m("ap_select_responsible")})}),a(_s,{children:s.map(e=>a(ks,{value:e.id,children:e.name},e.id))})]})]}),f("checkerWho")&&t("div",{className:"space-y-2",children:[a(Pi,{className:Ni(g("checkerWho")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Verificador"}),t(vs,{value:e.checkerId||"",onValueChange:e=>r("checkerId",e),disabled:n,children:[a(ys,{children:a(xs,{placeholder:m("ap_select_checker")})}),a(_s,{children:s.map(e=>a(ks,{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(Pi,{className:Ni(g("place")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Local"}),t(vs,{value:e.placeId||"",onValueChange:e=>r("placeId",e),disabled:n,children:[a(ys,{children:a(xs,{placeholder:m("ap_select_place")})}),a(_s,{children:Ib(o).map(e=>a(ks,{value:e.id,children:e.name},e.id))})]})]}),f("planType")&&t("div",{className:"space-y-2",children:[a(Pi,{className:Ni(g("planType")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Tipo de Ação"}),t(vs,{value:e.typeId||"",onValueChange:e=>r("typeId",e),disabled:n,children:[a(ys,{children:a(xs,{placeholder:m("ap_select_type")})}),a(_s,{children:h.map(e=>a(ks,{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(Pi,{className:Ni(g("priority")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Prioridade"}),t(vs,{value:e.priorityType?.toString()||"",onValueChange:e=>r("priorityType",Number(e)),disabled:n,children:[a(ys,{children:a(xs,{placeholder:m("ap_select_priority")})}),a(_s,{children:kb.map(e=>a(ks,{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(Pi,{children:m("ap_belongs_to")}),t(vs,{value:e.parentId||"",onValueChange:e=>r("parentId",e),disabled:n,children:[a(ys,{children:a(xs,{placeholder:m("ap_select_parent")})}),a(_s,{children:c.map(e=>a(ks,{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(Pi,{className:Ni(g("startDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Início"}),a(Zc,{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(Pi,{className:Ni(g("endDate")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Data de Término"}),a(Zc,{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(Pi,{children:m("ap_duration_days")}),a(Ei,{type:"number",value:v,disabled:!0,className:"bg-muted"})]})]}),f("estimatedCost")&&t("div",{className:"space-y-2 max-w-xs",children:[a(Pi,{className:Ni(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(Ei,{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(Pi,{children:"Causa"}),t(vs,{value:e.causeId||"",onValueChange:e=>r("causeId",e),disabled:n,children:[a(ys,{children:a(xs,{placeholder:m("ap_select_cause")})}),a(_s,{children:d.map(e=>a(ks,{value:e.id,children:e.label},e.id))})]})]}),f("description")&&t("div",{className:"space-y-2",children:[a(Pi,{className:Ni(g("description")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Descrição"}),a(Es,{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(Pi,{className:Ni(g("justification")&&"after:content-['*'] after:ml-0.5 after:text-destructive"),children:"Justificativa"}),a(Es,{value:e.justification||"",onChange:e=>r("justification",e.target.value),maxLength:4e3,disabled:n,rows:4,placeholder:m("ap_justification_placeholder")})]})]})}function Ib(e,a=0){const t=[];for(const r of e)t.push({...r,depth:a}),r.children?.length&&t.push(...Ib(r.children,a+1));return t}function Tb(e){const{progress:a,onReportProgress:t,onEditProgress:r,onDeleteProgress:n}=e,[i,o]=s(!1),[d,c]=s(null),u=!!a&&Ab.includes(a.status),m=l(async e=>{if(t&&a){o(!0);try{const r=100===e.percentProgress;await t({id:a.id,...e,conclude:r})}finally{o(!1)}}},[t,a]),p=l(async e=>{if(r){o(!0);try{await r(e)}finally{o(!1),c(null)}}},[r]),h=l(async e=>{if(n){o(!0);try{await n(e)}finally{o(!1)}}},[n]);return{progress:a,canReportProgress:u,isSubmitting:i,editingReport:d,setEditingReport:c,reportProgress:m,editProgress:p,deleteProgress:h}}function Rb(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 Mb(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 Lb(e){return 100===e?"#84c148":e>0?"#1b75bb":""}function zb({open:e,onOpenChange:r,report:n,onSave:o,isSubmitting:l=!1}){const{t:d}=La(),[c,u]=s(n?.percentProgress||0),[m,p]=s(n?.timeProgress||""),[h,f]=s(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(Yi,{open:e,onOpenChange:r,children:t(as,{className:"sm:max-w-md",variant:"form",isDirty:g,children:[a(ts,{children:a(is,{children:d("ap_edit_progress")})}),t("div",{className:"space-y-4 py-4",children:[t("div",{className:"space-y-2",children:[a(Pi,{children:d("ap_progress_percent")}),a(Ei,{type:"number",min:0,max:100,value:c,onChange:e=>u(Number(e.target.value))})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:d("ap_time_spent")}),a(Ei,{value:m,onChange:e=>p(e.target.value),onBlur:()=>p(Rb(m)||""),placeholder:"00:00"})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:d("ap_comments")}),a(Es,{value:h,onChange:e=>f(e.target.value),rows:3,maxLength:4e3})]})]}),t(ns,{children:[a(Si,{variant:"outline",onClick:()=>r(!1),disabled:l,children:"Cancelar"}),a(Si,{onClick:()=>{n&&o({...n,percentProgress:c,timeProgress:Rb(m)||"00:00",comments:h})},disabled:l,children:l?"Salvando...":"Salvar"})]})]})})}function Fb(e){const{t:r}=La(),{progress:n,canReportProgress:i,isSubmitting:o,editingReport:l,setEditingReport:d,reportProgress:c,editProgress:u,deleteProgress:m}=Tb(e),[p,h]=s(""),[f,g]=s(""),[v,b]=s("");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=Lb(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(Zu,{value:n.percentProgress,className:"h-3"}),n.timeProgress&&t("div",{className:"text-xs text-muted-foreground",children:["Tempo total: ",Mb(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(Pi,{children:r("ap_progress_percent")}),a(Ei,{type:"number",min:0,max:100,value:p,onChange:e=>h(e.target.value),placeholder:"0"})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:r("ap_time_spent")}),a(Ei,{value:f,onChange:e=>g(e.target.value),onBlur:()=>g(Rb(f)||""),placeholder:"00:00"})]})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:r("ap_comments")}),a(Es,{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(Si,{variant:"outline",size:"sm",onClick:()=>{h(""),g(""),b("")},disabled:N||o,children:"Limpar"}),a(Si,{size:"sm",onClick:async()=>{const e=Number(p);(e||0===e)&&(await c({percentProgress:e,timeProgress:Rb(f)||"00:00",comments:v}),h(""),g(""),b(""))},disabled:y||o,children:o?"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(jb,{report:e,onEdit:()=>d(e),onDelete:()=>m(e.id),disabled:!i},e.id))})]}),a(zb,{open:!!l,onOpenChange:e=>!e&&d(null),report:l,onSave:u,isSubmitting:o})]})}function jb({report:r,onEdit:n,onDelete:i,disabled:s}){const o=r.date?new Date(r.date):null,l=Lb(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}),o&&a("span",{className:"text-xs text-muted-foreground",children:o.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: ",Mb(r.timeProgress)]})]}),r.comments&&a("p",{className:"text-xs text-muted-foreground mt-1",children:r.comments})]}),!s&&t(Ls,{children:[a(zs,{asChild:!0,children:a(Ai,{})}),t(qs,{align:"end",children:[a(Vs,{onClick:n,children:e.t("edit")}),a(Vs,{className:"text-destructive",onClick:i,children:e.t("ap_delete")})]})]})]})}function Ub({predecessors:e=[],availablePredecessors:r=[],onAdd:n,onRemove:s,disabled:o=!1}){const{t:l}=La(),[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:[!o&&u.length>0&&t("div",{className:"flex items-end gap-3",children:[t("div",{className:"flex-1 space-y-2",children:[a(Pi,{children:l("ap_add_predecessor")}),t(vs,{value:d,onValueChange:c,children:[a(ys,{children:a(xs,{placeholder:l("ap_select_action")})}),a(_s,{children:u.map(e=>a(ks,{value:e.id,children:e.label},e.id))})]})]}),t(Si,{size:"sm",onClick:()=>{d&&n&&(n(d),c(""))},disabled:!d,children:[a(Y,{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(Db,{status:e.predecessorStatus})]}),!o&&s&&t(Ls,{children:[a(zs,{asChild:!0,children:a(Ai,{})}),a(qs,{align:"end",children:a(Vs,{className:"text-destructive",onClick:()=>s(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 Ob({costs:e=[],onAdd:r,onEdit:n,onDelete:i,disabled:o=!1}){const{t:l}=La(),[d,c]=s(""),[u,m]=s(""),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})]})]}),!o&&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(Pi,{children:"Descrição"}),a(Ei,{value:d,onChange:e=>c(e.target.value),placeholder:l("ap_cost_description")})]}),t("div",{className:"space-y-2",children:[a(Pi,{children:"Valor (R$)"}),a(Ei,{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(Si,{size:"sm",onClick:()=>{d&&u&&r&&(r({description:d,value:Number(u),date:(new Date).toISOString()}),c(""),m(""))},disabled:!d||!u,children:[a(Y,{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})]}),!o&&(n||i)&&t(Ls,{children:[a(zs,{asChild:!0,children:a(Ai,{})}),t(qs,{align:"end",children:[n&&a(Vs,{onClick:()=>n(e),children:l("edit")}),i&&a(Vs,{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 Bb({comments:e=[],currentUserId:r,onAdd:n,onEdit:i,onDelete:o,disabled:l=!1,maxLength:d=4e3}){const{t:c}=La(),[u,m]=s(""),[p,h]=s(!1),[f,g]=s(null),[v,b]=s(""),x=()=>{g(null),b("")};return t("div",{className:"space-y-6 p-1",children:[!l&&n&&t("div",{className:"space-y-3",children:[a(Es,{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(Si,{variant:"outline",size:"sm",onClick:()=>m(""),disabled:!u||p,children:"Limpar"}),a(Si,{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(Ps,{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(ua,{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:$b(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(Es,{value:v,onChange:e=>b(e.target.value),maxLength:d,rows:3}),t("div",{className:"flex gap-2 justify-end",children:[a(Si,{variant:"outline",size:"sm",onClick:x,disabled:p,children:"Cancelar"}),a(Si,{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(Ls,{children:[a(zs,{asChild:!0,children:a(Ai,{})}),t(qs,{align:"end",children:[i&&a(Vs,{onClick:()=>(e=>{g(e.id),b(e.stringText||e.text)})(e),children:c("edit")}),o&&a(Vs,{className:"text-destructive",onClick:()=>(async e=>{if(o){h(!0);try{await o(e)}finally{h(!1)}}})(e.id),children:"Excluir"})]})]})]},e.id))]})]})}function $b(e){const{t:a}=La();if(!e)return"";const t=new Date(e);return`${t.toLocaleDateString("pt-BR")} ${t.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`}function qb({history:e=[],isLoading:r=!1}){const{t:n}=La();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(Ve,{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(xe,{className:"h-3 w-3"}),a("span",{children:Vb(e.date)})]}),t("div",{className:"flex items-center gap-1",children:[a(Ve,{className:"h-3 w-3"}),a("span",{children:Wb(e.date)})]}),e.isMobileRequest&&t("div",{className:"flex items-center gap-1",children:[a(ma,{className:"h-3 w-3"}),a("span",{children:n("ap_via_app")})]})]})]})]},e.id))})]})})}function Vb(e){const{t:a}=La();return new Date(e).toLocaleDateString("pt-BR")}function Wb(e){const{t:a}=La();return new Date(e).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}function Hb({attachments:e=[],onUpload:n,onDelete:i,onRename:o,onDownload:l,onView:d,disabled:c=!1}){const{t:m}=La(),p=u(null),[h,f]=s(null),[g,v]=s(""),b=async e=>{g.trim()&&o&&(await o(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(Si,{size:"sm",onClick:()=>p.current?.click(),children:[a(Y,{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:Ni("flex items-center gap-3 rounded-lg border bg-card p-3",e.status===fb.error&&"border-destructive/50 bg-destructive/5",e.status===fb.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(Si,{size:"sm",variant:"outline",onClick:x,children:m("cancel")}),a(Si,{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===fb.uploading||e.status===fb.waiting)&&a(Zu,{value:e.progress||0,className:"h-1.5"}),e.status===fb.error&&a("p",{className:"text-xs text-destructive",children:"Erro ao enviar arquivo"}),e.status===fb.duplicateItem&&a("p",{className:"text-xs text-warning",children:"Arquivo duplicado"}),e.status===fb.canceled&&a("p",{className:"text-xs text-muted-foreground",children:"Upload cancelado"})]}),t("div",{className:"flex items-center gap-2",children:[e.status===fb.done&&t(r,{children:[a("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:Gb(e.size)}),t(Ls,{children:[a(zs,{asChild:!0,children:a(Ai,{})}),t(qs,{align:"end",children:[o&&!c&&a(Vs,{onClick:()=>(e=>{const a=e.name.replace(e.extension,"");f(e.id),v(a)})(e),children:"Renomear"}),d&&a(Vs,{onClick:()=>d(e.id),children:"Visualizar"}),l&&a(Vs,{onClick:()=>l(e.id),children:"Download"}),i&&!c&&t(r,{children:[a(Ks,{}),a(Vs,{className:"text-destructive",onClick:()=>i(e.id),children:"Excluir"})]})]})]})]}),e.status===fb.uploading&&a(Si,{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(pa,{className:"h-8 w-8 mb-2 opacity-50"}),a("p",{className:"text-sm",children:"Nenhum anexo adicionado"})]})]})}function Gb(e){const{t:a}=La();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 Kb(e){const{formData:r,isLoading:n,isSaving:i,activeTab:s,isFormDisabled:o,updateField:l,setActiveTab:d,save:c,changeStatus:u,remove:m,cancel:p}=Eb(e),{t:h}=La(),{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:j,onDeleteComment:U,onUploadAttachment:O,onDeleteAttachment:B,onRenameAttachment:$,onDownloadAttachment:q,onViewAttachment:V}=e;if(n&&!r.id)return a(Rs,{isLoading:!0,children:a("div",{})});const W=function(e){const{t:a}=La();if(!e)return[];return{[ob.waitingStart]:[ob.running,ob.suspended,ob.canceled],[ob.running]:[ob.effectivenessCheck,ob.done,ob.suspended,ob.canceled],[ob.effectivenessCheck]:[ob.running,ob.done,ob.suspended,ob.canceled],[ob.done]:[ob.running],[ob.suspended]:[ob.running,ob.canceled],[ob.canceled]:[ob.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(Si,{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(Db,{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&&!o&&t(Ls,{children:[a(zs,{asChild:!0,children:a(Si,{variant:"outline",size:"sm",children:"Alterar Status"})}),a(qs,{align:"end",children:W.map(e=>a(Vs,{onClick:()=>u(e),children:Nb[e]},e))})]}),!f&&e.onDelete&&t(Ls,{children:[a(zs,{asChild:!0,children:a(Si,{variant:"ghost",size:"icon",children:a(ta,{className:"h-4 w-4"})})}),a(qs,{align:"end",children:a(Vs,{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(uc,{value:s,onValueChange:d,children:[t(mc,{className:"mb-6",children:[a(pc,{value:"general",children:"Geral"}),!f&&a(pc,{value:"progress",children:"Progresso"}),!f&&g?.enablePredecessors&&a(pc,{value:"predecessors",children:h("ap_predecessors")}),!f&&g?.enableCosts&&a(pc,{value:"costs",children:"Custos"}),!f&&g?.enableAttachments&&a(pc,{value:"attachments",children:h("ap_attachments")}),!f&&g?.enableComments&&a(pc,{value:"comments",children:h("ap_comments")}),!f&&g?.enableHistory&&a(pc,{value:"history",children:"Histórico"})]}),a(hc,{value:"general",children:a(Pb,{formData:r,updateField:l,disabled:o,users:v,places:b,actionTypes:x,causes:y,parentActions:N,config:g})}),!f&&a(hc,{value:"progress",children:a(Fb,{...e})}),!f&&g?.enablePredecessors&&a(hc,{value:"predecessors",children:a(Ub,{predecessors:_,availablePredecessors:C,onAdd:T,onRemove:R,disabled:o})}),!f&&g?.enableCosts&&a(hc,{value:"costs",children:a(Ob,{costs:k,onAdd:M,onEdit:L,onDelete:z,disabled:o})}),!f&&g?.enableAttachments&&a(hc,{value:"attachments",children:D||a(Hb,{attachments:E,onUpload:O,onDelete:B,onRename:$,onDownload:q,onView:V,disabled:o})}),!f&&g?.enableComments&&a(hc,{value:"comments",children:P||a(Bb,{comments:S,onAdd:F,onEdit:j,onDelete:U,disabled:o})}),!f&&g?.enableHistory&&a(hc,{value:"history",children:I||a(qb,{history:A})})]})})}),t("div",{className:"flex items-center justify-end gap-3 border-t bg-card px-6 py-4",children:[p&&a(Si,{variant:"outline",onClick:p,disabled:i,children:"Cancelar"}),a(Si,{onClick:c,disabled:i||o,children:i?"Salvando...":"Salvar"})]})]})}const Yb=["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 Qb(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 Xb(e){const a=e.lastIndexOf(".");return-1===a?"":e.substring(a+1).toLowerCase()}function Jb({storedFile:e,customFileName:r,allowedExtensions:n,customExtensionErrorMessage:i,minSizeInBytes:o=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}=La(),S=u(null),[E,D]=s(null),[P,I]=s(null),[T,R]=s(!1),M=E||e,L=E?.name||e?.name||"",z=E?.size||e?.size;L&&Xb(L);const F=r||L,j=c&&!E&&!!e,U=m&&!E&&!!e,O=!!P||!!b||f&&g&&!M,B=!!M,$=l(e=>{if(Yb.includes(e.type))return{type:"forbidden-type"};if(e.size<=o)return{type:"min-size"};if(e.size>=d)return{type:"max-size"};if(n?.length){const a=Xb(e.name);if(!n.includes(a))return{type:"extension",message:i}}return null},[o,d,n,i]),q=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]),V=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: ${Qb(o)}`;case"max-size":return`Tamanho máximo: ${Qb(d)}`;default:return k("file_error")}})();return t("div",{className:Ni("space-y-1",C),children:[a("div",{className:Ni("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(Oe,{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:Qb(z)}),t("div",{className:"flex items-center gap-0.5",children:[j&&w&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",disabled:T,onClick:K,children:a(Xe,{className:"h-3.5 w-3.5 text-primary"})})}),a(Zs,{children:"Download"})]}),U&&_&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:Y,children:a(_e,{className:"h-3.5 w-3.5 text-primary"})})}),a(Zs,{children:"Visualizar"})]}),p&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:H,children:a(ce,{className:"h-3.5 w-3.5 text-primary"})})}),a(Zs,{children:"Substituir"})]}),h&&t(Xs,{children:[a(Js,{asChild:!0,children:a(Si,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 bg-muted rounded",onClick:G,children:a(A,{className:"h-3 w-3 text-muted-foreground"})})}),a(Zs,{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:V,onDragOver:W,children:[a(ha,{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:q,disabled:v})]})}var Zb,ex,ax,tx,rx,nx;function ix(e){switch(e.type){case Zb.text:return e.textValue;case Zb.number:return e.numberValue;case Zb.date:return e.dateValue;case Zb.time:return e.timeValue;case Zb.url:case Zb.singleSelection:case Zb.multiSelection:return e.itemsValue;case Zb.questions:return e.questionsValue;case Zb.readOnlyText:return e.textValue;default:return null}}function sx(e,a){if(!a)return!0;const t=null!=ix(e)&&""!==ix(e)&&!(Array.isArray(ix(e))&&0===ix(e).length);return!1!==e.isActive||t}function ox(e){return e.filter(e=>e.type!==Zb.readOnlyText).map(e=>({formFieldAssociationId:e.id,textValue:e.type===Zb.text?e.textValue:void 0,numberValue:e.type===Zb.number?e.numberValue:void 0,dateValue:e.type===Zb.date?e.dateValue:void 0,timeValue:e.type===Zb.time?e.timeValue:void 0,itemsValue:[Zb.url,Zb.singleSelection,Zb.multiSelection].includes(e.type)?e.itemsValue:void 0,questionsValue:e.type===Zb.questions?e.questionsValue:void 0}))}function lx(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 Zb.text:r.textValue=t.textValue;break;case Zb.number:r.numberValue=t.numberValue;break;case Zb.date:r.dateValue=t.dateValue;break;case Zb.time:r.timeValue=t.timeValue;break;case Zb.url:case Zb.singleSelection:case Zb.multiSelection:r.itemsValue=t.itemsValue||[];break;case Zb.questions:r.questionsValue=t.questionsValue||[]}return r}):e}function dx(e){const a=[];return e.forEach(e=>{if(!e.required||e.readOnly||e.type===Zb.readOnlyText)return;const t=ix(e);if((null==t||""===t||Array.isArray(t)&&0===t.length)&&a.push(e.id),e.type===Zb.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 cx({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 ux({field:e,readOnly:r,onChange:n}){const i=e.config,s=i?.multiline??!1,o=r||e.readOnly,l=a=>{n?.({...e,textValue:a})};return t("div",{className:"space-y-1.5",children:[a(Pi,{className:Ni(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?a(Es,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:o,rows:4}):a(Ei,{value:e.textValue||"",onChange:e=>l(e.target.value),placeholder:e.placeholder,disabled:o})]})}function mx({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,s=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(Pi,{className:Ni(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(Ei,{type:"date",value:s,onChange:a=>{return t=a.target.value,void n?.({...e,dateValue:t||void 0});var t},placeholder:e.placeholder,disabled:i})]})}function px({field:e,readOnly:r,onChange:n}){const i=r||e.readOnly,s=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(Pi,{className:Ni(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(Ei,{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:s(a.target.value)}),placeholder:e.placeholder,disabled:i})]})}function hx({field:e,readOnly:r,onChange:n}){const i=e.config,o=i?.multiple??!1,l=r||e.readOnly,[d,c]=s(""),u=e.itemsValue||[],m=()=>{if(!d.trim())return;const a={value:crypto.randomUUID(),text:d.trim()};n?.({...e,itemsValue:[...u,a]}),c("")};if(!o){const r=u[0]?.text||"";return t("div",{className:"space-y-1.5",children:[a(Pi,{className:Ni(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(Ei,{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(Si,{variant:"outline",size:"icon",asChild:!0,className:"flex-shrink-0",children:a("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:a(me,{className:"h-4 w-4"})})})]})]})}return t("div",{className:"space-y-1.5",children:[a(Pi,{className:Ni(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(Ei,{type:"url",value:d,onChange:e=>c(e.target.value),placeholder:e.placeholder||"https://",onKeyDown:e=>"Enter"===e.key&&(e.preventDefault(),m())}),a(Si,{variant:"outline",size:"icon",onClick:m,disabled:!d.trim(),className:"flex-shrink-0",children:a(Y,{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(Si,{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(W,{className:"h-3 w-3"})})]},r.value))})]})}function fx({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=null!=i?.decimals&&i.decimals>0?(1/Math.pow(10,i.decimals)).toString():"1";return t("div",{className:"space-y-1.5",children:[a(Pi,{className:Ni(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(Ei,{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:s,min:i?.min,max:i?.max,step:o}),null!=i?.min&&null!=i?.max&&t("p",{className:"text-xs text-muted-foreground",children:["Min: ",i.min," | Max: ",i.max]})]})}function gx({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=i?.viewMode??ax.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(Pi,{className:Ni(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===ax.dropdown&&t(vs,{value:d,onValueChange:c,disabled:s,children:[a(ys,{children:a(xs,{placeholder:e.placeholder||"Selecione..."})}),a(_s,{children:l.map(e=>t(ks,{value:e.value,children:[e.text,!1===e.isActive&&a("span",{className:"text-xs text-muted-foreground ml-1",children:"(inativo)"})]},e.value))})]}),(o===ax.radio||o===ax.buttons)&&a(em,{value:d,onValueChange:c,disabled:s,className:Ni(o===ax.buttons?"flex flex-wrap gap-2":"space-y-2"),children:l.map(r=>t("div",{className:"flex items-center gap-2",children:[a(am,{value:r.value,id:`${e.id}-${r.value}`}),t(Pi,{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))}),!s&&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 vx({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=i?.viewMode??ax.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(Pi,{className:Ni(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(Ps,{variant:"secondary",className:"gap-1 pr-1",children:[a("span",{className:"text-xs",children:r.text}),!s&&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(A,{className:"h-3 w-3"})})]},r.value))}),!s&&a("div",{className:Ni(o===ax.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(As,{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:s}),t(Pi,{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 bx({field:e,readOnly:r,onChange:n}){const i=e.config,s=r||e.readOnly,o=i?.questions||[],l=i?.options||[],d=e.questionsValue||[];return 0===o.length||0===l.length?t("div",{className:"space-y-1.5",children:[a(Pi,{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(Pi,{className:Ni(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:o.map((r,i)=>t("tr",{className:Ni(i<o.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(em,{value:(i=r.value,d.find(e=>e.questionValue===i)?.optionValue||""),onValueChange:a=>((a,t,r,i)=>{const s={questionValue:a,questionText:t,optionValue:r,optionText:i},o=d.filter(e=>e.questionValue!==a);o.push(s),n?.({...e,questionsValue:o})})(r.value,r.text,a,t.text),disabled:s,className:"flex justify-center",children:a(am,{value:t.value,id:`${e.id}-${r.value}-${t.value}`})})},t.value);var i})]},r.value))})]})})]})}function xx({fields:e,readOnly:t=!1,hideInactiveWithoutValue:r=!1,onChange:n,onFieldChange:i}){const s=l(a=>{if(i?.(a),n){const t=e.map(e=>e.id===a.id?a:e);n(t)}},[e,n,i]),o=e.filter(e=>sx(e,r));return 0===o.length?null:a("div",{className:"space-y-4",children:o.map(e=>a(yx,{field:e,readOnly:t,onChange:s},e.id))})}function yx({field:e,readOnly:t,onChange:r}){const n={field:e,readOnly:t,onChange:r};switch(e.type){case Zb.readOnlyText:return a(cx,{...n});case Zb.text:return a(ux,{...n});case Zb.date:return a(mx,{...n});case Zb.time:return a(px,{...n});case Zb.url:return a(hx,{...n});case Zb.number:return a(fx,{...n});case Zb.singleSelection:return a(gx,{...n});case Zb.multiSelection:return a(vx,{...n});case Zb.questions:return a(bx,{...n});default:return null}}function Nx({queryParams:e,events:r,softwares:n,users:i=[],permissions:o={viewAllEvents:!0,viewOnlyMyEvents:!1,download:!1},isLoading:d=!1,onFilter:c,onReset:u,onExport:m,onSoftwareChange:p}){const[h,f]=s(e.softwareId),[g,v]=s(e.eventId),[b,x]=s(e.userId||"all"),[y,N]=s(wx(e.startDate)),[w,_]=s(wx(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(wx(a)),_(wx(a)),v(e.eventId),o.viewAllEvents&&x("all"),u?.()},[e.eventId,o.viewAllEvents,u]),A=o.viewOnlyMyEvents&&!o.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(Pi,{className:"text-xs text-muted-foreground",children:"Módulo *"}),t(vs,{value:String(h),onValueChange:C,disabled:d,children:[a(ys,{className:"h-8 text-xs",children:a(xs,{placeholder:"Selecione..."})}),a(_s,{children:n.map(e=>a(ks,{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(Pi,{className:"text-xs text-muted-foreground",children:"Evento *"}),t(vs,{value:String(g),onValueChange:e=>v(parseInt(e)),disabled:d,children:[a(ys,{className:"h-8 text-xs",children:a(xs,{placeholder:"Selecione..."})}),a(_s,{children:r.map(e=>a(ks,{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(Pi,{className:"text-xs text-muted-foreground",children:"Usuário *"}),t(vs,{value:b,onValueChange:x,disabled:d||A,children:[a(ys,{className:"h-8 text-xs",children:a(xs,{placeholder:"Selecione..."})}),t(_s,{children:[a(ks,{value:"all",className:"text-xs",children:"Todos"}),i.map(e=>a(ks,{value:e.id,className:"text-xs",children:e.name},e.id))]})]})]}),t("div",{className:"flex flex-col gap-1 min-w-[150px]",children:[a(Pi,{className:"text-xs text-muted-foreground",children:"De *"}),a(Ei,{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(Pi,{className:"text-xs text-muted-foreground",children:"Até *"}),a(Ei,{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(Si,{variant:"outline",size:"sm",onClick:S,disabled:d,children:[a(fa,{className:"h-3.5 w-3.5 mr-1"}),"Limpar"]}),o.download&&m&&t(Si,{variant:"outline",size:"sm",onClick:()=>m("xlsx"),disabled:d,children:[a(Xe,{className:"h-3.5 w-3.5 mr-1"}),"Exportar"]}),t(Si,{size:"sm",onClick:k,disabled:d||!E,children:[a(ga,{className:"h-3.5 w-3.5 mr-1"}),"Filtrar"]})]})]})}function wx(e){return(e instanceof Date?e:new Date(e)).toISOString().split("T")[0]}function _x(e,a,t,r="Anônimo"){return e.map(e=>({...e,translatedSoftware:kx(e.software,t),user:e.userEmail||e.userName||r,translatedEvent:Cx(e.eventName,a),date:new Date(e.dateTime)})).sort((e,a)=>(a.date?.getTime()??0)-(e.date?.getTime()??0))}function Cx(e,a){const t=a.find(a=>a.name===e);return t?.translation||e}function kx(e,a){const t=e.includes(".")?e.split(".").pop():e,r=a.find(e=>e.software===t);return r?.translation||t}function Sx(e,a){const t=[],r={...Rx,...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:Ax(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:Ix(e),value:a})})}e.entities?.forEach(e=>{e.data?.forEach(e=>{if("Removed"===e.property)return;if(""===e.newValue&&!e.tagTranslate)return;const i=Ex(e,n,a?.translateProperty),s=Dx(e,null,n,r,a);s&&t.push({name:i,value:s})})}),e.entities?.forEach(e=>{if(e.association?.length){const a=e.association.filter(e=>""!==e.id).map(e=>{const a=Ax(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 s=a?.formatDate?a.formatDate(e.dateTime):Tx(e.dateTime);return t.push({name:r.accomplishedIn,value:s}),t}function Ax(e){return e.code&&e.name&&e.code!==e.name?`${e.code} ${e.name}`:e.name||e.code||""}function Ex(e,a,t){if(e.propertyCustomName)return e.propertyCustomName;const r=Ix(e.property);return t?t(a,r):r}function Dx(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=Ex(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 s=`${a}: "${Px(e,"newValue",r,n)}" ${i}`;const o=e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Dx(a,e,t,r,n)));return o.some(Boolean)&&(s+="\n"+o.filter(Boolean).join("\n")),s}return e.children.map(a=>(a.propertyResource=`${e.propertyResource}.${a.property}`,Dx(a,e,t,r,n))).filter(Boolean).join("\n")}if("Removed"===e.property)return"";if("Modified"===e.state){const i=Px(e,"oldValue",r,n),s=Px(e,"newValue",r,n);return`${a?Ex(e,t,n?.translateProperty)+": ":""}${r.changedFrom} "${i}" ${r.changedTo} "${s}"`}const i=Px(e,"newValue",r,n);return a?`${Ex(e,t,n?.translateProperty)}: ${i}`:i}function Px(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):Tx(n):String(n)}function Ix(e){return e.replace(/([A-Z])/g,(e,a,t)=>`${t>0?"-":""}${a.toLowerCase()}`)}function Tx(e){try{return new Date(e).toLocaleString()}catch{return e}}(ex=Zb||(Zb={}))[ex.readOnlyText=1]="readOnlyText",ex[ex.text=2]="text",ex[ex.date=3]="date",ex[ex.time=4]="time",ex[ex.url=5]="url",ex[ex.number=6]="number",ex[ex.singleSelection=7]="singleSelection",ex[ex.multiSelection=8]="multiSelection",ex[ex.questions=9]="questions",(tx=ax||(ax={}))[tx.dropdown=1]="dropdown",tx[tx.buttons=2]="buttons",tx[tx.radio=3]="radio",tx[tx.checkbox=4]="checkbox",(nx=rx||(rx={}))[nx.custom=1]="custom",nx[nx.users=2]="users",nx[nx.usersLists=3]="usersLists";const Rx={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 Mx({documentId:e,onFetchDetails:r,onClose:n,labels:i,translateProperty:o,translatePropertyValue:d,formatDate:c}){const[u,p]=s(!1),[h,f]=s([]),[g,v]=s(null),b=l(async e=>{p(!0),v(null);try{const a=Sx(await r(e),{translateProperty:o,translatePropertyValue:d,formatDate:c,labels:i});f(a)}catch(a){v("Erro ao carregar detalhes da trilha de auditoria."),f([])}finally{p(!1)}},[r,o,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(Si,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:n,children:a(A,{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(Ts,{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 Lx({title:r,softwares:n,softwareId:i,permissions:o={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}=La();r??v("audit_trail");const[b,x]=s(!0),[y,N]=s([]),[w,_]=s([]),[C,k]=s([]),[S,A]=s(null),[E,D]=s(!1),P=u(null),I=new Date;I.setHours(0,0,0,0);const[T,R]=s({software:n.find(e=>e.id===i)?.software||"",softwareId:i,event:"All",eventId:1,startDate:I,endDate:I,limit:c,softwares:n,userId:o.viewOnlyMyEvents&&!o.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=_x((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)},[]),j=l(()=>{D(!1),A(null)},[]),U=l(async()=>{const e={...T,startDate:I,endDate:I,eventId:1,userId:o.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(Nx,{queryParams:T,events:w,softwares:n,users:C,permissions:o,isLoading:b,onFilter:L,onReset:U,onExport:o.download?O:void 0,onSoftwareChange:z})}),t("div",{className:"flex flex-1 min-h-0 relative",children:[t("div",{className:Ni("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(Ts,{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(Oe,{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(va,{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(Ve,{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(fe,{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(Oe,{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:Ni("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(_e,{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:Ni("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(Mx,{documentId:S,onFetchDetails:d.onFetchDetails,onClose:j,labels:h,translateProperty:d.translateProperty,translatePropertyValue:d.translatePropertyValue,formatDate:f||B})})]})]})}function zx({open:r,onOpenChange:n,returnSteps:i,initialObservation:o="",title:l=e.t("approval_execute_action"),descriptions:d=[],setDefaultApproverOnInit:c=!0,onSubmit:u}){const[m,p]=s(!0),[h,f]=s(c&&i.length>0?i[0].id:null),[g,v]=s(o),b=e=>{p(e),e&&!c?f(null):!e&&!c&&i.length>0&&f(i[0].id)},x=g!==o||!m;return a(Yi,{open:r,onOpenChange:n,children:t(as,{className:"sm:max-w-[480px]",variant:"form",isDirty:x,children:[a(ts,{children:a(is,{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(Pi,{children:"Etapa"}),t(vs,{value:h??void 0,onValueChange:f,disabled:m,children:[a(ys,{children:a(xs,{placeholder:e.t("approval_select_step")})}),a(_s,{children:i.map(e=>a(ks,{value:e.id,children:e.name},e.id))})]})]}),t("div",{className:"space-y-1.5",children:[a(Pi,{children:e.t("approval_opinion")}),a(Es,{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(ns,{children:[a(Si,{variant:"ghost",onClick:()=>n(!1),children:"Cancelar"}),a(Si,{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 Fx({open:e,onOpenChange:r,approvers:n,isLoading:i=!1,ignoreUserIds:l=[],onSubmit:d}){const{t:c}=La(),[u,m]=s(null),p=o(()=>{const e=new Set(l);return n.filter(a=>!e.has(a.id))},[n,l]),h=o(()=>p.map(e=>({value:e.id,label:e.name})),[p]);return a(Yi,{open:e,onOpenChange:r,children:t(as,{className:"sm:max-w-[450px]",variant:"form",isDirty:!!u,children:[a(ts,{children:a(is,{children:c("approval_select_approver")})}),a(Rs,{isLoading:i,type:"spinner",children:a("div",{className:"space-y-4",children:a(vo,{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(ns,{children:[a(Si,{variant:"ghost",onClick:()=>r(!1),children:"Cancelar"}),a(Si,{onClick:()=>{if(!u)return;const e=p.find(e=>e.id===u);e&&d(e)},disabled:!u||i,children:"Concluir"})]})]})})}function jx(e){const{t:a}=La();if(!e)return"";return("string"==typeof e?new Date(e):e).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric"})}function Ux({text:e,maxLength:r=130}){const{t:n}=La(),[i,o]=s(!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:()=>o(!i),children:n(i?"approval_read_less":"approval_read_more")})]})}function Ox({approver:e}){if(1===e.type&&e.approverId)return t(Uc,{className:"h-9 w-9 shrink-0",children:[a(Oc,{src:e.photoUrl,alt:e.name}),a(Bc,{className:"text-xs",children:e.name?.substring(0,2).toUpperCase()})]});const r=2===e.type?Je:3===e.type?ba:fe;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 Bx({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(oe,{className:"h-3.5 w-3.5 text-green-600"}),"Aprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:jx(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(xa,{className:"h-3.5 w-3.5 text-red-600"}),"Reprovado"]}),a("span",{className:"text-xs text-muted-foreground",children:jx(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(U,{className:"h-3.5 w-3.5"}),"Aguardando"]})}function $x({approver:e}){const{t:r}=La(),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(Bx,{approver:e})]})}function qx({config:e,isLoading:r=!1,onClose:n,onApprove:i,onDefineApprover:o,onRefreshSteps:d,availableApprovers:c=[],isLoadingApprovers:u=!1}){const{t:m}=La(),[p,h]=s(!1),[f,g]=s(!1),[v,b]=s(""),[x,y]=s(""),[N,w]=s(!1),[_,C]=s(""),k=r||p,S=l((e,a)=>{b(e),y(a??""),g(!0)},[]),E=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 o(e.associationId,_,a),await(d?.(e.associationId)),h(!1)},[e.associationId,_,o,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(Si,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0",children:a(A,{className:"h-5 w-5"})}),a("span",{className:"text-lg font-medium",children:e.title})]}),k?a(Rs,{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:Ni("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:Ni("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(Ux,{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 ",jx(r.returnDate)]})]}),r.returnObservation&&a("p",{className:"text-sm text-muted-foreground bg-muted rounded p-2 break-words",children:a(Ux,{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(Ox,{approver:e}),a($x,{approver:e})]}),T(r,e)&&a(Si,{size:"sm",onClick:()=>S(e.id),children:"Aprovar"}),R(r,e)&&a(Si,{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(Ux,{text:e.observation})}),e.returnObservation&&a("p",{className:"text-sm text-muted-foreground break-words ml-11",children:a(Ux,{text:e.returnObservation})})]},e.id))]},r.id))]}),a(zx,{open:f,onOpenChange:g,returnSteps:e.returnSteps,initialObservation:x,title:e.approveDialogTitle,descriptions:e.approveDialogDescriptions,setDefaultApproverOnInit:e.approveDialogSetDefaultApproverOnInit,onSubmit:E}),a(Fx,{open:N,onOpenChange:w,approvers:c,isLoading:u,ignoreUserIds:I,onSubmit:P})]})}var Vx,Wx;function Hx({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}=La(),g=u??f("leadership_remove_team"),v=p??f("leadership_no_members"),[b,x]=s(""),[y,N]=s(!1),[w,_]=s(null),C=o(()=>new Set(r),[r]),k=o(()=>e.filter(e=>C.has(e.id)),[e,C]),S=o(()=>e.filter(e=>!C.has(e.id)).map(e=>({value:e.id,label:e.name})),[e,C]),E=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:Ni("space-y-3",h),children:[a("div",{className:"flex items-start gap-3",children:a("div",{className:"flex-1",children:a(vo,{options:S,value:b,onValueChange:e=>{const a="string"==typeof e?e:e?.[0]??"";x(a),a&&E(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(Uc,{className:"h-8 w-8 shrink-0",children:[e.avatar&&a(Oc,{src:e.avatar,alt:e.name}),a(Bc,{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(ya,{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(ba,{className:"h-3.5 w-3.5"}),a("span",{className:"truncate max-w-[120px]",children:e.placeName})]}),a("button",{type:"button",className:Ni("text-muted-foreground hover:text-destructive transition-colors",i&&"opacity-50 pointer-events-none"),onClick:()=>!i&&D(e.id),title:f("remove"),children:a(A,{className:"h-4 w-4"})})]})]},e.id))}):t("div",{className:"flex flex-col items-center justify-center py-8 text-muted-foreground",children:[a(fe,{className:"h-12 w-12 mb-2 opacity-30"}),a("p",{className:"text-sm",children:v})]}),a(Yi,{open:y,onOpenChange:N,children:t(as,{className:"sm:max-w-[400px]",children:[a(ts,{children:a(is,{children:g})}),a("p",{className:"text-sm text-muted-foreground",children:m}),t(ns,{children:[a(Si,{variant:"ghost",onClick:()=>N(!1),children:"Cancelar"}),a(Si,{variant:"destructive",onClick:P,children:"Remover"})]})]})})]})}(Wx=Vx||(Vx={}))[Wx.ApprovalFlow=1]="ApprovalFlow",Wx[Wx.Association=2]="Association";export{ar as AUTH_CONFIG,Ec as AccessDeniedDialog,Lc as Accordion,jc as AccordionContent,zc as AccordionItem,Fc as AccordionTrigger,Ai as ActionButton,Ai as ActionMenu,Wl as ActionMenuItems,Hb as ActionPlanAttachmentsTab,Bb as ActionPlanCommentsTab,Ob as ActionPlanCostTab,Pb as ActionPlanGeneralTab,qb as ActionPlanHistoryTab,Kb as ActionPlanPage,Ub as ActionPlanPredecessorsTab,zb as ActionPlanProgressDialog,Fb as ActionPlanProgressTab,Db as ActionPlanStatusBadge,gh as AggregationType,jd as Alert,Od as AlertDescription,ji as AlertDialog,Gi as AlertDialogAction,Ki as AlertDialogCancel,$i as AlertDialogContent,Hi as AlertDialogDescription,Vi as AlertDialogFooter,qi as AlertDialogHeader,Bi as AlertDialogOverlay,Oi as AlertDialogPortal,Wi as AlertDialogTitle,Ui as AlertDialogTrigger,Ud as AlertTitle,Ld as AliasRedirect,Md as AliasRouteGuard,bh as AnalysisFunctionality,Ug as AppHeader,Qg as AppLayout,Yg as AppSidebar,Vx as ApprovalFlowReturnStep,qx as ApprovalSidenav,zx as ApproveDialog,Mx as AuditTrailDetails,Nx as AuditTrailFilter,Lx as AuditTrailPage,qo as AuthErrorInterceptor,ol as AuthProvider,rl as AuthService,vo as AutoComplete,Uc as Avatar,Bc as AvatarFallback,Oc as AvatarImage,Ps as Badge,bd as BaseForm,Ru as Blockquote,Zg as BodyContent,$c as Breadcrumb,Kc as BreadcrumbEllipsis,Vc as BreadcrumbItem,Wc as BreadcrumbLink,qc as BreadcrumbList,Hc as BreadcrumbPage,Gc as BreadcrumbSeparator,Yf as BurndownPanel,Si as Button,Qc as ButtonGroup,Sb as CLOSED_STATUSES,tr as CRUD_CONFIG,gf as CURRENCY_FIELDS,Xc as Calendar,Bd as CallbackPage,Ii as Card,Li as CardContent,Mi as CardDescription,zi as CardFooter,Ti as CardHeader,wl as CardSkeleton,Ri as CardTitle,Vf as CartesianPanel,pp as ChartContainer,vp as ChartLegend,bp as ChartLegendContent,hp as ChartStyle,fp as ChartTooltip,gp as ChartTooltipContent,As as Checkbox,oc as Collapsible,dc as CollapsibleContent,lc as CollapsibleTrigger,ud as ColorPicker,ko as ComboTree,vo as Combobox,no as Command,io as CommandDialog,lo as CommandEmpty,co as CommandGroup,so as CommandInput,mo as CommandItem,oo as CommandList,uo as CommandSeparator,po as CommandShortcut,Jg as ContentContainer,Pl as ContextMenu,Ol as ContextMenuCheckboxItem,jl as ContextMenuContent,Tl as ContextMenuGroup,Ul as ContextMenuItem,$l as ContextMenuLabel,Rl as ContextMenuPortal,Ll as ContextMenuRadioGroup,Bl as ContextMenuRadioItem,ql as ContextMenuSeparator,Vl as ContextMenuShortcut,Ml as ContextMenuSub,Fl as ContextMenuSubContent,zl as ContextMenuSubTrigger,Il as ContextMenuTrigger,Mc as CoreProviders,ad as CrudActionBar,xg as CrudActionMenu,vg as CrudGrid,Sd as CrudPageInternal,yd as CrudPagination,yg as CrudPrimitiveFilterBar,xd as CrudPrimitivePagination,bg as CrudPrimitiveTable,ld as CrudTable,xx as CustomFormFields,nb as D4SignWidget,ff as DASHBOARD_STORAGE_KEYS,ei as DATETIME_FORMATS,_b as DEFAULT_ACTION_TYPES,ri as DEFAULT_DATETIME_FORMAT,ti as DEFAULT_LOCALE,ni as DEFAULT_TIMEZONE,fg as DashboardForm,Uh as DashboardFormTab,xh as DashboardFunctionality,gg as DashboardGeneralView,tg as DashboardGrid,qh as DashboardLanguage,dg as DashboardList,Nh as DashboardListType,_h as DashboardPageTime,kh as DashboardPanelDimension,Dh as DashboardPanelOrderBy,Ah as DashboardPanelOrderByType,Ih as DashboardPanelPeriod,ng as DashboardPanelRenderer,Rh as DashboardPanelType,Bh as DashboardShareType,Lh as DashboardUpdateTime,ig as DashboardView,Fh as DashboardViewType,yg as DataFilterBar,Jc as DataList,xd as DataPagination,bg as DataTable,Zc as DatePicker,Yi as Dialog,rs as DialogBody,Ji as DialogClose,as as DialogContent,ss as DialogDescription,ns as DialogFooter,ts as DialogHeader,Zi as DialogOverlay,Xi as DialogPortal,is as DialogTitle,Qi as DialogTrigger,zp as DialogWizard,eo as DisabledMenuItem,ib as DocumentSigner,eu as Drawer,ru as DrawerClose,iu as DrawerContent,du as DrawerDescription,ou as DrawerFooter,su as DrawerHeader,nu as DrawerOverlay,tu as DrawerPortal,lu as DrawerTitle,au as DrawerTrigger,Ls as DropdownMenu,Ws as DropdownMenuCheckboxItem,qs as DropdownMenuContent,Fs as DropdownMenuGroup,Vs as DropdownMenuItem,Gs as DropdownMenuLabel,js as DropdownMenuPortal,Os as DropdownMenuRadioGroup,Hs as DropdownMenuRadioItem,Ks as DropdownMenuSeparator,Ys as DropdownMenuShortcut,Us as DropdownMenuSub,$s as DropdownMenuSubContent,Bs as DropdownMenuSubTrigger,zs as DropdownMenuTrigger,fb as EAttachmentItemStatus,Zb as ECustomFormFieldType,ax as EFieldViewMode,rx as ESelectionFieldDataSource,ub as ETaskPlanAssociationType,db as ETaskPlanPriority,ob as ETaskPlanStatus,pb as ETaskPlanTypeProgress,Mp as ElectronicSignatureDialog,El as EllipsisText,iv as EmailService,Al as EmptyState,vo as EntitySelect,cc as ErrorBoundary,Tp as ExportDialog,Ep as ExportFormat,Yb as FORBIDDEN_FILE_TYPES,qp as FilePrintType,Bp as FileViewerType,kd as FilterBar,os as Form,hs as FormControl,mx as FormDateField,fs as FormDescription,ds as FormField,ms as FormItem,ps as FormLabel,gs as FormMessage,vx as FormMultiSelectionField,fx as FormNumericField,bx as FormQuestionsField,gx as FormSingleSelectionField,_l as FormSkeleton,ux as FormTextField,px as FormTimeField,hx as FormUrlField,mu as Grid,_u as H1,Cu as H2,ku as H3,Su as H4,Cl as HeaderSkeleton,pu as HoverCard,fu as HoverCardContent,hu as HoverCardTrigger,hd as IconPicker,eh as IframeDialog,$v as ImageEditor,qv as ImageRenderer,Tu as InlineCode,Ei as Input,gu as InputGroup,bu as InputGroupAddon,yu as InputGroupButton,Nu as InputGroupInput,wu as InputGroupTextarea,vf as LINK_PROPERTIES,cr as LOGO_CONFIG,Pi as Label,Du as Large,Eu as Lead,Ev as LeadershipDialog,Av as LeadershipForm,Iv as LeadershipPage,Mu as List,Bf as ListPanel,Rs as LoadingState,tc as LocaleProvider,$d as LoginPage,ur as MESSAGES,bc as MODULES_DATA,hf as MONTHS_MAP,ov as ManageAccessModal,Xf as MatrixRiskPanel,Wh as MatrixViewType,Zm as Menubar,ip as MenubarCheckboxItem,rp as MenubarContent,Ym as MenubarGroup,np as MenubarItem,op as MenubarLabel,Km as MenubarMenu,Qm as MenubarPortal,Jm as MenubarRadioGroup,sp as MenubarRadioItem,lp as MenubarSeparator,dp as MenubarShortcut,Xm as MenubarSub,tp as MenubarSubContent,ap as MenubarSubTrigger,ep as MenubarTrigger,Hg as ModalStateProvider,Pc as ModuleAccessGuard,Nc as ModuleGrid,Ic as ModuleOfferContent,ic as ModuleProvider,wc as ModulesContent,Ac as ModulesDialog,vc as ModulesFooterCards,vo as MultiSelect,lh as MultiselectPermissions,Iu as Muted,Lu as NavigationMenu,Ou as NavigationMenuContent,qu as NavigationMenuIndicator,Fu as NavigationMenuItem,Bu as NavigationMenuLink,zu as NavigationMenuList,Uu as NavigationMenuTrigger,$u as NavigationMenuViewport,Rg as NavigationProvider,Uf as NumericPanel,Sp as OnboardingDialog,Zp as OnlineEditorDialog,Au as P,kb as PRIORITIES,Qt as PROD_PROJECT_ID,Ab as PROGRESS_ALLOWED_STATUSES,Vu as PageBreadcrumb,Vd as PageMetadataProvider,Hu as Pagination,Gu as PaginationContent,Ju as PaginationEllipsis,Ku as PaginationItem,Yu as PaginationLink,Xu as PaginationNext,Qu as PaginationPrevious,mf as PaletteType,Mf as PanelError,Rf as PanelHeader,Gh as PanelItemsPerPanel,Lf as PanelLoader,zf as PanelNoData,Yh as PanelSortType,Xh as PanelState,Ff as PanelUnavailable,Kf as ParetoPanel,Qf as PerformancePanel,Gf as PiePanel,lv as PlaceCard,dv as PlacesList,af as PlanType,ao as Popover,ro as PopoverContent,to as PopoverTrigger,Zu as Progress,Td as ProtectedRoute,dr as QUALIEX_CONFIG,lr as QUERY_KEYS,Xo as QualiexEnrichmentService,Vo as QualiexErrorInterceptor,vd as QualiexUserField,rf as QueriesContextType,sf as QueriesShareType,lf as QuickFilterDashboard,em as RadioGroup,am as RadioGroupItem,cx as ReadOnlyTextField,hh as ReportRequestList,dh as ReportRequestStatus,nm as ResizableHandle,rm as ResizablePanel,tm as ResizablePanelGroup,wp as RichTextEditor,cf as RiskCriticality,rr as SEARCH_CONFIG,vb as STATUS_COLORS,Nb as STATUS_LABELS,xb as STATUS_MAP,bb as STATUS_TEXT_COLORS,Zn as SUPPORTED_LOCALES,bo as ScrollArea,xo as ScrollBar,vs as Select,Fx as SelectApproverDialog,_s as SelectContent,bs as SelectGroup,ks as SelectItem,Cs as SelectLabel,ws as SelectScrollDownButton,Ns as SelectScrollUpButton,vo as SelectSearch,Ss as SelectSeparator,ys as SelectTrigger,xs as SelectValue,Fi as Separator,im as Sheet,pm as SheetBody,om as SheetClose,um as SheetContent,gm as SheetDescription,hm as SheetFooter,mm as SheetHeader,dm as SheetOverlay,lm as SheetPortal,fm as SheetTitle,sm as SheetTrigger,Nm as Sidebar,Bg as SidebarActionTrigger,Dm as SidebarContent,Am as SidebarFooter,Pm as SidebarGroup,Tm as SidebarGroupAction,Rm as SidebarGroupContent,Im as SidebarGroupLabel,Xg as SidebarHeader,km as SidebarInput,Cm as SidebarInset,jg as SidebarLogo,Mm as SidebarMenu,jm as SidebarMenuAction,Um as SidebarMenuBadge,Fm as SidebarMenuButton,Lm as SidebarMenuItem,Om as SidebarMenuSkeleton,Bm as SidebarMenuSub,qm as SidebarMenuSubButton,$m as SidebarMenuSubItem,ym as SidebarProvider,_m as SidebarRail,Em as SidebarSeparator,kl as SidebarSkeleton,wm as SidebarTrigger,sb as SignConfigForm,rb as SignWidget,Jb as SingleFileUpload,ho as Skeleton,Vm as Slider,Pu as Small,Ms as SonnerToaster,Ts as Spinner,Ap as SplitButton,Cd as Stack,Lp as StepSelector,Lp as Stepper,fh as StimulsoftViewer,fd as Switch,ai as TIMEZONES,Gm as TabPageContent,Hm as TabPageHeader,Wm as TabPageLayout,pl as Table,fl as TableBody,yl as TableCaption,xl as TableCell,gl as TableFooter,bl as TableHead,hl as TableHeader,Dl as TableResizeHandle,vl as TableRow,Hl as TableRowActions,Nl as TableSkeleton,uc as Tabs,hc as TabsContent,mc as TabsList,pc as TabsTrigger,Hx as TeamSelector,ah as TermsOfUseDialog,th as TermsOfUseViewer,Of as TextPanel,Es as Textarea,Rp as Timepicker,Ms as Toaster,Xl as Toggle,Zl as ToggleGroup,ed as ToggleGroupItem,Lo as TokenManager,So as TokenService,Xs as Tooltip,Zs as TooltipContent,Qs as TooltipProvider,Js as TooltipTrigger,ko as TreeSelect,kg as TreeTable,El as TruncatedCell,Op as UpdatesNotification,ih as UsersGroupsSelector,Ov as VideoEditor,Bv as VideoRenderer,Xp as ViewerDialog,Zh as VisualizationType,Jd as addAppTranslations,hr as assets,Ds as badgeVariants,Sx as buildDetailRows,mv as buildHierarchy,yi as buildModuleUrl,Df as buildPlacesTree,Qp as buildWopiUrl,Yc as buttonGroupVariants,ki as buttonVariants,Vv as calculateAspectRatio,Ix as camelToDash,Ni as cn,Ad as createCrudPage,Ag as createCrudRoutingConfig,Sg as createRoutingHandlers,el as createService,Ed as createSimpleSaveHandler,cl as createSimpleService,mr as createTranslatedMessages,Ef as currencyFormatter,_i as debounce,Go as deriveEmailField,Ho as deriveNameField,Ko as deriveUsernameField,ui as detectBrowserLocale,hi as detectBrowserPreferences,mi as detectBrowserTimezone,jv as detectVideoProvider,sv as emailService,zo as errorService,Gv as extractImageFileName,Af as extractNumberFromCurrency,Lv as extractVimeoId,Rv as extractYouTubeId,uv as filterAndPromoteOrphans,si as findDatetimeFormat,ii as findLocale,oi as findTimezone,pv as flattenTree,Qb as formatBytes,bi as formatCurrency,vi as formatDate,gi as formatDatetime,Kv as formatFileSize,Mb as formatTime,Rb as formatTimeProgress,Dd as generateCrudConfig,wb as getActionTypes,Zf as getDefaultPanelSize,Zt as getEnvironmentConfig,ix as getFieldValue,Xb as getFileExtension,ox as getFormFieldValues,wf as getLinkFromRow,eg as getMinPanelSize,Gp as getOnlineViewerType,Cb as getPriorities,Lb as getProgressColor,or as getQualiexApiUrl,yb as getStatusLabels,Oo as getSupabaseClient,Hp as getViewerType,Yp as getWopiViewer,xi as handleExternalLink,pi as inferDatetimeFormat,vu as inputGroupAddonVariants,xu as inputGroupButtonVariants,Sf as isCurrency,sr as isDevEnvironment,er as isDevSupabaseProject,Hv as isImageUrl,nr as isLovablePreview,yf as isNullOrEmptyField,di as isValidDatetimeFormat,li as isValidLocale,ci as isValidTimezone,ab as loadClicksignScript,Rc as loadForlogicFonts,fr as logoSrc,rv as mergeTranslationFiles,ju as navigationMenuTriggerStyle,Uv as normalizeVideoUrl,zv as normalizeVimeoUrl,Mv as normalizeYouTubeUrl,Fv as parseIframeSrc,cv as placeService,_x as processTrails,Nf as processUrl,Wo as qualiexApi,Wv as resizeKeepingAspect,Yo as resolveFieldMappings,zg as resolvePageTitle,lx as setFormFieldValues,Gd as setupQualiexCore,sx as shouldShowField,ir as shouldUseDevTokens,Zv as signService,Ci as slugify,gr as smallLogoSrc,bf as sortByMonthYear,_f as toQueryString,Ql as toggleVariants,wi as trimTextFields,Eb as useActionPlan,Tb as useActionPlanProgress,ev as useActiveModules,Rd as useAliasFromUrl,ll as useAuth,dd as useBaseForm,Yl as useColumnResize,vv as useCreateMultipleLeadersMutation,gv as useCreateSingleLeaderMutation,dl as useCrud,Fg as useDebounce,Sc as useDerivedContractedModules,cs as useFormField,Kg as useHasOpenModal,nv as useI18nFormatters,ml as useIsMobile,hv as useLeadershipApi,rc as useLocale,ul as useMediaQuery,Tv as useMediaUpload,Gg as useModalState,kc as useModuleAccess,sc as useModuleConfig,Mg as useNavigation,Hd as usePageMetadata,Wd as usePageMetadataContext,Lg as usePageTitle,Og as usePermissionQuery,gd as useQualiexUsers,xv as useRemoveLeaderMutation,Wu as useRouteBreadcrumbs,av as useRowResize,xm as useSidebar,Vg as useSidebarResize,Yv as useSignConfig,yv as useSyncSubordinatesMutation,bv as useUpdateLeaderMutation,Up as useUpdatesNotification,tv as useWizard,dx as validateFields};