UNPKG

@birhaus/patterns

Version:

BIRHAUS Pattern Components - ApprovalWorkflow, RoleManager, SmartSearch, FinancialDashboard, AuditTimeline

9 lines 61.3 kB
import Za,{forwardRef,useState,useCallback,useEffect,useRef,useMemo}from'react';import {AlertTriangle,RotateCcw,Building,DollarSign,GraduationCap,Settings,X,AlertCircle,Plus,ChevronUp,ChevronDown,Trash2,Save,Check,UserCheck,Search,Filter,Clock,CheckCircle,XCircle,User,TrendingUp,TrendingDown,Wallet,RefreshCw,Banknote,CreditCard,Calendar,ArrowUpRight,ArrowDownRight,Download,Info,Target,EyeOff,Eye,Minus,BarChart3}from'lucide-react';import {formatDistanceToNow}from'date-fns';import {es}from'date-fns/locale';import {jsxs,jsx,Fragment}from'react/jsx-runtime';function oa(...e){return e.filter(Boolean).join(" ")}var la={"iglesia.creada":"cre\xF3 una iglesia","iglesia.actualizada":"actualiz\xF3 una iglesia","iglesia.eliminada":"elimin\xF3 una iglesia","pastor.creado":"registr\xF3 un pastor","pastor.actualizado":"actualiz\xF3 un pastor","pastor.eliminado":"elimin\xF3 un pastor","donacion.registrada":"registr\xF3 una donaci\xF3n","donacion.anulada":"anul\xF3 una donaci\xF3n","transferencia.creada":"cre\xF3 una transferencia","transferencia.completada":"complet\xF3 una transferencia","gasto.registrado":"registr\xF3 un gasto","gasto.aprobado":"aprob\xF3 un gasto","gasto.rechazado":"rechaz\xF3 un gasto","usuario.login":"inici\xF3 sesi\xF3n","usuario.logout":"cerr\xF3 sesi\xF3n","resumen.enviado":"envi\xF3 un resumen","resumen.aprobado":"aprob\xF3 un resumen","resumen.rechazado":"rechaz\xF3 un resumen",create:"cre\xF3",update:"actualiz\xF3",delete:"elimin\xF3",approve:"aprob\xF3",reject:"rechaz\xF3",login:"inici\xF3 sesi\xF3n",logout:"cerr\xF3 sesi\xF3n"},Ia={creada:"text-green-600",creado:"text-green-600",registrada:"text-green-600",registrado:"text-green-600",actualizada:"text-blue-600",actualizado:"text-blue-600",eliminada:"text-red-600",eliminado:"text-red-600",anulada:"text-yellow-600",aprobado:"text-green-600",rechazado:"text-red-600",completada:"text-green-600",enviado:"text-blue-600",login:"text-gray-500",logout:"text-gray-500"};function Pa({events:e,showFilters:t=true,maxHeight:s="600px",className:o="",emptyMessage:m="No hay eventos que mostrar",filterAllEntitiesLabel:f="Todas las entidades",filterAllActionsLabel:u="Todas las acciones",clearFiltersLabel:x="Limpiar filtros",showDetailsLabel:g="Ver detalles",hideDetailsLabel:b="Ocultar detalles"}){let[p,y]=useState("all"),[E,N]=useState("all"),[j,M]=useState(new Set),{entities:l,verbs:I}=useMemo(()=>{let n=new Set,C=new Set;return e.forEach(F=>{F.entity&&n.add(F.entity),C.add(F.verb);}),{entities:Array.from(n).sort(),verbs:Array.from(C).sort()}},[e]),R=useMemo(()=>e.filter(n=>!(p!=="all"&&n.entity!==p||E!=="all"&&n.verb!==E)),[e,p,E]),B=n=>{let C=new Set(j);C.has(n)?C.delete(n):C.add(n),M(C);},T=n=>{let C=n.split(".").pop()||"";return Ia[C]||"text-gray-700"},ue=n=>!n||Object.keys(n).length===0?null:jsx("div",{className:"mt-2 p-3 bg-gray-50 rounded-md text-xs space-y-1 border",children:Object.entries(n).map(([C,F])=>jsxs("div",{className:"flex gap-2",children:[jsxs("span",{className:"text-gray-500 font-medium min-w-20",children:[C,":"]}),jsx("span",{className:"text-gray-700 flex-1",children:typeof F=="object"?JSON.stringify(F,null,2):String(F)})]},C))});return jsxs("div",{className:oa("space-y-4",o),"data-birhaus-component":"audit-timeline",children:[t&&(l.length>0||I.length>0)&&jsxs("div",{className:"flex gap-3 items-center p-3 bg-gray-50 border border-gray-200 rounded-md",children:[jsx(Filter,{className:"h-4 w-4 text-gray-400"}),l.length>0&&jsxs("select",{value:p,onChange:n=>y(n.target.value),className:"px-3 py-1 border border-gray-300 rounded-md text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500",children:[jsx("option",{value:"all",children:f}),l.map(n=>jsx("option",{value:n,children:n.charAt(0).toUpperCase()+n.slice(1)},n))]}),I.length>0&&jsxs("select",{value:E,onChange:n=>N(n.target.value),className:"px-3 py-1 border border-gray-300 rounded-md text-sm bg-white focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500",children:[jsx("option",{value:"all",children:u}),I.map(n=>jsx("option",{value:n,children:la[n]||n},n))]}),(p!=="all"||E!=="all")&&jsx("button",{onClick:()=>{y("all"),N("all");},className:"text-sm text-primary-600 hover:text-primary-700 hover:underline focus:outline-none focus:ring-2 focus:ring-primary-500 px-2 py-1 rounded",children:x})]}),jsx("div",{className:"space-y-2 overflow-y-auto pr-2 scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100",style:{maxHeight:s},children:R.length===0?jsxs("div",{className:"text-center py-8 text-gray-500 bg-gray-50 rounded-lg border-2 border-dashed border-gray-200",children:[jsx(Clock,{className:"h-8 w-8 text-gray-400 mx-auto mb-2"}),jsx("p",{children:m})]}):R.map((n,C)=>{let F=j.has(n.id),G=n.payload&&Object.keys(n.payload).length>0;return jsxs("div",{className:"flex gap-3 p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-300 hover:shadow-sm transition-all duration-150",children:[jsxs("div",{className:"flex flex-col items-center",children:[jsx("div",{className:"w-2 h-2 rounded-full bg-primary-600 mt-2 flex-shrink-0"}),C<R.length-1&&jsx("div",{className:"w-px flex-1 bg-gray-200 mt-2"})]}),jsx("div",{className:"flex-1 min-w-0",children:jsxs("div",{className:"flex items-start justify-between gap-2",children:[jsxs("div",{className:"flex-1",children:[jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsx(User,{className:"h-3 w-3 text-gray-400"}),jsx("span",{className:"text-sm font-medium text-gray-900",children:n.actor_name||"Usuario"}),jsx("span",{className:oa("text-sm font-medium",T(n.verb)),children:la[n.verb]||n.verb}),n.entity&&jsx("span",{className:"text-xs px-2 py-1 bg-gray-200 text-gray-700 rounded-full",children:n.entity})]}),n.entity_id&&jsxs("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:["ID: ",n.entity_id]}),G&&jsx("button",{onClick:()=>B(n.id),className:"flex items-center gap-1 mt-2 text-xs text-primary-600 hover:text-primary-700 hover:underline focus:outline-none focus:ring-2 focus:ring-primary-500 px-1 py-0.5 rounded",children:F?jsxs(Fragment,{children:[jsx(ChevronUp,{className:"h-3 w-3"}),b]}):jsxs(Fragment,{children:[jsx(ChevronDown,{className:"h-3 w-3"}),g]})}),F&&ue(n.payload)]}),jsxs("div",{className:"flex items-center gap-1 text-xs text-gray-500 whitespace-nowrap",children:[jsx(Clock,{className:"h-3 w-3"}),jsx("span",{title:new Date(n.created_at).toLocaleString("es-ES"),children:formatDistanceToNow(new Date(n.created_at),{addSuffix:true,locale:es})})]})]})})]},n.id)})})]})}function ja(){let[e,t]=useState([]);return {events:e,addEvent:m=>{let f={...m,id:`audit_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,created_at:new Date().toISOString()};return t(u=>[f,...u]),f},clearEvents:()=>{t([]);}}}function he(...e){return e.flat().filter(Boolean).join(" ")}var ua=forwardRef(({item:e,renderItem:t,actions:s=[],onAction:o,onCancel:m,titleEs:f="Revisar Elemento",titleEn:u="Review Item",reasonLabelEs:x="Comentarios",reasonLabelEn:g="Comments",reasonPlaceholderEs:b="Agregar comentarios...",reasonPlaceholderEn:p="Add comments...",cancelButtonEs:y="Cancelar",cancelButtonEn:E="Cancel",confirmButtonEs:N="Confirmar",confirmButtonEn:j="Confirm",loading:M=false,error:l,locale:I="es",className:R,itemClassName:B,actionsClassName:T,...ue},n)=>{let[C,F]=useState(null),[G,_]=useState(""),[oe,le]=useState(false),c=useCallback((A,de)=>I==="es"?A:de||A,[I]);s.length>4&&console.warn(`BIRHAUS ApprovalWorkflow: ${s.length} actions exceed 4-3-1 cognitive rule recommendation of 4. Consider consolidating actions or using progressive disclosure.`);let S=C?s.find(A=>A.key===C):null,ye=useCallback(A=>{F(A),_("");},[]),ce=useCallback(async()=>{if(!(!C||!S)&&!(S.requiresReason&&!G.trim()))try{le(!0),await o(C,e,G.trim()||void 0);}catch(A){console.error("Approval action failed:",A);}finally{le(false);}},[C,S,G,o,e]),ge=useCallback(()=>{F(null),_(""),m?.();},[m]),pe=useCallback(()=>{F(null),_("");},[]),H=c(f,u);return jsxs("div",{ref:n,className:he("birhaus-approval-workflow space-y-6",R),...ue,children:[jsx("div",{className:"flex items-center justify-between",children:jsx("h2",{className:"text-xl font-semibold text-gray-900",children:H})}),l&&jsx("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertTriangle,{className:"w-5 h-5 text-red-600 mt-0.5 flex-shrink-0"}),jsx("p",{className:"text-sm text-red-800",children:l})]})}),jsx("div",{className:he("bg-gray-50 border border-gray-200 rounded-lg p-6",B),children:t(e)}),C?jsxs("div",{className:"space-y-4",children:[S&&jsx("div",{className:"p-4 bg-amber-50 border border-amber-200 rounded-lg",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertTriangle,{className:"w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0"}),jsx("div",{className:"flex-1",children:jsx("p",{className:"text-sm font-medium text-amber-900",children:c(S.confirmationMessageEs||`Confirmar: ${S.labelEs}`,S.confirmationMessageEn||`Confirm: ${S.labelEn||S.labelEs}`)})})]})}),jsxs("div",{children:[jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[c(x,g),S?.requiresReason&&jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),jsx("textarea",{value:G,onChange:A=>_(A.target.value),placeholder:c(b,p),rows:3,className:he("w-full px-3 py-2 border border-gray-300 rounded-lg","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent","disabled:opacity-50 disabled:cursor-not-allowed","resize-none"),disabled:oe}),S?.requiresReason&&!G.trim()&&jsx("p",{className:"text-xs text-red-600 mt-1",children:I==="es"?"Este campo es requerido":"This field is required"})]}),jsxs("div",{className:"flex gap-3",children:[jsxs("button",{type:"button",onClick:pe,disabled:oe,className:he("inline-flex items-center px-4 py-2 text-sm font-medium","text-gray-700 bg-white border border-gray-300 rounded-lg","hover:bg-gray-50 hover:border-gray-400","focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-1","disabled:opacity-50 disabled:cursor-not-allowed","transition-all duration-200"),children:[jsx(RotateCcw,{className:"w-4 h-4 mr-2"}),I==="es"?"Volver":"Back"]}),jsx("button",{type:"button",onClick:ce,disabled:oe||S?.requiresReason&&!G.trim(),className:he("inline-flex items-center px-4 py-2 text-sm font-medium rounded-lg","focus:outline-none focus:ring-2 focus:ring-offset-1","disabled:opacity-50 disabled:cursor-not-allowed","transition-all duration-200 flex-1 justify-center",S?.variant==="primary"&&["bg-blue-600 text-white","hover:bg-blue-700 focus:ring-blue-500"],S?.variant==="danger"&&["bg-red-600 text-white","hover:bg-red-700 focus:ring-red-500"],(!S?.variant||S?.variant==="secondary")&&["bg-gray-600 text-white","hover:bg-gray-700 focus:ring-gray-500"]),children:oe?jsxs(Fragment,{children:[jsx("div",{className:"animate-spin w-4 h-4 border-2 border-current border-t-transparent rounded-full mr-2"}),I==="es"?"Procesando...":"Processing..."]}):jsxs(Fragment,{children:[S?.icon&&jsx(S.icon,{className:"w-4 h-4 mr-2"}),c(N,j)]})})]})]}):jsxs("div",{className:he("space-y-4",T),children:[jsx("div",{className:"flex flex-wrap gap-3",children:s.map(A=>{let de=A.icon,U=c(A.labelEs,A.labelEn);return jsxs("button",{type:"button",onClick:()=>ye(A.key),disabled:M,className:he("inline-flex items-center px-4 py-2 text-sm font-medium rounded-lg","border transition-all duration-200 flex-1 md:flex-none","focus:outline-none focus:ring-2 focus:ring-offset-1","disabled:opacity-50 disabled:cursor-not-allowed",A.variant==="primary"&&["bg-blue-600 text-white border-blue-600","hover:bg-blue-700 hover:border-blue-700","focus:ring-blue-500"],A.variant==="secondary"&&["bg-white text-gray-700 border-gray-300","hover:bg-gray-50 hover:border-gray-400","focus:ring-gray-500"],A.variant==="danger"&&["bg-red-600 text-white border-red-600","hover:bg-red-700 hover:border-red-700","focus:ring-red-500"]),children:[de&&jsx(de,{className:"w-4 h-4 mr-2"}),U]},A.key)})}),m&&jsx("div",{className:"flex justify-end",children:jsx("button",{type:"button",onClick:ge,disabled:M,className:he("text-sm text-gray-500 hover:text-gray-700","disabled:opacity-50 disabled:cursor-not-allowed"),children:c(y,E)})})]})]})});ua.displayName="BirhausApprovalWorkflow";function La(){let[e,t]=useState(null),[s,o]=useState(false),[m,f]=useState(null),u=useCallback(b=>{t(b),f(null);},[]),x=useCallback(()=>{t(null),f(null);},[]),g=useCallback(async(b,p,y,E)=>{if(E)try{o(!0),f(null),await E(b,p,y),x();}catch(N){throw f(N instanceof Error?N.message:"An error occurred"),N}finally{o(false);}},[x]);return {item:e,loading:s,error:m,startApproval:u,clearApproval:x,handleAction:g,setError:f}}var Fa={approveReject:[{key:"approve",labelEs:"Aprobar",labelEn:"Approve",variant:"primary",icon:CheckCircle,confirmationMessageEs:"Esta acci\xF3n aprobar\xE1 el elemento.",confirmationMessageEn:"This action will approve the item."},{key:"reject",labelEs:"Rechazar",labelEn:"Reject",variant:"danger",icon:XCircle,requiresReason:true,confirmationMessageEs:"Esta acci\xF3n rechazar\xE1 el elemento.",confirmationMessageEn:"This action will reject the item."}],financialApproval:[{key:"approve",labelEs:"Aprobar Transacci\xF3n",labelEn:"Approve Transaction",variant:"primary",icon:CheckCircle,confirmationMessageEs:"Esta acci\xF3n procesar\xE1 la transacci\xF3n y actualizar\xE1 los registros financieros.",confirmationMessageEn:"This action will process the transaction and update financial records."},{key:"reject",labelEs:"Rechazar Transacci\xF3n",labelEn:"Reject Transaction",variant:"danger",icon:XCircle,requiresReason:true,confirmationMessageEs:"Esta acci\xF3n cancelar\xE1 la transacci\xF3n y notificar\xE1 al solicitante.",confirmationMessageEn:"This action will cancel the transaction and notify the requester."}],documentApproval:[{key:"approve",labelEs:"Aprobar Documento",labelEn:"Approve Document",variant:"primary",icon:CheckCircle,confirmationMessageEs:"Esta acci\xF3n marcar\xE1 el documento como aprobado.",confirmationMessageEn:"This action will mark the document as approved."},{key:"request_changes",labelEs:"Solicitar Cambios",labelEn:"Request Changes",variant:"secondary",requiresReason:true,confirmationMessageEs:"Esta acci\xF3n solicitar\xE1 cambios en el documento.",confirmationMessageEn:"This action will request changes to the document."},{key:"reject",labelEs:"Rechazar Documento",labelEn:"Reject Document",variant:"danger",icon:XCircle,requiresReason:true,confirmationMessageEs:"Esta acci\xF3n rechazar\xE1 permanentemente el documento.",confirmationMessageEn:"This action will permanently reject the document."}]};function ee(...e){return e.flat().filter(Boolean).join(" ")}var fa={general:Settings,academic:GraduationCap,financial:DollarSign,administrative:Building},va={general:"bg-purple-100 text-purple-700 border-purple-200",academic:"bg-blue-100 text-blue-700 border-blue-200",financial:"bg-green-100 text-green-700 border-green-200",administrative:"bg-amber-100 text-amber-700 border-amber-200"},ha=forwardRef(({user:e,availableRoles:t,onRoleChange:s,onClose:o,onSuccess:m,titleEs:f="Gesti\xF3n de Roles de Usuario",titleEn:u="User Role Management",primaryRoleLabelEs:x="Rol Principal",primaryRoleLabelEn:g="Primary Role",additionalRolesLabelEs:b="Roles Adicionales",additionalRolesLabelEn:p="Additional Roles",assignPrimaryRoleLabelEs:y="Asignar rol principal",assignPrimaryRoleLabelEn:E="Assign primary role",addAdditionalRoleLabelEs:N="Agregar rol adicional",addAdditionalRoleLabelEn:j="Add additional role",changeLabelEs:M="Cambiar",changeLabelEn:l="Change",removeLabelEs:I="Remover",removeLabelEn:R="Remove",showAdvancedLabelEs:B="Mostrar",showAdvancedLabelEn:T="Show",hideAdvancedLabelEs:ue="Ocultar",hideAdvancedLabelEn:n="Hide",cancelLabelEs:C="Cancelar",cancelLabelEn:F="Cancel",saveLabelEs:G="Guardar Cambios",saveLabelEn:_="Save Changes",warningTitleEs:oe="Importante sobre los cambios de roles",warningTitleEn:le="Important about role changes",warningMessageEs:c="Los cambios en los roles afectar\xE1n inmediatamente los permisos del usuario. Se recomienda notificar al usuario sobre estos cambios.",warningMessageEn:S="Role changes will immediately affect user permissions. It is recommended to notify the user about these changes.",loading:ye=false,error:ce=null,locale:ge="es",showAdvancedByDefault:pe=false,maxAdditionalRoles:H=5,allowPrimaryRoleChange:A=true,allowMultipleRoles:de=true,renderUserInfo:U,renderRoleMetadata:be,getRoleIcon:ke,getRoleColor:Q,className:Se,headerClassName:Le,contentClassName:X$1,actionsClassName:Ne,...W},Fe)=>{let[D,me]=useState(e.primaryRole||null),[q,Te]=useState(e.additionalRoles||[]),[te,$e]=useState(pe),[ze,fe]=useState(false),[re,Ie]=useState("primary"),[V,qe]=useState(false),[J,ve]=useState([]),Y=useCallback((d,ne)=>ge==="es"?d:ne||d,[ge]),Ae=useCallback(d=>ke?.(d)||fa[d]||Settings,[ke]),Pe=useCallback(d=>Q?.(d)||va[d]||"bg-gray-100 text-gray-700 border-gray-200",[Q]);useEffect(()=>{q.length>H&&console.warn(`BIRHAUS RoleManager: ${q.length} additional roles exceed Miller's Law limit of ${H}. Consider reducing role count or implementing progressive disclosure.`);},[q.length,H]);let He=useCallback(()=>{let d=[];return A&&d.push(D?"change_primary":"assign_primary"),de&&q.length<H&&d.push("add_additional"),q.length>0&&d.push("manage_additional"),d},[A,de,D,q.length,H]),We=useCallback(async d=>{let ne=D;me(d);let je={type:"primary_role_assigned",userId:e.id,roleId:d.id,role:d,oldValue:ne,newValue:d,timestamp:new Date().toISOString()};ve(we=>[...we,je]),fe(false);},[D,e.id]),Ve=useCallback(async d=>{if(q.some(we=>we.id===d.id)){fe(false);return}if(q.length>=H){console.warn(`BIRHAUS RoleManager: Cannot add more than ${H} additional roles (Miller's Law compliance)`),fe(false);return}let ne=[...q,d];Te(ne);let je={type:"additional_role_added",userId:e.id,roleId:d.id,role:d,newValue:d,timestamp:new Date().toISOString()};ve(we=>[...we,je]),fe(false);},[q,H,e.id]),h=useCallback(d=>{let ne=q.find(Me=>Me.id===d);if(!ne)return;let je=q.filter(Me=>Me.id!==d);Te(je);let we={type:"additional_role_removed",userId:e.id,roleId:d,role:ne,oldValue:ne,timestamp:new Date().toISOString()};ve(Me=>[...Me,we]);},[q,e.id]),k=useCallback(async()=>{if(J.length===0){m?.();return}qe(true);try{for(let d of J)await s(d);ve([]),m?.();}catch(d){console.error("Error processing role changes:",d);}finally{qe(false);}},[J,s,m]),z=useCallback(()=>{me(e.primaryRole||null),Te(e.additionalRoles||[]),ve([]),$e(pe),o?.();},[e.primaryRole,e.additionalRoles,pe,o]),se=useCallback(d=>{Ie(d),fe(true);},[]),Ue=He();Ue.length>4&&console.warn(`BIRHAUS RoleManager: ${Ue.length} actions exceed 4-3-1 cognitive rule recommendation of 4. Consider consolidating actions or using progressive disclosure.`);let Ye=Y(f,u);return jsxs("div",{ref:Fe,className:ee("birhaus-role-manager space-y-6",Se),...W,children:[jsxs("div",{className:ee("flex items-center justify-between",Le),children:[jsx("h2",{className:"text-xl font-semibold text-gray-900",children:Ye}),o&&jsx("button",{onClick:z,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",disabled:V,children:jsx(X,{className:"w-5 h-5 text-gray-500"})})]}),ce&&jsx("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertCircle,{className:"w-5 h-5 text-red-600 mt-0.5 flex-shrink-0"}),jsx("p",{className:"text-sm text-red-800",children:ce})]})}),jsxs("div",{className:ee("space-y-6",X$1),children:[jsx("div",{className:"bg-gray-50 rounded-lg p-4 border border-gray-200",children:U?U(e):jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"w-12 h-12 rounded-full bg-gradient-to-br from-blue-600 to-blue-700 flex items-center justify-center text-white font-medium",children:e.fullName.split(" ").map(d=>d[0]).join("").slice(0,2).toUpperCase()}),jsxs("div",{children:[jsx("h3",{className:"font-medium text-gray-900",children:e.fullName}),jsx("p",{className:"text-sm text-gray-600",children:e.email})]})]})}),jsxs("div",{children:[jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:Y(x,g)}),jsx("div",{className:"space-y-2",children:D?jsx("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:ee("p-2 rounded-lg",Pe(D.module)),children:(()=>{let d=Ae(D.module);return jsx(d,{className:"h-4 w-4"})})()}),jsxs("div",{children:[jsx("h4",{className:"font-medium text-gray-900",children:D.name}),D.description&&jsx("p",{className:"text-sm text-gray-500",children:D.description}),be&&D.metadata&&jsx("div",{className:"mt-2",children:be(D,D.metadata)})]})]}),A&&jsx("button",{onClick:()=>se("primary"),className:"text-blue-600 hover:text-blue-700 text-sm font-medium transition-colors",disabled:V,children:Y(M,l)})]})}):A&&jsx("button",{onClick:()=>se("primary"),className:"w-full p-4 border-2 border-dashed border-gray-300 rounded-lg hover:border-gray-400 transition-colors",disabled:V,children:jsxs("div",{className:"flex items-center justify-center gap-2 text-gray-600",children:[jsx(Plus,{className:"w-5 h-5"}),jsx("span",{children:Y(y,E)})]})})})]}),de&&jsxs("div",{children:[jsxs("div",{className:"flex items-center justify-between mb-2",children:[jsxs("label",{className:"text-sm font-medium text-gray-700",children:[Y(b,p),q.length>0&&jsxs("span",{className:"ml-2 text-xs text-gray-500",children:["(",q.length,"/",H,")"]})]}),jsxs("button",{onClick:()=>$e(!te),className:"text-sm text-gray-600 hover:text-gray-900 flex items-center gap-1 transition-colors",children:[te?jsx(ChevronUp,{className:"w-4 h-4"}):jsx(ChevronDown,{className:"w-4 h-4"}),te?Y(ue,n):Y(B,T)]})]}),te&&jsxs("div",{className:"space-y-2",children:[q.map(d=>jsx("div",{className:"bg-white border border-gray-200 rounded-lg p-3",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:ee("p-1.5 rounded",Pe(d.module)),children:(()=>{let ne=Ae(d.module);return jsx(ne,{className:"h-4 w-4"})})()}),jsxs("div",{children:[jsx("h5",{className:"text-sm font-medium text-gray-900",children:d.name}),d.description&&jsx("p",{className:"text-xs text-gray-500",children:d.description}),be&&d.metadata&&jsx("div",{className:"mt-1",children:be(d,d.metadata)})]})]}),jsx("button",{onClick:()=>h(d.id),className:"p-1 hover:bg-red-50 rounded text-red-600 hover:text-red-700 transition-colors",disabled:V,children:jsx(Trash2,{className:"w-4 h-4"})})]})},d.id)),q.length<H&&jsx("button",{onClick:()=>se("additional"),className:"w-full p-3 border-2 border-dashed border-gray-300 rounded-lg hover:border-gray-400 transition-colors",disabled:V,children:jsxs("div",{className:"flex items-center justify-center gap-2 text-gray-600 text-sm",children:[jsx(Plus,{className:"w-4 h-4"}),jsx("span",{children:Y(N,j)})]})})]})]}),jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertCircle,{className:"w-5 h-5 text-amber-600 mt-0.5 flex-shrink-0"}),jsxs("div",{className:"space-y-1",children:[jsx("p",{className:"text-sm font-medium text-amber-900",children:Y(oe,le)}),jsx("p",{className:"text-sm text-amber-700",children:Y(c,S)})]})]})})]}),jsxs("div",{className:ee("flex items-center justify-between gap-3 pt-4 border-t",Ne),children:[jsx("div",{className:"text-sm text-gray-600",children:J.length>0&&jsxs("span",{className:"flex items-center gap-1",children:[jsx(AlertCircle,{className:"w-4 h-4"}),ge==="es"?`${J.length} cambio${J.length!==1?"s":""} pendiente${J.length!==1?"s":""}`:`${J.length} pending change${J.length!==1?"s":""}`]})}),jsxs("div",{className:"flex items-center gap-3",children:[o&&jsxs("button",{onClick:z,className:ee("inline-flex items-center px-4 py-2 text-sm font-medium","text-gray-700 bg-white border border-gray-300 rounded-lg","hover:bg-gray-50 hover:border-gray-400","focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-1","disabled:opacity-50 disabled:cursor-not-allowed","transition-all duration-200"),disabled:V,children:[jsx(RotateCcw,{className:"w-4 h-4 mr-2"}),Y(C,F)]}),jsx("button",{onClick:k,className:ee("inline-flex items-center px-4 py-2 text-sm font-medium rounded-lg","bg-blue-600 text-white border border-blue-600","hover:bg-blue-700 hover:border-blue-700","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1","disabled:opacity-50 disabled:cursor-not-allowed","transition-all duration-200"),disabled:V||J.length===0,children:V?jsxs(Fragment,{children:[jsx("div",{className:"animate-spin w-4 h-4 border-2 border-current border-t-transparent rounded-full mr-2"}),ge==="es"?"Guardando...":"Saving..."]}):jsxs(Fragment,{children:[jsx(Save,{className:"w-4 h-4 mr-2"}),Y(G,_)]})})]})]}),ze&&jsx(Ka,{roles:t,selectedRoleId:re==="primary"?D?.id:void 0,excludeRoleIds:[...D?[D.id]:[],...q.map(d=>d.id)],onSelect:re==="primary"?We:Ve,onClose:()=>fe(false),locale:ge,titleEs:re==="primary"?"Seleccionar Rol Principal":"Seleccionar Rol Adicional",titleEn:re==="primary"?"Select Primary Role":"Select Additional Role",getModuleIcon:Ae,getModuleColor:Pe})]})});ha.displayName="BirhausRoleManager";function Ka({roles:e,selectedRoleId:t,excludeRoleIds:s=[],onSelect:o,onClose:m,locale:f="es",titleEs:u="Seleccionar Rol",titleEn:x="Select Role",getModuleIcon:g=p=>fa[p]||Settings,getModuleColor:b=p=>va[p]||"bg-gray-100 text-gray-700 border-gray-200"}){let[p,y]=useState(null),E=e.filter(R=>R.isActive!==false&&!s.includes(R.id)),N=E.reduce((R,B)=>(R[B.module]||(R[B.module]=[]),R[B.module].push(B),R),{}),j=E.length;j>9&&console.warn(`BIRHAUS RoleSelector: ${j} roles exceed Miller's Law guideline of 7\xB12 items. Consider implementing search/filtering or grouping for better usability.`);let M=R=>{y(R);},l=()=>{p&&o(p);};return jsx("div",{className:"fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4",children:jsxs("div",{className:"bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[jsxs("div",{className:"flex items-center justify-between p-6 border-b bg-gray-50/50",children:[jsx("h3",{className:"text-lg font-semibold text-gray-900",children:f==="es"?u:x}),jsx("button",{onClick:m,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:jsx(X,{className:"w-5 h-5 text-gray-500"})})]}),jsx("div",{className:"p-6 space-y-4 overflow-y-auto max-h-[60vh]",children:Object.entries(N).map(([R,B])=>jsxs("div",{className:"space-y-2",children:[jsxs("div",{className:"flex items-center space-x-2 text-sm font-medium text-gray-700",children:[(()=>{let T=g(R);return jsx(T,{className:"w-4 h-4"})})(),jsx("span",{children:R.charAt(0).toUpperCase()+R.slice(1)})]}),jsx("div",{className:"grid gap-2",children:B.map(T=>jsxs("button",{onClick:()=>M(T),className:ee("p-4 rounded-lg border-2 transition-all text-left relative",p?.id===T.id?"border-blue-600 bg-blue-50":ee("border-gray-200 hover:border-gray-300 hover:shadow-sm",b(T.module))),children:[p?.id===T.id&&jsx("div",{className:"absolute top-3 right-3",children:jsx(Check,{className:"w-5 h-5 text-blue-600"})}),jsxs("div",{className:"pr-8",children:[jsx("h4",{className:"font-medium text-gray-900",children:T.name}),T.description&&jsx("p",{className:"text-sm text-gray-600 mt-1",children:T.description}),jsx("div",{className:"flex items-center space-x-2 mt-2",children:jsxs("span",{className:"text-xs bg-white/50 px-2 py-1 rounded",children:[f==="es"?"Nivel":"Level"," ",T.hierarchyLevel]})})]})]},T.id))})]},R))}),jsxs("div",{className:"flex items-center justify-end gap-3 p-6 border-t bg-gray-50/50",children:[jsx("button",{onClick:m,className:ee("inline-flex items-center px-4 py-2 text-sm font-medium","text-gray-700 bg-white border border-gray-300 rounded-lg","hover:bg-gray-50 hover:border-gray-400","focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-1","transition-all duration-200"),children:f==="es"?"Cancelar":"Cancel"}),jsxs("button",{onClick:l,disabled:!p,className:ee("inline-flex items-center px-4 py-2 text-sm font-medium rounded-lg","bg-blue-600 text-white border border-blue-600","hover:bg-blue-700 hover:border-blue-700","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1","disabled:opacity-50 disabled:cursor-not-allowed","transition-all duration-200"),children:[jsx(UserCheck,{className:"w-4 h-4 mr-2"}),f==="es"?"Seleccionar":"Select"]})]})]})})}function Qa(e){let[t,s]=useState(e),[o,m]=useState(false),[f,u]=useState(null),[x,g]=useState([]),b=useCallback(N=>{s(N),u(null);},[]),p=useCallback(async(N,j)=>{if(!j){g(M=>[...M,N]);return}try{m(!0),u(null),await j(N),g([]);}catch(M){throw u(M instanceof Error?M.message:"An error occurred"),M}finally{m(false);}},[]),y=useCallback(()=>{g([]),u(null);},[]),E=x.length>0;return {user:t,loading:o,error:f,changes:x,hasUnsavedChanges:E,updateUser:b,handleRoleChange:p,clearChanges:y,setError:u}}var Xa={education:{maxAdditionalRoles:3,allowMultipleRoles:true,modules:["academic","administrative","general"],hierarchyLevels:{superAdmin:1,director:10,coordinator:20,teacher:30,staff:40}},financial:{maxAdditionalRoles:2,allowMultipleRoles:true,modules:["financial","administrative","general"],hierarchyLevels:{cfo:1,manager:10,analyst:20,clerk:30}},corporate:{maxAdditionalRoles:4,allowMultipleRoles:true,modules:["administrative","general"],hierarchyLevels:{ceo:1,vp:5,director:10,manager:20,employee:30}}};function Re(...e){return e.flat().filter(Boolean).join(" ")}var st=forwardRef(function({placeholderEs:t="Buscar elementos...",placeholderEn:s,emptyStateMessageEs:o="No se encontraron elementos para tu b\xFAsqueda",emptyStateMessageEn:m,loadingMessageEs:f="Buscando...",loadingMessageEn:u,searchDelay:x=300,minSearchLength:g=2,maxResults:b=7,fuzzyThreshold:p=.6,enableRecentSearches:y=true,enableSuggestions:E=true,enableMultiSelect:N=false,maxSelections:j=5,showSelectedCount:M=true,filters:l=[],showFilters:I=false,enableAdvancedFilters:R=false,onSearch:B,onSelect:T,onMultiSelect:ue,onClearSelection:n,onFiltersChange:C,renderItem:F,renderEmptyState:G,renderLoadingState:_,className:oe,dropdownClassName:le,itemClassName:c,initialQuery:S="",initialFilters:ye={},preselectedItems:ce=[],ariaLabel:ge,ariaDescription:pe,autoFocus:H=false,clearOnSelect:A=!N},de){let[U,be]=useState(S),[ke,Q]=useState(false),[Se,Le]=useState(false),[X$1,Ne]=useState({items:[],total:0,hasMore:false}),[W,Fe]=useState(ce),[D,me]=useState(-1),[q,Te]=useState([]),[te,$e]=useState(ye),[ze,fe]=useState(false),re=useRef(null),Ie=useRef(null),V=useRef();Za.useImperativeHandle(de,()=>({focus:()=>re.current?.focus(),clear:Ae,getQuery:()=>U,getSelectedItems:()=>W,setQuery:h=>be(h)}),[U,W]),useEffect(()=>{H&&re.current&&re.current.focus();},[H]),useEffect(()=>{let h=k=>{Ie.current&&!Ie.current.contains(k.target)&&!re.current?.contains(k.target)&&(Q(false),me(-1));};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]),useEffect(()=>(V.current&&clearTimeout(V.current),U.length>=g?V.current=setTimeout(()=>{qe(U,te);},x):U.length===0?J():(Ne({items:[],total:0,hasMore:false}),Q(false)),()=>{V.current&&clearTimeout(V.current);}),[U,te]);let qe=useCallback(async(h,k)=>{Le(true);try{let z=await B(h,k),se=z.items.slice(0,b);Ne({...z,items:se}),Q(!0),me(-1),y&&h.trim()&&Te(Ue=>{let Ye=Ue.filter(d=>d!==h.trim());return [h.trim(),...Ye].slice(0,5)});}catch(z){console.error("BIRHAUS SmartSearch error:",z),Ne({items:[],total:0,hasMore:false});}finally{Le(false);}},[B,b,y]),J=useCallback(async()=>{if(!(!y&&!E))try{let h=await B("",{...te,showRecent:!0}),k=h.items.slice(0,b);Ne({...h,items:k}),k.length>0&&Q(!0);}catch{}},[y,E,B,te,b]),ve=h=>{if(N){let k=W.some(se=>se.id===h.id),z;if(k)z=W.filter(se=>se.id!==h.id);else if(W.length<j)z=[...W,h];else {console.warn("BIRHAUS Warning: Maximum selections exceeded (Miller's Law)");return}Fe(z),ue?.(z);}else T?.(h,W),A&&(be(""),Q(false));me(-1);},Y=h=>{if(!(!ke||X$1.items.length===0))switch(h.key){case "ArrowDown":h.preventDefault(),me(k=>k<X$1.items.length-1?k+1:k);break;case "ArrowUp":h.preventDefault(),me(k=>k>0?k-1:-1);break;case "Enter":h.preventDefault(),D>=0&&D<X$1.items.length&&ve(X$1.items[D]);break;case "Escape":h.preventDefault(),Q(false),me(-1);break}},Ae=()=>{be(""),Q(false),me(-1),Ne({items:[],total:0,hasMore:false}),re.current?.focus();},Pe=()=>{Fe([]),n?.();},He=(h,k)=>{let z={...te,[h]:k};$e(z),C?.(z);},We=(h,k)=>{let z=N?W.some(se=>se.id===h.id):k===D;return F?F(h,z,N):jsx(nt,{item:h,isSelected:z,isMultiSelect:N,className:c})},Ve=s&&typeof window<"u"&&navigator.language.startsWith("en")?s:t;return jsxs("div",{className:Re("relative",oe),ref:Ie,children:[jsxs("div",{className:"relative",children:[jsx(Search,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400"}),jsx("input",{ref:re,type:"text",value:U,onChange:h=>{be(h.target.value),h.target.value.length>0&&Q(true);},onFocus:()=>{(X$1.items.length>0||U.length===0)&&(Q(true),U.length===0&&J());},onKeyDown:Y,placeholder:Ve,className:Re("w-full pl-10 pr-10 py-3 border rounded-lg","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent","placeholder-gray-400 text-gray-900 bg-white","transition-shadow duration-200"),"aria-label":ge,"aria-describedby":pe?"search-description":void 0}),Se&&jsx("div",{className:"absolute right-3 top-1/2 transform -translate-y-1/2",children:jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-500"})}),!Se&&U&&jsx("button",{onClick:Ae,className:"absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600","aria-label":"Limpiar b\xFAsqueda",children:jsx(X,{className:"w-4 h-4"})})]}),N&&W.length>0&&jsxs("div",{className:"mt-2 flex items-center justify-between text-sm",children:[jsx("div",{className:"flex items-center space-x-2",children:jsxs("span",{className:"text-gray-600",children:[W.length," seleccionado",W.length!==1?"s":"",j&&` de ${j}`]})}),jsx("button",{onClick:Pe,className:"text-blue-600 hover:text-blue-800 font-medium",children:"Limpiar selecci\xF3n"})]}),I&&l.length>0&&jsx("div",{className:"mt-2",children:jsx(it,{filters:l,activeFilters:te,onFilterChange:He,showAdvanced:ze,onToggleAdvanced:()=>fe(!ze),enableAdvanced:R})}),ke&&jsx("div",{className:Re("absolute z-50 w-full mt-1 bg-white border rounded-lg shadow-lg max-h-96 overflow-auto",le),children:Se&&_?_():Se?jsxs("div",{className:"px-4 py-8 text-center text-gray-500",children:[jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500 mx-auto mb-2"}),u&&typeof window<"u"&&navigator.language.startsWith("en")?u:f]}):X$1.items.length===0?G?G():jsxs("div",{className:"px-4 py-8 text-center text-gray-500",children:[jsx(Search,{className:"w-8 h-8 mx-auto mb-2 text-gray-400"}),jsx("p",{className:"text-sm",children:U?m&&typeof window<"u"&&navigator.language.startsWith("en")?m:o:"Comienza a escribir para buscar..."})]}):jsxs(Fragment,{children:[U&&jsxs("div",{className:"px-3 py-2 text-xs font-semibold text-gray-500 uppercase bg-gray-50 border-b",children:["Resultados (",X$1.total,")",X$1.hasMore&&` - Mostrando primeros ${b}`]}),!U&&jsx("div",{className:"px-3 py-2 text-xs font-semibold text-gray-500 uppercase bg-gray-50 border-b",children:y?"Recientes":"Sugerencias"}),X$1.items.map((h,k)=>jsx("div",{className:Re("border-b last:border-b-0 cursor-pointer transition-colors",k===D&&"bg-blue-50",N&&W.some(z=>z.id===h.id)&&"bg-blue-50"),onClick:()=>ve(h),children:We(h,k)},h.id)),X$1.hasMore&&jsx("div",{className:"px-3 py-2 text-xs text-center text-gray-500 bg-gray-50",children:"Hay m\xE1s resultados disponibles - refina tu b\xFAsqueda"})]})}),pe&&jsx("div",{id:"search-description",className:"sr-only",children:pe})]})});function nt({item:e,isSelected:t,isMultiSelect:s,className:o}){let m=typeof e.icon=="function"?e.icon:null;return jsxs("div",{className:Re("w-full px-3 py-3 text-left hover:bg-gray-50 flex items-start space-x-3",t&&"bg-blue-50",o),children:[jsx("div",{className:"p-2 rounded-lg bg-gray-100 text-gray-600 flex-shrink-0",children:m?jsx(m,{className:"w-4 h-4"}):typeof e.icon=="object"?e.icon:jsx(Search,{className:"w-4 h-4"})}),jsxs("div",{className:"flex-1 min-w-0",children:[jsxs("div",{className:"flex items-start justify-between",children:[jsxs("div",{className:"flex-1",children:[jsx("p",{className:"font-medium text-gray-900 truncate",children:e.title}),e.subtitle&&jsx("p",{className:"text-sm text-gray-500 truncate",children:e.subtitle})]}),jsxs("div",{className:"flex items-center space-x-2 ml-2 flex-shrink-0",children:[e.recentlyUsed&&jsxs("span",{className:"text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full flex items-center",children:[jsx(Clock,{className:"w-3 h-3 mr-1"}),"Reciente"]}),e.badge&&jsx("span",{className:Re("text-xs px-2 py-0.5 rounded-full",e.badge.variant==="success"&&"bg-green-100 text-green-700",e.badge.variant==="warning"&&"bg-yellow-100 text-yellow-700",e.badge.variant==="error"&&"bg-red-100 text-red-700",e.badge.variant==="info"&&"bg-blue-100 text-blue-700",e.badge.variant==="neutral"&&"bg-gray-100 text-gray-700"),children:e.badge.labelEs}),s&&t&&jsx(CheckCircle,{className:"w-4 h-4 text-blue-600"})]})]}),e.description&&jsx("p",{className:"mt-1 text-sm text-gray-600 line-clamp-2",children:e.description}),e.status&&jsxs("div",{className:"mt-2 flex items-center space-x-1 text-sm",children:[e.status.showIndicator&&jsxs(Fragment,{children:[e.status.variant==="success"&&jsx(CheckCircle,{className:"w-4 h-4 text-green-500"}),e.status.variant==="warning"&&jsx(AlertTriangle,{className:"w-4 h-4 text-yellow-500"}),e.status.variant==="error"&&jsx(AlertTriangle,{className:"w-4 h-4 text-red-500"}),e.status.variant==="info"&&jsx(AlertTriangle,{className:"w-4 h-4 text-blue-500"})]}),jsx("span",{className:Re(e.status.variant==="success"&&"text-green-600",e.status.variant==="warning"&&"text-yellow-600",e.status.variant==="error"&&"text-red-600",e.status.variant==="info"&&"text-blue-600"),children:e.status.labelEs})]})]})]})}function it({filters:e,activeFilters:t,onFilterChange:s,showAdvanced:o,onToggleAdvanced:m,enableAdvanced:f}){let u=e.filter(g=>g.visible!==false),x=e.filter(g=>g.visible===false);return jsxs("div",{className:"space-y-2",children:[u.length>0&&jsx("div",{className:"flex flex-wrap gap-2",children:u.map(g=>jsx(ya,{filter:g,value:t[g.key],onChange:b=>s(g.key,b)},g.key))}),f&&x.length>0&&jsxs("div",{className:"space-y-2",children:[jsxs("button",{onClick:m,className:"text-sm text-blue-600 hover:text-blue-800 flex items-center space-x-1",children:[jsx(Filter,{className:"w-4 h-4"}),jsxs("span",{children:[o?"Ocultar":"Mostrar"," filtros avanzados"]})]}),o&&jsx("div",{className:"flex flex-wrap gap-2 pt-2 border-t",children:x.map(g=>jsx(ya,{filter:g,value:t[g.key],onChange:b=>s(g.key,b)},g.key))})]})]})}function ya({filter:e,value:t,onChange:s}){switch(e.type){case "select":return jsxs("select",{value:t||"",onChange:o=>s(o.target.value||null),className:"px-3 py-1 border rounded text-sm",children:[jsx("option",{value:"",children:e.labelEs}),e.options?.map(o=>jsx("option",{value:o.value,children:o.labelEs},o.value))]});case "boolean":return jsxs("label",{className:"flex items-center space-x-2 text-sm",children:[jsx("input",{type:"checkbox",checked:t||false,onChange:o=>s(o.target.checked),className:"rounded"}),jsx("span",{children:e.labelEs})]});case "text":return jsx("input",{type:"text",value:t||"",onChange:o=>s(o.target.value||null),placeholder:e.labelEs,className:"px-3 py-1 border rounded text-sm"});default:return null}}function ot(){let[e,t]=useState([]),[s,o]=useState([]),m=useCallback(b=>{o(p=>{let y=p.filter(E=>E!==b);return [b,...y].slice(0,5)});},[]),f=useCallback(()=>{o([]);},[]),u=useCallback(b=>{t(p=>p.some(y=>y.id===b.id)?p:[...p,b]);},[]),x=useCallback(b=>{t(p=>p.filter(y=>y.id!==b));},[]),g=useCallback(()=>{t([]);},[]);return {selectedItems:e,recentSearches:s,addToRecent:m,clearRecent:f,addSelection:u,removeSelection:x,clearSelections:g,setSelectedItems:t}}var lt={fuzzyMatch:(e,t,s=.6)=>{let o=e.toLowerCase(),m=t.toLowerCase();if(m.includes(o))return true;let f=0;for(let x=0;x<m.length&&f<o.length;x++)m[x]===o[f]&&f++;return f/o.length>=s},highlightMatch:(e,t)=>{if(!t.trim())return e;let s=new RegExp(`(${t.trim().split(" ").join("|")})`,"gi");return e.replace(s,"<mark>$1</mark>")},sortByRelevance:(e,t)=>t.trim()?e.sort((s,o)=>{let m=s.title.toLowerCase(),f=o.title.toLowerCase(),u=t.toLowerCase(),x=m.includes(u)?1:0,g=f.includes(u)?1:0;if(x!==g)return g-x;let b=m.startsWith(u)?1:0,p=f.startsWith(u)?1:0;if(b!==p)return p-b;let y=s.recentlyUsed?1:0,E=o.recentlyUsed?1:0;return y!==E?E-y:(o.frequency||0)-(s.frequency||0)}):e.sort((s,o)=>(o.frequency||0)-(s.frequency||0))};var Rt={idioma:"es",moneda:"PYG",formatoNumero:"es-PY",mostrarGraficos:true,mostrarObjetivos:true,mostrarProyecciones:true,diasProyeccion:7,actualizacionAutomatica:false,intervaloActualizacion:15};function Ct({datos:e,color:t,altura:s=60,mostrarPuntos:o=false}){let{ruta:m,area:f,minY:u,maxY:x}=useMemo(()=>{if(e.length===0)return {ruta:"",area:"",minY:0,maxY:0};let g=e.map(I=>I.valor),b=Math.min(...g),p=Math.max(...g),y=p-b||1,E=200,N=4,j=e.map((I,R)=>{let B=R/(e.length-1)*(E-N*2)+N,T=s-N-(I.valor-b)/y*(s-N*2);return {x:B,y:T,valor:I.valor}}),M=j.reduce((I,R,B)=>`${I} ${B===0?"M":"L"} ${R.x} ${R.y}`,""),l=`${M} L ${j[j.length-1].x} ${s-N} L ${N} ${s-N} Z`;return {ruta:M,area:l,minY:b,maxY:p}},[e,s]);return e.length===0?jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:jsx(BarChart3,{className:"w-6 h-6"})}):jsxs("svg",{width:"200",height:s,className:"overflow-visible",children:[jsx("path",{d:f,fill:`url(#gradiente-${t.replace("#","")})`,opacity:.2}),jsx("path",{d:m,stroke:t,strokeWidth:2,fill:"none",strokeLinecap:"round",strokeLinejoin:"round"}),jsx("defs",{children:jsxs("linearGradient",{id:`gradiente-${t.replace("#","")}`,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:[jsx("stop",{offset:"0%",stopColor:t,stopOpacity:.4}),jsx("stop",{offset:"100%",stopColor:t,stopOpacity:0})]})}),o&&m&&e.map((g,b)=>{let p=b/(e.length-1)*192+4,y=s-4-(g.valor-u)/(x-u||1)*(s-8);return jsx("circle",{cx:p,cy:y,r:"2",fill:t,className:"opacity-60 hover:opacity-100 transition-opacity"},b)})]})}function St({tendencia:e,tama\u00F1o:t="mediano",mostrarTexto:s=true,idioma:o}){let m=e.direccion==="subida"?TrendingUp:e.direccion==="bajada"?TrendingDown:Minus,f=e.direccion==="subida"?"text-green-600":e.direccion==="bajada"?"text-red-600":"text-gray-500",u=t==="peque\xF1o"?"w-3 h-3":t==="grande"?"w-5 h-5":"w-4 h-4",x=o==="es"?e.direccion==="subida"?"Subida":e.direccion==="bajada"?"Bajada":"Estable":e.direccion==="subida"?"Up":e.direccion==="bajada"?"Down":"Stable";return jsxs("div",{className:`flex items-center space-x-1 ${f}`,children:[jsx(m,{className:u}),s&&jsxs("div",{className:"flex items-center space-x-1",children:[jsxs("span",{className:`font-medium ${t==="peque\xF1o"?"text-xs":t==="grande"?"text-base":"text-sm"}`,children:[e.porcentaje>=0?"+":"",e.porcentaje.toFixed(1),"%"]}),jsxs("span",{className:"text-xs text-gray-500",children:["(",x,")"]})]})]})}function At({estado:e,tama\u00F1o:t="mediano",idioma:s}){let o={saludable:{icono:CheckCircle,color:"text-green-600 bg-green-100",etiquetaEs:"Saludable",etiquetaEn:"Healthy"},precaucion:{icono:AlertCircle,color:"text-yellow-600 bg-yellow-100",etiquetaEs:"Precauci\xF3n",etiquetaEn:"Warning"},critico:{icono:AlertCircle,color:"text-red-600 bg-red-100",etiquetaEs:"Cr\xEDtico",etiquetaEn:"Critical"}},{icono:m,color:f,etiquetaEs:u,etiquetaEn:x}=o[e],g=t==="peque\xF1o"?"w-3 h-3":t==="grande"?"w-5 h-5":"w-4 h-4";return jsxs("div",{className:`flex items-center space-x-1 px-2 py-1 rounded-full text-xs ${f}`,children:[jsx(m,{className:g}),jsx("span",{className:"font-medium",children:s==="es"?u:x})]})}function Bt({metrica:e,configuracion:t,compacto:s=false,mostrarGrafico:o=true,alSeleccionar:m,alMostrarDetalles:f}){let[u,x]=useState(o),g=useMemo(()=>{let E=N=>new Intl.NumberFormat(t.formatoNumero,{style:"currency",currency:t.moneda,minimumFractionDigits:t.moneda==="PYG"?0:2,maximumFractionDigits:t.moneda==="PYG"?0:2}).format(N);return e.unidad==="moneda"?E(e.valor):e.unidad==="porcentaje"?`${e.valor.toFixed(1)}%`:`${e.valor.toLocaleString(t.formatoNumero)}`},[e.valor,e.unidad,t]),b=useMemo(()=>{if(!e.objetivo)return null;let E=e.valor/e.objetivo*100;return Math.min(E,100)},[e.valor,e.objetivo]),p=useMemo(()=>{switch(e.estado){case "saludable":return "#10b981";case "precaucion":return "#f59e0b";case "critico":return "#ef4444";default:return "#6366f1"}},[e.estado]),y=useMemo(()=>{switch(e.categoria){case "ingresos":return "bg-green-100 text-green-800";case "gastos":return "bg-red-100 text-red-800";case "balance":return "bg-blue-100 text-blue-800";case "proyeccion":return "bg-purple-100 text-purple-800";default:return "bg-gray-100 text-gray-800"}},[e.categoria]);return jsxs("div",{className:` relative overflow-hidden transition-all duration-200 hover:shadow-lg bg-white rounded-xl shadow-sm border border-gray-200 ${s?"p-4":"p-6"} ${m?"cursor-pointer hover:border-blue-300":""} ${e.estado==="critico"?"ring-2 ring-red-200 ring-opacity-50":""} ${e.estado==="precaucion"?"ring-2 ring-yellow-200 ring-opacity-50":""} ${e.estado==="saludable"?"ring-2 ring-green-200 ring-opacity-30":""} `,onClick:()=>m?.(e.id),children:[jsxs("div",{className:"flex items-start justify-between mb-4",children:[jsxs("div",{className:"flex-1",children:[jsxs("div",{className:"flex items-center space-x-2 mb-1",children:[jsx("h3",{className:`font-semibold text-gray-900 ${s?"text-sm":"text-base"}`,children:t.idioma==="es"?e.nombreEs:e.nombreEn}),jsx("span",{className:`px-2 py-1 text-xs font-medium rounded-full ${y}`,children:e.categoria})]}),jsx("p",{className:`text-gray-600 ${s?"text-xs":"text-sm"}`,children:t.idioma==="es"?e.descripcionEs:e.descripcionEn})]}),jsxs("div",{className:"flex items-center space-x-2",children:[jsx(At,{estado:e.estado,tama\u00F1o:s?"peque\xF1o":"mediano",idioma:t.idioma}),f&&jsx("button",{onClick:E=>{E.stopPropagation(),f(e.id);},className:"p-1 text-gray-400 hover:text-gray-600 transition-colors",children:jsx(Info,{className:"w-4 h-4"})})]})]}),jsxs("div",{className:"mb-4",children:[jsx("div",{className:`font-bold text-gray-900 ${s?"text-2xl":"text-3xl"}`,children:g}),jsxs("div",{className:"flex items-center justify-between mt-2",children:[jsx(St,{tendencia:e.tendencia,tama\u00F1o:s?"peque\xF1o":"mediano",idioma:t.idioma}),jsx("span",{className:`text-gray-500 ${s?"text-xs":"text-sm"}`,children:e.tendencia.periodo})]})]}),t.mostrarObjetivos&&e.objetivo&&b!==null&&jsxs("div",{className:"mb-4",children:[jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxs("span",{className:`text-gray-600 flex items-center space-x-1 ${s?"text-xs":"text-sm"}`,children:[jsx(Target,{className:"w-3 h-3"}),jsx("span",{children:t.idioma==="es"?"Objetivo":"Target"})]}),jsx("span",{className:`font-medium text-gray-900 ${s?"text-xs":"text-sm"}`,children:e.unidad==="moneda"?new Intl.NumberFormat(t.formatoNumero,{style:"currency",currency:t.moneda,minimumFractionDigits:0,maximumFractionDigits:0}).format(e.objetivo):`${e.objetivo} ${e.unidad==="porcentaje"?"%":""}`})]}),jsx("div",{className:"w-full bg-gray-200 rounded-full h-2",children:jsx("div",{className:`h-2 rounded-full transition-all duration-500 ${e.estado==="saludable"?"bg-green-500":e.estado==="precaucion"?"bg-yellow-500":"bg-red-500"}`,style:{width:`${b}%`}})}),jsxs("div",{className:"flex justify-between mt-1",children:[jsx("span",{className:"text-xs text-gray-500",children:"0"}),jsxs("span",{className:"text-xs text-gray-500",children:[b.toFixed(0),"%"]})]})]}),t.mostrarGraficos&&e.datosTemporales.length>0&&jsxs("div",{className:"border-t border-gray-100 pt-4",children:[jsxs("div",{className:"flex items-center justify-between mb-2",children:[jsx("span",{className:`text-gray-600 font-medium ${s?"text-xs":"text-sm"}`,children:t.idioma==="es"?"Tendencia (30 d\xEDas)":"Trend (30 days)"}),jsx("button",{onClick:E=>{E.stopPropagation(),x(!u);},className:"p-1 text-gray-400 hover:text-gray-600 transition-colors",children:u?jsx(EyeOff,{className:"w-3 h-3"}):jsx(Eye,{className:"w-3 h-3"})})]}),u&&jsx("div",{className:"flex justify-center",children:jsx(Ct,{datos:e.datosTemporales,color:p,altura:s?40:60,mostrarPuntos:true})})]}),!s&&jsx("div",{className:"mt-4 pt-4 border-t border-gray-100",children:jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[jsxs("div",{children:[jsx("span",{className:"text-gray-500",children:t.idioma==="es"?"Actual":"Current"}),jsx("div",{className:"font-medium text-gray-900",children:e.unidad==="moneda"?new Intl.NumberFormat(t.formatoNumero,{style:"currency",currency:t.moneda,minimumFractionDigits:0,maximumFractionDigits:0}).format(e.tendencia.actual):`${e.tendencia.actual.toFixed(1)} ${e.unidad==="porcentaje"?"%":""}`})]}),jsxs("div",{children:[jsx("span",{className:"text-gray-500",children:t.idioma==="es"?"Anterior":"Previous"}),jsx("div",{className:"font-medium text-gray-900",children:e.unidad==="moneda"?new Intl.NumberFormat(t.formatoNumero,{style:"currency",currency:t.moneda,minimumFractionDigits:0,maximumFractionDigits:0}).format(e.tendencia.anterior):`${e.tendencia.anterior.toFixed(1)} ${e.unidad==="porcentaje"?"%":""}`})]})]})}),jsxs("div",{className:"mt-2 text-xs text-gray-400 flex items-center space-x-1",children:[jsx(Clock,{className:"w-3 h-3"}),jsxs("span",{children:[t.idioma==="es"?"Actualizado: ":"Updated: ",new Date(e.ultimaActualizacion).toLocaleString(t.formatoNumero)]})]})]})}function kt({metricas:e,posicionCaja:t,proyecciones:s=[],alertas:o=[],configuracion:m={},filtrosPeriodo:f,compacto:u=false,soloLectura:x=false,alCargarDatos:g,alCambiarPerio